JavaScript模拟深蓝vs卡斯帕罗夫的国际象棋对局示例
本文实例讲述了JavaScript模拟深蓝vs卡斯帕罗夫的国际象棋对局示例。分享给大家供大家参考。具体如下:
/**
*JavaScriptmacrotorunachessgame,showingboard,piecesandmovesplayed.
*
*Author:ToddWhiteman
*Revision:1.0
*Date:October2012
*/
varboard="\
GarryKasparov\n\
8║♜♞♝♛♚♝♞♜Move:0\n\
7║♟♟♟♟♟♟♟♟\n\
6║\n\
5║\n\
4║\n\
3║\n\
2║♙♙♙♙♙♙♙♙\n\
1║♖♘♗♕♔♗♘♖\n\
╚═══════════════\n\
abcdefgh\n\
DeepBlue\n\
";
vargameintro=[
"Site:Philadelphia,PAUSA\n\
Date:1996.02.10\n\
Round:1\n\
White:DeepBlue\n\
Black:Kasparov,Garry\n\
Result:1-0\n\
Opening:SicilianDefense2.c3\n\
Annotator:Wheeler,DavidA.\n\
",
"Thisgameisworld-famous,becauseitwasthefirstgame\n\
wonbyacomputeragainstareigningworldchampionunder\n\
normalchesstournamentconditions(inparticular,normaltimecontrols).\n\
",
"DeepBluewasacomputerdevelopedbyIBMtowinagainstKasparov.\n\
DeepBluewonthisgame,butKasparovreboundedoverthefollowing5\n\
gamestowin3anddraw2,soundlybeatingDeepBlueinthe1996match.\n\
",
"Inthe1997rematch,DeepBluemanagedtowintheentirematch.\n\
GarryKasparovisconsideredtobeoneofthegreatesthumanchessplayers\n\
ofalltime,soboththissinglegameandthelaterwinofamatchshowed\n\
thatcomputer-basedchesshadtrulyarrivedatthepinnacleofchessplay.\n\
"
];
varmovelist="\
1.e2e4c7c5\n\
2.c2c3\n\
{It'smorecommontoplay2.Nf3,butKasparovhasdeepexperiencewith\n\
thatline,sowhite'sopeningbookgoesinadifferentdirection.}\n\
\n\
2....d7d5\n\
3.e4xd5Qd8xd5\n\
4.d2d4Ng8f6\n\
5.Ng1f3Bc8g4\n\
6.Bf1e2e7e6\n\
7.h2h3Bg4h5\n\
8.e1g1h1f1Nb8c6\n\
9.Bc1e3c5xd4\n\
10.c3xd4Bf8b4\n\
{AmorecommonmovehereisBe7.ThiswasanewapproachbyKasparov,\n\
developingthebishopinanunusualway.Whetherornotit'sagood\n\
approachisdebated.Afterthismove,thecomputerleftitsopeningbook\n\
andbegancalculatingitsnextmove.}\n\
\n\
11.a2a3Bb4a5\n\
12.Nb1c3Qd5d6\n\
13.Nc3b5Qd6e7?!\n\
{Thisallowswhitetomakeitspiecesmoreactive.\n\
Othermoves,whichwouldprobablybebetter,includeQb8andQd5.}\n\
\n\
14.Nf3e5!Bh5xe2\n\
15.Qd1xe2e8g8h8f8\n\
16.Ra1c1Ra8c8\n\
17.Be3g5\n\
{Blacknowhasaproblem,especiallywiththepinnedknightonf6.}\n\
\n\
17....Ba5b6\n\
18.Bg5xf6g7xf6\n\
{Kasparovavoids...Qxf6?becausewhitewouldgainmaterialwith19.Nd7.\n\
NotethatKasparov'skingisnowfarmoreexposed.}\n\
\n\
19.Ne5c4!Rf8d8\n\
20.Nc4xb6!a7xb6\n\
21.Rf1d1f6f5\n\
22.Qe2e3!\n\
{Thisisanexcellentplaceforthewhitequeen.}\n\
\n\
22...Qe7f6\n\
23.d4d5!\n\
{Kasparovcommentedthathemighthaveofferedthispawn\n\
sacrificehimselfinthisposition,sinceithurtblack'spawn\n\
structure,openeduptheboard,andblack'sexposedkingsuggested\n\
thattherewasprobablyawaytoexploittheresult.\n\
Kasparovhasbeenattackingthed4pawn,andthecomputerwisely\n\
decidedtoadvanceitforanattackinsteadoftryingtodefendit.}\n\
\n\
23...Rd8xd5\n\
24.Rd1xd5e6xd5\n\
25.b2b3!Kg8h8?\n\
{Kasparovattemptstoprepareacounter-attack,bypreparingto\n\
movehisrooktofileg,butitwon'twork.\n\
Burgesssuggeststhat25....Ne7Rxc8+wouldhavebetter,though\n\
whitewouldstillhavesomeadvantage.\n\
Indeed,afterthispointonit'sdifficulttoidentify\n\
anymovethatwilldramaticallyhelpblack.}\n\
\n\
26.Qe3xb6Rc8g8\n\
27.Qb6c5d5d4\n\
28.Nb5d6f5f4\n\
29.Nd6xb7\n\
{Thisisavery'computerish'/materialisticmove;whiteisgrabbing\n\
anundevelopedpawnforasmallgaininmaterial.\n\
However,thecomputerhasnotidentifiedanythreatofcheckmateor\n\
otherrisksfromblack,soitsimplyacquiresthematerial.}\n\
\n\
29....Nc6e5\n\
30.Qc5d5\n\
{Themove30.Qxd4??wouldbeterrible,becauseNf3+\n\
wouldwinthewhitequeen.}\n\
\n\
30....f4f3\n\
31.g2g3Ne5d3\n\
{Themove31...Qf4won'twork,becauseof32.Rc8!Qg533.Rc5!}\n\
\n\
32.Rc1c7Rg8e8\n\
{Kasparovisattacking,butthecomputerhascorrectlydeterminedthat\n\
theattackisnotarealthreat.}\n\
\n\
33.Nb7d6Re8e1+\n\
34.Kg1h2Nd3xf2\n\
35.Nd6xf7+Kh8g7\n\
36.Nf7g5Kg7h6\n\
37.Rc7xh7+\n\
{Kasparovresigns-expecting...Kg638.Qg8+Kf5Nxf3andwhite's\n\
strengthisoverwhelming.Whitewillhavelotsofwaystodefeatblack,\n\
whileblackhasnorealwaytoattackwhite.}\n\
";
/******************************
*Komodomacrocontentsbegin.
******************************/
varmoveDisplayTime=2000;//milliseconds
varmessageDisplayTime=6000;//milliseconds
//Indicatorvalues,rangefrom8..30-thoughKomodousesalotofthese
//numbersforspecialpurposes.
varindicWhiteSquare=10;
varindicBlackSquare=11;
varindicMoveFrom=12;
varindicMoveTo=13;
/**
*Highlighttheblack/whitechesssquares.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*/
functionHighlightSquares(scimoz){
for(varline=1;line<9;line++){
for(varcol=6;col<21;col+=2){
varpos=scimoz.findColumn(line,col);
varcharlength=scimoz.positionAfter(pos)-pos;
varisBlackSquare=(line%2)==0?(col%4)==0:(col%4)==2;
if(isBlackSquare){
scimoz.indicatorCurrent=indicBlackSquare;
}else{
scimoz.indicatorCurrent=indicWhiteSquare;
}
scimoz.indicatorFillRange(pos,charlength);
}
}
}
/**
*Drawthestartingboardlayout.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*/
functionDrawInitialBoard(scimoz){
//Setboardstyling.
scimoz.setMarginWidthN(0,0);//Removethelinenumbermargin.
scimoz.caretStyle=scimoz.CARETSTYLE_INVISIBLE;//Hidethecaret
scimoz.indicSetStyle(indicWhiteSquare,scimoz.INDIC_STRAIGHTBOX);//SeeScintilladocsforothers
scimoz.indicSetAlpha(indicWhiteSquare,40);
scimoz.indicSetOutlineAlpha(indicWhiteSquare,30);
scimoz.indicSetFore(indicWhiteSquare,0xFFFFFF);//ColourisBGRformat!!
scimoz.indicSetStyle(indicBlackSquare,scimoz.INDIC_STRAIGHTBOX);//SeeScintilladocsforothers
scimoz.indicSetAlpha(indicBlackSquare,40);
scimoz.indicSetOutlineAlpha(indicBlackSquare,30);
scimoz.indicSetFore(indicBlackSquare,0x000000);//Colourblack-it'sBGRformat!!
scimoz.indicSetStyle(indicMoveFrom,scimoz.INDIC_ROUNDBOX);//SeeScintilladocsforothers
scimoz.indicSetAlpha(indicMoveFrom,40);
scimoz.indicSetOutlineAlpha(indicMoveFrom,90);
scimoz.indicSetFore(indicMoveFrom,0x00EEEE);//ColourisBGRformat!!
scimoz.indicSetStyle(indicMoveTo,scimoz.INDIC_ROUNDBOX);//SeeScintilladocsforothers
scimoz.indicSetAlpha(indicMoveTo,40);
scimoz.indicSetOutlineAlpha(indicMoveTo,90);
scimoz.indicSetFore(indicMoveTo,0x00EEEE);//ColourisBGRformat!!
//Addtheboardtext.
scimoz.addText(ko.stringutils.bytelength(board),board);
//Makeitalargeboard-validrangeis+-20.
scimoz.zoom=15;
//Highlighttheblack/whitesquares.
HighlightSquares(scimoz);
}
/**
*Displaythegivenmessagebesidetheboard.Clearsanypreviousmessage.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*@param{String}message-Themessagetodisplay.
*/
functionDisplayMessage(scimoz,message,nosplit){
try{
//Clearexistingmessagelines.
for(varline=1;line<scimoz.lineCount;line++){
varpos=scimoz.findColumn(line,26);
vareolpos=scimoz.getLineEndPosition(line);
if(eolpos>pos){
scimoz.targetStart=pos;
scimoz.targetEnd=eolpos;
scimoz.replaceTarget(0,"");
}
}
//Formatthemessage.
vartextUtils=Components.classes["@activestate.com/koTextUtils;1"]
.getService(Components.interfaces.koITextUtils);
varlines=message.split("\n");
for(vari=0;i<lines.length;i++){
lines[i]=ko.stringutils.strip(lines[i]);
}
if(!nosplit){
message=lines.join("");
message=textUtils.break_up_lines(message,26);
lines=message.split("\n");
}
//Displaynewmessage-limitlinesto
for(vari=0;i<lines.length;i++){
varline=lines[i];
if(i+1>=scimoz.lineCount){
scimoz.currentPos=scimoz.length;
scimoz.newLine();
}
varpos=scimoz.findColumn(i+1,26);
varlineStart=scimoz.positionFromLine(i+1);
varlineDiff=pos-lineStart;
while(lineDiff<26){
//Addspacepaddingtothestartoftheline.
line=""+line;
lineDiff+=1;
}
scimoz.currentPos=pos;
scimoz.addText(ko.stringutils.bytelength(line),line);
}
}catch(ex){
//Exceptionhandling-showproblemstotheuser.
alert("Error:"+ex+"\n\n"+ex.stack.toString());
}
}
/**
*Playtheintroductionstrings.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*/
functionPlayIntro(scimoz,callback){
for(vari=0;i<gameintro.length;i++){
setTimeout(DisplayMessage,messageDisplayTime*i,scimoz,gameintro[i],i==0);
}
setTimeout(callback,(messageDisplayTime*gameintro.length),scimoz);
}
/**
*Highlightthechessmove.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*@param{Integer}indicator-Theindicatortouseforhighlighting.
*@param{Integer}pos-Thepositiontohighlight.
*/
functionHighlightMove(scimoz,indicator,pos){
scimoz.indicatorCurrent=indicator;
scimoz.indicatorClearRange(0,scimoz.length);
varcharlength=scimoz.positionAfter(pos)-pos;
scimoz.indicatorFillRange(pos,charlength);
}
/**
*Determinethepositioninthedocumentfortheco-ordinates.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*@param{String}move-Thecodedchessmovetomake.
*/
functionGetBoardPosition(scimoz,chesscode){
varcol=chesscode.charCodeAt(0)-'a'.charCodeAt(0);
varrow='8'.charCodeAt(0)-chesscode.charCodeAt(1);
returnscimoz.findColumn(row+1,(col*2)+6);
}
/**
*Makethegivenchessmove.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*@param{String}move-Thecodedchessmovetomake.
*/
functionMakeMove(scimoz,move){
varisTake=(move.indexOf("x")>=0);
move=move.replace("x","");
if(move.length==8){
//Specialdoublemoveforcastling.
MakeMove(scimoz,move.substr(4));
move=move.substr(0,4);
}
if(move.length>=5){
move=move.substr(1);
}
varfromPos=GetBoardPosition(scimoz,move.substr(0,2));
scimoz.targetStart=fromPos;
scimoz.targetEnd=scimoz.positionAfter(fromPos);
piece=scimoz.getTextRange(fromPos,scimoz.targetEnd);
scimoz.replaceTarget("".length,"");
HighlightMove(scimoz,indicMoveFrom,fromPos);
vartoPos=GetBoardPosition(scimoz,move.substr(2));
scimoz.targetStart=toPos;
scimoz.targetEnd=scimoz.positionAfter(toPos);
scimoz.replaceTarget(piece.length,piece);
HighlightSquares(scimoz);
HighlightMove(scimoz,indicMoveTo,toPos);
//Clearoldmessages.
DisplayMessage(scimoz,"",false);
}
/**
*Makethegivenchessmove.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*@param{String}move-Thecodedchessmovetomake.
*/
functionProcessMove(scimoz,move){
move=move.replace("!","");
move=move.replace("?","");
move=move.replace("+","");
varmatch=move.match(/(\d+)\.\s*([\w\.]+)\s*(\w+)?/);
if(!match.length){
dump("Unrecognizedmove:"+move+"\n");
}
varmoveWhite=match[2];
varmoveBlack=match[3];
if(moveWhite[0]!="."){
MakeMove(scimoz,moveWhite);
}else{
MakeMove(scimoz,moveBlack);
return;
}
setTimeout(MakeMove,moveDisplayTime,scimoz,moveBlack);
}
/**
*Playallofthechessmovesanddisplaythemovecommentary.
*
*@param{Components.interfaces.ISciMoz}scimoz-Theeditorcontrol.
*/
functionPlayMoves(scimoz){
varmoves=movelist.split("\n");
varstate="move";
varmessage="";
varnexttimeout=0;
for(vari=0;i<moves.length;i++){
varmove=ko.stringutils.strip(moves[i]);
if(!move){
continue;
}
switch(state){
case"move":
if(move.match(/^[0-9]+\./)){
//Piecetomove.
setTimeout(ProcessMove,nexttimeout,scimoz,move);
nexttimeout+=moveDisplayTime;
nexttimeout+=moveDisplayTime;
break;
}elseif(move[0]=="{"){
state="message";
message="";
move=move.substr(1);
//Fallthrough.
}else{
continue;
}
case"message":
if(move.indexOf("}")>=0){
move=move.substring(0,move.indexOf("}"));
state="move";
}
if(message)message+="";
message+=move;
if(state=="move"){
setTimeout(DisplayMessage,nexttimeout,scimoz,message,false);
message="";
nexttimeout+=messageDisplayTime;
}
break;
}
}
}
/**
*Playthechessgameinthegiveneditor.
*
*@param{Components.interfaces.koIScintillaView}view-Theeditorview.
*/
functionPlayChess(view){
try{
/**
*@type{Components.interfaces.ISciMoz}-Theeditorcontrol.
*/
varscimoz=view.scimoz;
DrawInitialBoard(scimoz);
PlayIntro(scimoz,PlayMoves);
}catch(ex){
//Exceptionhandling-showproblemstotheuser.
alert("Error:"+ex+"\n\n"+ex.stack.toString());
}
}
//Createanewtextfileasynchronouslyandstartplayingchess.
ko.views.manager.doNewViewAsync("Text","editor",PlayChess);
希望本文所述对大家的javascript程序设计有所帮助。