DIV CSS 佈局教程網

JavaScript 模擬深藍對卡斯帕羅夫的國際象棋對局
編輯:關於JavaScript     

這份程式碼出自 Komodo 編輯器,用途是把 1996 年「深藍 vs 卡斯帕羅夫」第一局的棋譜,以棋盤動畫的形式逐步演出來,同時在棋盤右側顯示每一步的評註。

/**
 * JavaScript macro to run a chess game, showing board, pieces and moves played.
 * Author: Todd Whiteman
 */
var board = "\ Garry Kasparov \n\
 8║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ Move: 0 \n\
 7║♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ \n\
 6║ \n\
 5║ \n\
 4║ \n\
 3║ \n\
 2║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ \n\
 1║♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖ \n\
 ╚═══════════════ \n\
 a b c d e f g h \n\
 Deep Blue \n";

var gameintro = [
    "Site: Philadelphia, PA USA\nDate: 1996.02.10\nRound: 1\n" +
    "White: Deep Blue\nBlack: Kasparov, Garry\nResult: 1-0\n" +
    "Opening: Sicilian Defense 2.c3\n",

    "本局世界知名,因為這是電腦在正常比賽規則(含正常用時限制)下,\n\
     第一次擊敗現任世界冠軍的對局。\n",

    "Deep Blue 是 IBM 為擊敗卡斯帕羅夫而開發的電腦。\n\
     它贏下了這局,但卡斯帕羅夫隨後連扳三局並和兩局,以 4:2 贏得 1996 年的比賽。\n",

    "1997 年的復賽中,Deep Blue 拿下整場比賽。\n\
     卡斯帕羅夫被視為史上最偉大的人類棋手之一,\n\
     因此這單局與後續的勝出,都象徵電腦象棋真正抵達了巔峰。\n"
];

var movelist = "\
 1. e2e4 c7c5 \n\
 2. c2c3 \n\
 {較常見的是 2. Nf3,但卡斯帕羅夫在該變化上經驗深厚,\n\
  因此白方的开局書選擇了另一個方向。} \n\
 2.... d7d5 \n\
 3. e4xd5 Qd8xd5 \n\
 4. d2d4 Ng8f6 \n\
 5. Ng1f3 Bc8g4 \n\
 6. Bf1e2 e7e6 \n\
 7. h2h3 Bg4h5 \n\
 8. e1g1 Nb8c6 \n\
 9. Bc1e3 c5xd4 \n\
 10. c3xd4 Bf8b4 \n\
 {更常見的是 Be7。這是卡斯帕羅夫的新 approach,以不尋常的方式發展主教。\n\
  好壞仍有爭議。走完這步後,電腦離開开局書,開始自行計算。} \n\
 11. a2a3 Bb4a5 \n\
 12. Nb1c3 Qd5d6 \n\
 13. Nc3b5 Qd6e7?! \n\
 {這讓白方得以更積極地調動子力。較好的應手應是 Qb8 或 Qd5。} \n\
 14. Nf3e5! Bh5xe2 \n\
 15. Qd1xe2 e8f8 \n\
 16. Ra1c1 Ra8c8 \n\
 17. Be3g5 \n\
 {黑方開始有麻煩,尤其是 f6 上被釘住的騎士。} \n\
 17.... Ba5b6 \n\
 18. Bg5xf6 g7xf6 \n\
 {卡斯帕羅夫避開 ...Qxf6?!,因為白方 19. Nd7 可掠奪子力。\n\
  注意此時黑王已相當暴露。} \n\
 19. Ne5c4! Rf8d8 \n\
 20. Nc4xb6! a7xb6 \n\
 21. Rf1d1 f6f5 \n\
 22. Qe2e3! \n\
 {白后到達極佳的位置。} \n\
 22... Qe7f6 \n\
 23. d4d5! \n\
 {卡斯帕羅夫自己說過,他可能也會在此犠牲這個兵:\n\
  它破壞黑方兵形、開啟戰線,而黑王暴露使得取得補償的可能性很高。\n\
  黑方一直在攻擊 d4 兵,電腦明智地選擇推進發動攻勢,而非消極守備。} \n\
 23... Rd8xd5 \n\
 24. Rd1xd5 e6xd5 \n\
 25. b2b3! Kg8h8?! \n\
 {卡斯帕羅夫試圖準備反擊,想把車調到 g 線,但行不通。\n\
  此後很難再找到能大幅改善局勢的著法。} \n\
 26. Qe3xb6 Rc8g8 \n\
 27. Qb6c5 d5d4 \n\
 28. Nb5d6 f5f4 \n\
 29. Nd6xb7 \n\
 {這是非常「電腦式」的著法:白方可愛地掠奪一個未發展的兵,\n\
  取得小幅實質優勢。由於電腦未偵測到任何將殺或反擊風險,就單純地吃子。} \n\
 29.... Nc6e5 \n\
 30. Qc5d5 \n\
 {30. Qxd4?? 是災難,因為 ...Nf3+ 會白送后。} \n\
 30.... f4f3 \n\
 31. g2g3 Ne5d3 \n\
 {31... Qf4 行不通,因為 32. Rc8! Qg5 33. Rc5!} \n\
 32. Rc1c7 Rg8e8 \n\
 {黑方在進攻,但電腦正確判斷出這威脅並不真實。} \n\
 33. Nb7d6 Re8e1+ \n\
 34. Kg1h2 Nd3xf2 \n\
 35. Nd6xf7+ Kh8g7 \n\
 36. Nf7g5 Kg7h6 \n\
 37. Rc7xh7+ \n\
 {卡斯帕羅夫認負——預期 ...Kg6 38. Qg8+ Kf5 及後續的攻勢,\n\
  白方可獲得的優勢壓倒性,黑方則無真正的反擊手段。} \n";

var moveDisplayTime = 2000;   // 每步顯示時間(毫秒)
var messageDisplayTime = 6000;
var indicWhiteSquare = 10, indicBlackSquare = 11;
var indicMoveFrom = 12, indicMoveTo = 13;

/** 標示棋盤上的黑白格 */
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 ? (col % 4) == 0 : (col % 4) == 2;
            scimoz.indicatorCurrent = isBlackSquare ? indicBlackSquare : indicWhiteSquare;
            scimoz.indicatorFillRange(pos, charlength);
        }
    }
}

/** 繪製初始棋盤並設定樣式 */
function DrawInitialBoard(scimoz) {
    scimoz.setMarginWidthN(0, 0);                    // 隱藏行號邊欄
    scimoz.caretStyle = scimoz.CARETSTYLE_INVISIBLE; // 隱藏游標
    scimoz.indicSetStyle(indicWhiteSquare, scimoz.INDIC_STRAIGHTBOX);
    scimoz.indicSetAlpha(indicWhiteSquare, 40);
    scimoz.indicSetOutlineAlpha(indicWhiteSquare, 30);
    scimoz.indicSetFore(indicWhiteSquare, 0xFFFFFF); // 顏色為 BGR 格式
    scimoz.indicSetStyle(indicBlackSquare, scimoz.INDIC_STRAIGHTBOX);
    scimoz.indicSetAlpha(indicBlackSquare, 40);
    scimoz.indicSetOutlineAlpha(indicBlackSquare, 30);
    scimoz.indicSetFore(indicBlackSquare, 0x000000);
    scimoz.indicSetStyle(indicMoveFrom, scimoz.INDIC_ROUNDBOX);
    scimoz.indicSetAlpha(indicMoveFrom, 40);
    scimoz.indicSetOutlineAlpha(indicMoveFrom, 90);
    scimoz.indicSetFore(indicMoveFrom, 0x00EEEE);
    scimoz.indicSetStyle(indicMoveTo, scimoz.INDIC_ROUNDBOX);
    scimoz.indicSetAlpha(indicMoveTo, 40);
    scimoz.indicSetOutlineAlpha(indicMoveTo, 90);
    scimoz.indicSetFore(indicMoveTo, 0x00EEEE);

    scimoz.addText(ko.stringutils.bytelength(board), board);
    scimoz.zoom = 15;      // 放大棋盤,有效範圍 +-20
    HighlightSquares(scimoz);
}

/** 在棋盤右側顯示評註,先清除舊訊息 */
function DisplayMessage(scimoz, message, nosplit) {
    try {
        for (var line = 1; line < scimoz.lineCount; line++) {
            var pos = scimoz.findColumn(line, 26);
            var eolpos = scimoz.getLineEndPosition(line);
            if (eolpos > pos) {
                scimoz.targetStart = pos;
                scimoz.targetEnd = eolpos;
                scimoz.replaceTarget(0, "");
            }
        }
        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 = textUtils.break_up_lines(lines.join(" "), 26);
            lines = message.split("\n");
        }
        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) { line = " " + line; lineDiff += 1; }  // 左側補空格對齊
            scimoz.currentPos = pos;
            scimoz.addText(ko.stringutils.bytelength(line), line);
        }
    } catch (ex) {
        alert("Error: " + ex + "\n\n" + ex.stack.toString());
    }
}

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);
}

function HighlightMove(scimoz, indicator, pos) {
    scimoz.indicatorCurrent = indicator;
    scimoz.indicatorClearRange(0, scimoz.length);
    var charlength = scimoz.positionAfter(pos) - pos;
    scimoz.indicatorFillRange(pos, charlength);
}

/** 把棋譜座標(如 "e4")換算成文件中的字元位置 */
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);
}

/** 執行一步棋:把棋子從起點「搬」到終點 */
function MakeMove(scimoz, move) {
    move = move.replace("x", "");              // 去掉吃子記號
    if (move.length == 8) {                    // 王車易位需處理兩段
        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);
    var piece = scimoz.getTextRange(fromPos, scimoz.targetEnd);
    scimoz.replaceTarget(1, " ");              // 起點清空
    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);

    DisplayMessage(scimoz, "", false);         // 清除舊評註
}

function ProcessMove(scimoz, move) {
    move = move.replace("!", "").replace("?", "").replace("+", "");
    var match = move.match(/(\d+)\.\s*([\w\.]+)\s*(\w+)\?/);
    if (!match.length) { dump("Unrecognized move: " + move + "\n"); return; }
    var moveWhite = match[2], moveBlack = match[3];
    if (moveWhite[0] != ".") {
        MakeMove(scimoz, moveWhite);
    } else {
        MakeMove(scimoz, moveBlack);
        return;
    }
    setTimeout(MakeMove, moveDisplayTime, scimoz, moveBlack);
}

/** 依序播放所有棋步與評註 */
function PlayMoves(scimoz) {
    var moves = movelist.split("\n");
    var state = "move", message = "", 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]+\./)) {
                    setTimeout(ProcessMove, nexttimeout, scimoz, move);
                    nexttimeout += moveDisplayTime * 2;   // 白黑各一步
                    break;
                } else if (move[0] == "{") {
                    state = "message"; message = ""; move = move.substr(1);
                } else { continue; }
                // 故意不加 break,續落到 message 處理
            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;
        }
    }
}

function PlayChess(view) {
    try {
        var scimoz = view.scimoz;
        DrawInitialBoard(scimoz);
        PlayIntro(scimoz, PlayMoves);
    } catch (ex) {
        alert("Error: " + ex + "\n\n" + ex.stack.toString());
    }
}

// 非同步建立新文字檔並開始播放
ko.views.manager.doNewViewAsync("Text", "editor", PlayChess);

這個例子有意思的地方

它把「文字編輯器」當成棋盤畫布使用:棋盤以 Unicode 棋子字元組成一塊等寬字串,一格佔兩個字元寬(棋子加空格),因此 GetBoardPosition 才能用 (col * 2) + 6 算出水平位置。走子時則是「把起點的字元讀出來、清空起點、寫到終點」,再靠 Scintilla 的 indicator 機制在起點與終點畫上不同顏色的標記。

另一個值得欣賞的細節是 PlayMoves 的狀態機:以 state 變數在「讀棋步」與「讀評註」兩個模式間切換,用大括號 { } 界定評註範圍,並透過 setTimeout 排出整條時間軸。這種「用 setTimeout 排隊」的做法在早期動畫中很常見,缺點是難以暫停或跳轉;現代的等價做法是 async/await 搭配 sleep,或用 requestAnimationFrame 管理時間軸。

棋譜本身的歷史意義也值得記一筆:這是 1996 年 2 月 10 日費城對局,白方 Deep Blue、黑方卡斯帕羅夫,1-0。它是電腦在正常比賽規則下首次擊敗現任世界冠軍。卡斯帕羅夫在後續五局以 3 和 2 勝的成績反贏該場比賽,直到 1997 年的復賽,Deep Blue 才拿下整場勝利。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved