DIV CSS 佈局教程網

JS 小遊戲實作:象棋暗棋的規則判定與棋盤邏輯
編輯:關於JavaScript     

象棋暗棋(翻棋)規則簡單卻細節不少:棋子蓋著、翻開後才能行動、同色吃子比大小、吃對方帥時特殊。這個實作的價值在於把「規則判定」從畫面邏輯中抽成獨立方法,可讀性相當高。

狀態與棋盤資料結構

棋盤 4 列 8 行,共 32 格;this.chess 是一維陣列,索引 = 列 × 8 + 行。每個元素記錄棋子名、種類(a 紅 / b 綠)、大小與狀態:

/** chinese chess
 * Author: fdipzone
 * Date: 2012-06-24
 * Ver: 1.0
 */
var gameimg = [
  'images/a1.gif','images/a2.gif','images/a3.gif','images/a4.gif',
  'images/a5.gif','images/a6.gif','images/a7.gif',
  'images/b1.gif','images/b2.gif','images/b3.gif','images/b4.gif',
  'images/b5.gif','images/b6.gif','images/b7.gif',
  'images/bg.gif','images/bg_over.gif','images/bg_sel.gif'
];
var chess_obj = new ChessClass();

window.onload = function(){
  $('init_btn').onclick = function(){ chess_obj.init(); };
  var callback = function(){ chess_obj.init(); };
  img_preload(gameimg, callback);
};

function ChessClass(){
  this.chess = [];
  this.boardrows = 4;
  this.boardcols = 8;
  this.area = 82;      // 每格邊長
  this.player = 1;     // 1: 紅  2: 綠
  this.selected = null;// 目前選中的棋子
  this.chesstype = ['', 'a', 'b'];
  this.isover = 0;
}

ChessClass.prototype.init = function(){
  this.reset_grade();
  this.create_board();
  this.create_chess();
  this.create_event();
  this.player = 1;
  this.selected = null;
  this.isover = 0;
  disp('init_div', 'hide');
};

棋盤與發棋

棋盤以 列_行 作為每格的 id,這個命名讓「索引 ↔ 座標」的轉換變成單純的除法與取餘數:

ChessClass.prototype.create_board = function(){
  var board = '';
  for(var i = 0; i < this.boardrows; i++){
    for(var j = 0; j < this.boardcols; j++){
      board += '<div id="' + i + '_' + j + '"><img src="images/chessbg.gif" /></div>';
    }
  }
  $('board').innerHTML = board;
  $('board').style.width  = this.boardcols * (this.area + 2) + 'px';
  $('board').style.height = this.boardrows * (this.area + 2) + 'px';
};

// 32 張棋子,格式為「種類 + 大小」,a 代表紅方、b 代表綠方
ChessClass.prototype.create_chess = function(){
  var chesses = [
    'a1','b7', 'a2','b7', 'a2','b7', 'a3','b7', 'a3','b7',
    'a4','b6', 'a4','b6', 'a5','b5', 'a5','b5', 'a6','b4',
    'a6','b4', 'a7','b3', 'a7','b3', 'a7','b2', 'a7','b2', 'a7','b1'
  ];
  this.chess = [];
  while(chesses.length > 0){
    var rnd = Math.floor(Math.random() * chesses.length);
    var tmpchess = chesses.splice(rnd, 1).toString();
    this.chess.push({
      'chess': tmpchess,
      'type':  tmpchess.substr(0, 1),
      'val':   tmpchess.substr(1, 1),
      'status': 0   // 0: 蓋住  1: 已翻開  -1: 空格
    });
  }
};

ChessClass.prototype.getindex = function(id){
  var tid = id.split('_');
  return parseInt(tid[0]) * this.boardcols + parseInt(tid[1]);
};

ChessClass.prototype.getid = function(index){
  return parseInt(index / this.boardcols) + '_' + parseInt(index % this.boardcols);
};

點擊行為的分派

action 是整個遊戲的中樞,依「目前有沒有選中棋子」與「點到的是什麼」分四路:蓋著的棋翻開、自己的棋改選、空格移動、敵棋比大小吃子。

ChessClass.prototype.create_event = function(){
  var self = this;
  var chess_area = $_tag('div', 'board');
  for(var i = 0; i < chess_area.length; i++){
    chess_area[i].onmouseover = function(){
      if(this.className != 'onsel'){ this.className = 'on'; }
    };
    chess_area[i].onmouseout = function(){
      if(this.className != 'onsel'){ this.className = ''; }
    };
    chess_area[i].onclick = function(){ self.action(this); };
  }
};

ChessClass.prototype.action = function(o){
  if(this.isover == 1){ return false; }
  var index = this.getindex(o.id);
  if(this.selected == null){
    if(this.chess[index]['status'] == 0){
      this.show(index);                 // 蓋著 → 翻開
    }else if(this.chess[index]['status'] == 1){
      if(this.chess[index]['type'] == this.chesstype[this.player]){
        this.select(index);             // 自己的棋 → 選取
      }
    }
  }else{
    if(index != this.selected['index']){
      if(this.chess[index]['status'] == 0){
        this.show(index);               // 點到蓋棋 → 翻開
      }else if(this.chess[index]['status'] == -1){
        this.move(index);               // 點空格 → 移動
      }else{
        if(this.chess[index]['type'] == this.chesstype[this.player]){
          this.select(index);           // 改選己方棋子
        }else{
          this.kill(index);             // 吃子
        }
      }
    }
  }
};

ChessClass.prototype.show = function(index){
  $(this.getid(index)).innerHTML =
    '<img src="images/' + this.chess[index]['chess'] + '.gif" />';
  this.chess[index]['status'] = 1;
  if(this.selected != null){
    $(this.getid(this.selected.index)).className = '';
    this.selected = null;
  }
  this.change_player();
  this.gameover();
};

ChessClass.prototype.select = function(index){
  if(this.selected != null){
    $(this.getid(this.selected['index'])).className = '';
  }
  this.selected = {'index': index, 'chess': this.chess[index]};
  $(this.getid(index)).className = 'onsel';
};

ChessClass.prototype.move = function(index){
  if(this.beside(index)){
    this.chess[index] = {
      'chess':  this.selected['chess']['chess'],
      'type':   this.selected['chess']['type'],
      'val':    this.selected['chess']['val'],
      'status': this.selected['chess']['status']
    };
    this.remove(this.selected['index']);
    this.show(index);
  }
};

ChessClass.prototype.kill = function(index){
  if(this.beside(index) == true && this.can_kill(index) == true){
    this.chess[index] = {
      'chess':  this.selected['chess']['chess'],
      'type':   this.selected['chess']['type'],
      'val':    this.selected['chess']['val'],
      'status': this.selected['chess']['status']
    };
    this.remove(this.selected['index']);
    var killed = this.player == 1 ? 2 : 1;
    $('grade_num' + killed).innerHTML = parseInt($('grade_num' + killed).innerHTML) - 1;
    this.show(index);
  }
};

ChessClass.prototype.remove = function(index){
  this.chess[index]['status'] = -1;   // 標記為空格
  $(this.getid(index)).innerHTML = '';
  $(this.getid(index)).className = '';
};

兩個核心規則:相鄰與可吃

beside 判斷是否上下左右相鄰一格(不含斜向,這點與部分地方規則不同);can_kill 則實作比大小,並特別處理「最小可吃最大」的規則:

/* 是否相鄰
 * @param index    目標格索引
 * @param selindex 執行方索引,可省略,省略時取目前選中的棋子
 */
ChessClass.prototype.beside = function(index, selindex){
  if(typeof(selindex) == 'undefined'){
    if(this.selected != null){ selindex = this.selected['index']; }
    else { return false; }
  }
  if(typeof(this.chess[index]) == 'undefined'){ return false; }
  var from_info = this.getid(selindex).split('_');
  var to_info   = this.getid(index).split('_');
  var fw = parseInt(from_info[0]), fc = parseInt(from_info[1]);
  var tw = parseInt(to_info[0]),   tc = parseInt(to_info[1]);
  if(fw == tw && Math.abs(fc - tc) == 1
     || fc == tc && Math.abs(fw - tw) == 1){
    return true;   // 同行或同列且間距為 1
  }else{
    return false;
  }
};

/* 是否可吃
 * @param index    被吃的棋子索引
 * @param selindex 執行吃子的棋子索引,可省略
 */
ChessClass.prototype.can_kill = function(index, selindex){
  if(typeof(selindex) == 'undefined'){
    if(this.selected != null){ selindex = this.selected['index']; }
    else { return false; }
  }
  if(this.chess[index]['type'] != this.chesstype[this.player]){
    if(parseInt(this.chess[selindex]['val']) == 7
       && parseInt(this.chess[index]['val']) == 1){
      return true;    // 7(兵)可吃 1(帥)
    }else if(parseInt(this.chess[selindex]['val']) == 1
       && parseInt(this.chess[index]['val']) == 7){
      return false;   // 1 不可吃 7
    }else if(parseInt(this.chess[selindex]['val'])
             <= parseInt(this.chess[index]['val'])){
      return true;    // 數字小者可吃數字大者
    }
  }
  return false;
};

勝負判定與「是否還有步可走」

除了「任一方棋子歸零」之外,還有一個容易忽略的平手/結束條件:當玩家還有棋,但所有己方棋子都無路可走時,也該結束。can_action 就是逐一檢查四個方向是否可移動或可吃子:

ChessClass.prototype.change_player = function(){
  if(this.player == 1){
    this.player = 2;
    $('grade_img2').className = 'img_on';
    $('grade_img1').className = 'img';
  }else{
    this.player = 1;
    $('grade_img1').className = 'img_on';
    $('grade_img2').className = 'img';
  }
};

ChessClass.prototype.reset_grade = function(){
  $('grade_img1').className = 'img_on';
  $('grade_img2').className = 'img';
  $('grade_num1').innerHTML = $('grade_num2').innerHTML = 16;
  $('grade_res1').className = $('grade_res2').className = 'none';
  $('grade_res1').innerHTML = $('grade_res2').innerHTML = '';
};

ChessClass.prototype.gameover = function(){
  if($('grade_num1').innerHTML == 0 || $('grade_num2').innerHTML == 0){
    this.isover = 1;
    this.show_grade();
    disp('init_div', 'show');
  }else if(this.can_action() == false){
    this.isover = 1;
    this.show_grade();
    disp('init_div', 'show');
  }
};

ChessClass.prototype.show_grade = function(){
  var num1 = parseInt($('grade_num1').innerHTML);
  var num2 = parseInt($('grade_num2').innerHTML);
  if(num1 > num2){
    $('grade_res2').innerHTML = 'LOSS'; $('grade_res2').className = 'loss';
    $('grade_res1').innerHTML = 'WIN';  $('grade_res1').className = 'win';
  }else if(num1 < num2){
    $('grade_res1').innerHTML = 'LOSS'; $('grade_res1').className = 'loss';
    $('grade_res2').innerHTML = 'WIN';  $('grade_res2').className = 'win';
  }else{
    $('grade_res1').innerHTML = $('grade_res2').innerHTML = 'DRAW';
    $('grade_res1').className = $('grade_res2').className = 'draw';
  }
};

ChessClass.prototype.can_action = function(){
  var chess = this.chess;
  for(var i = 0, max = chess.length; i < max; i++){
    if(chess[i].status == 0){ return true; }  // 還有蓋著的棋 → 一定能翻
    if(chess[i].status == 1
       && chess[i].type == this.chesstype[this.player]){
      if(this.beside(i - this.boardcols, i)
         && (chess[i - this.boardcols].status == -1
             || this.can_kill(i - this.boardcols, i))){ return true; } // 上
      if(this.beside(i + this.boardcols, i)
         && (chess[i + this.boardcols].status == -1
             || this.can_kill(i + this.boardcols, i))){ return true; } // 下
      if(this.beside(i - 1, i)
         && (chess[i - 1].status == -1 || this.can_kill(i - 1, i))){ return true; } // 左
      if(this.beside(i + 1, i)
         && (chess[i + 1].status == -1 || this.can_kill(i + 1, i))){ return true; } // 右
    }
  }
  return false;
};

設計上的觀察

這份程式最值得學的是「規則與渲染分離」:beside 與 can_kill 是純函數式的判斷,不碰 DOM,因此可以獨立測試;chess 陣列是唯一的資料來源,畫面只是它的投影。棋子的翻開、移動、吃子都先改資料再更新畫面,這正是現代前端「狀態驅動視圖」的雛形。

要改進的地方有兩點。其一,can_kill 中「7 可吃 1、1 不可吃 7」是暗棋規則,但一般規則還包含同色不可互吃、以及吃光對方後仍有「無子可動」的判定,這裡以棋子數量勝負取代,屬簡化版。其二,can_action 在每次 show 之後都全盤掃描四方向,資料量小時無妨,若棋盤擴大可以只在「轮到某方」時計算一次並快取結果。整體而言,作為暗棋規則的入門實作,它的結構清楚、擴充容易,很適合當作棋類遊戲的起手模板。

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