本文实例讲述了JavaScript模拟深蓝vs卡斯帕罗夫的国际象棋对局示例。分享给大家供大家参考。具体如下:

/**
 * JavaScript macro to run a chess game, showing board, pieces and moves played.
 *
 * Author: Todd Whiteman
 * Revision: 1.0
 * Date: October 2012
 */

var board = "    Garry Kasparov                                                             \n  8║";


var gameintro = [
  "Site: Philadelphia, PA USA                                                         \n  Date: 1996.02.10                                                              \n  Round: 1                                                                  \n  White: Deep Blue                                                              \n  Black: Kasparov, Garry                                                           \n  Result: 1-0                                                                \n  Opening: Sicilian Defense 2.c3                                                       \n  Annotator: Wheeler, David A.                                                        \n  ",                                                                    

  "This game is world-famous, because it was the first game                                          \n  won by a computer against a reigning world champion under                                         \n  normal chess tournament conditions (in particular, normal time controls).                                 \n  ",                                                                    

  "Deep Blue was a computer developed by IBM to win against Kasparov.                                     \n  Deep Blue won this game, but Kasparov rebounded over the following 5                                    \n  games to win 3 and draw 2, soundly beating Deep Blue in the 1996 match.                                  \n  ",                                                                    

  "In the 1997 rematch, Deep Blue managed to win the entire match.                                      \n  Garry Kasparov is considered to be one of the greatest human chess players                                 \n  of all time, so both this single game and the later win of a match showed                                 \n  that computer-based chess had truly arrived at the pinnacle of chess play.                                 \n  "
];


var movelist = "1. e2e4 c7c5                                                                  \n2. c2c3                                                                    \n{It's more common to play 2. Nf3, but Kasparov has deep experience with                                    \nthat line, so white's opening book goes in a different direction.}                                       \n                                                                        \n2.... d7d5                                                                   \n3. e4xd5 Qd8xd5                                                                \n4. d2d4 Ng8f6                                                                 \n5. Ng1f3 Bc8g4                                                                 \n6. Bf1e2 e7e6                                                                 \n7. h2h3 Bg4h5                                                                 \n8. e1g1h1f1 Nb8c6                                                               \n9. Bc1e3 c5xd4                                                                 \n10. c3xd4 Bf8b4                                                                \n{A more common move here is Be7. This was a new approach by Kasparov,                                     \ndeveloping the bishop in an unusual way. Whether or not it's a good                                      \napproach is debated. After this move, the computer left its opening book                                    \nand began calculating its next move.}                                                     \n                                                                        \n11. a2a3 Bb4a5                                                                 \n12. Nb1c3 Qd5d6                                                                \n13. Nc3b5 Qd6e7";



/******************************
 * Komodo macro contents begin.
 ******************************/

var moveDisplayTime = 2000; // milliseconds
var messageDisplayTime = 6000; // milliseconds

// Indicator values, range from 8..30 - though Komodo uses a lot of these
// numbers for special purposes.
var indicWhiteSquare = 10;
var indicBlackSquare = 11;
var indicMoveFrom = 12;
var indicMoveTo = 13;

/**
 * Highlight the black/white chess squares.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 */
function HighlightSquares(scimoz) {
  for (var line=1; line < 9; line++) {
    for (var col=6; col < 21; col+=2) {
      var pos = scimoz.findColumn(line, col);
      var charlength = scimoz.positionAfter(pos) - pos;
      var isBlackSquare = (line % 2) == 0 "");
      }
    }
    // Format the message.
    var textUtils = Components.classes["@activestate.com/koTextUtils;1"]
              .getService(Components.interfaces.koITextUtils);
    var lines = message.split("\n");
    for (var i=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");
    }
    // Display new message - limit lines to 
    for (var i=0; i < lines.length; i++) {
      var line = lines[i];
      if (i+1 >= scimoz.lineCount) {
        scimoz.currentPos = scimoz.length;
        scimoz.newLine();
      }
      var pos = scimoz.findColumn(i+1, 26);
      var lineStart = scimoz.positionFromLine(i+1);
      var lineDiff = pos - lineStart;
      while (lineDiff < 26) {
        // Add space padding to the start of the line.
        line = " " + line;
        lineDiff += 1;
      }
      scimoz.currentPos = pos;
      scimoz.addText(ko.stringutils.bytelength(line), line);
    }
  } catch(ex) {
    // Exception handling - show problems to the user.
    alert("Error: " + ex + "\n\n" + ex.stack.toString());
  }
}

/**
 * Play the introduction strings.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 */
function PlayIntro(scimoz, callback) {
  for (var i=0; i < gameintro.length; i++) {
    setTimeout(DisplayMessage, messageDisplayTime * i, scimoz, gameintro[i], i == 0);
  }
  setTimeout(callback, (messageDisplayTime * gameintro.length), scimoz);
}

/**
 * Highlight the chess move.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 * @param {Integer} indicator - The indicator to use for highlighting.
 * @param {Integer} pos - The position to highlight.
 */
function HighlightMove(scimoz, indicator, pos) {
  scimoz.indicatorCurrent = indicator;
  scimoz.indicatorClearRange(0, scimoz.length);
  var charlength = scimoz.positionAfter(pos) - pos;
  scimoz.indicatorFillRange(pos, charlength);
}

/**
 * Determine the position in the document for the co-ordinates.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 * @param {String} move - The coded chess move to make.
 */
function GetBoardPosition(scimoz, chesscode) {
  var col = chesscode.charCodeAt(0) - 'a'.charCodeAt(0);
  var row = '8'.charCodeAt(0) - chesscode.charCodeAt(1);
  return scimoz.findColumn(row+1, (col*2)+6);
}  

/**
 * Make the given chess move.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 * @param {String} move - The coded chess move to make.
 */
function MakeMove(scimoz, move) {
  var isTake = (move.indexOf("x") >= 0);
  move = move.replace("x", "");
  if (move.length == 8) {
    // Special double move for castling.
    MakeMove(scimoz, move.substr(4));
    move = move.substr(0, 4);
  }
  if (move.length >= 5) {
    move = move.substr(1);
  }
  var fromPos = 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);
  var toPos = GetBoardPosition(scimoz, move.substr(2));
  scimoz.targetStart = toPos;
  scimoz.targetEnd = scimoz.positionAfter(toPos);
  scimoz.replaceTarget(piece.length, piece);
  HighlightSquares(scimoz);
  HighlightMove(scimoz, indicMoveTo, toPos);
  // Clear old messages.
  DisplayMessage(scimoz, "", false);
}  

/**
 * Make the given chess move.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 * @param {String} move - The coded chess move to make.
 */
function ProcessMove(scimoz, move) {
  move = move.replace("!", "");
  move = move.replace("", "");
  move = move.replace("+", "");
  var match = move.match(/(\d+)\.\s*([\w\.]+)\s*(\w+)"Unrecognized move: " + move + "\n");
  }
  var moveWhite = match[2];
  var moveBlack = match[3];
  if (moveWhite[0] != ".") {
    MakeMove(scimoz, moveWhite);
  } else {
    MakeMove(scimoz, moveBlack);
    return;
  }
  setTimeout(MakeMove, moveDisplayTime, scimoz, moveBlack);
}

/**
 * Play all of the chess moves and display the move commentary.
 *
 * @param {Components.interfaces.ISciMoz} scimoz - The editor control.
 */
function PlayMoves(scimoz) {
  var moves = movelist.split("\n");
  var state = "move";
  var message = "";
  var nexttimeout = 0;
  for (var i=0; i < moves.length; i++) {
    var move = ko.stringutils.strip(moves[i]);
    if (!move) {
      continue;
    }
    switch (state) {
      case "move":
        if (move.match(/^[0-9]+\./)) {
          // Piece to move.
          setTimeout(ProcessMove, nexttimeout, scimoz, move);
          nexttimeout += moveDisplayTime;
          nexttimeout += moveDisplayTime;
          break;
        } else if (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;
    }
  }
}

/**
 * Play the chess game in the given editor.
 *
 * @param {Components.interfaces.koIScintillaView} view - The editor view.
 */
function PlayChess(view) {
  try {
    /**
     * @type {Components.interfaces.ISciMoz} - The editor control.
     */
    var scimoz = view.scimoz;
    DrawInitialBoard(scimoz);
    PlayIntro(scimoz, PlayMoves);
  } catch(ex) {
    // Exception handling - show problems to the user.
    alert("Error: " + ex + "\n\n" + ex.stack.toString());
  }
}

// Create a new text file asynchronously and start playing chess.
ko.views.manager.doNewViewAsync("Text", "editor", PlayChess);

希望本文所述对大家的javascript程序设计有所帮助。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。