HTML5+JS 《五子飛》游戲實現(六)鼠標響應與多重選擇
上一章我們提到了如果有多條線上的棋子可以被吃掉,那么游戲需要提示用戶,讓用戶選擇吃哪條線上的。另外因為是網頁游戲,所以一定要實現鼠標單擊棋子可以進行操作。
當鼠標移動棋子上面后,切換鼠標指針為手形,移開棋子后再切換回默認的狀態:
el.mousemove(function (e) { var o = el.offset(); var p = { x: e.clientX - o.left, y: e.clientY - o.top }; el.css("cursor", "default"); for (var i = 0; i < t.chesses.length; i++) { if (Canvas.inRegion([p.x, p.y], t.chesses[i].bounds.toArrayXY())) { el.css("cursor", "pointer"); break; } } });
同時,還要根據鼠標位置來判斷當前是哪顆棋子,是選中棋子還是移動棋子。
如果只是選中棋子,只需要在點擊棋子后,在棋子的外面畫一個框用來區別其他棋子,表示是當前棋子:
var b = this.chesses[this.currentIndex].bounds; Canvas.drawRect(this.panel, "rgba(255,0,0,0.4)", 2, b.x - 2, b.y - 2, b.x + b.w + 2, b.y + b.h + 2);
如果是移動棋子,還要區別只是單純的移動棋子還是移動后可以吃對方的棋子。單純的移動棋子也就只需要更新目標位置為當前棋子就行了。
if (t.currentPlayer == t.chesses[i].player && t.chesses[i].player != Player.None) { t.currentIndex = i; }
要是可以吃掉對方的棋子,就需要把對方的棋子吃掉或有多條路線可以吃棋時提示用戶選擇吃哪條路線的棋子。吃了棋子后還要判斷對方還可不可以繼續走棋,如果不能繼續走棋,那么還需要提示用戶游戲結束,我方贏了。
if (t.currentPlayer == t.chesses[t.currentIndex].player && t.chesses[i].player == Player.None) { if (t.moveChess(i, t.currentIndex)) { t.currentIndex = i; if (!t.chessarray) { player = t.currentPlayer; t.currentPlayer = t.getAnotherPlayer(player); t.changePlayer(); if (t.isGameOver(t.currentPlayer)) { t.winner = player; t.isover = true; } } } }
判斷游戲是否結束:
// 游戲結束 this.isGameOver = function (player) { var i, j, k, pos; // 檢查是否有可移動的棋子 for (i = 0; i < this.chesses.length; i++) { if (this.chesses[i].player == player) { for (j = 0; j < this.lines.length; j++) { pos = $.inArray(this.chesses[i].point.index, this.lines[j]); if (pos != -1) { for (k = 0; k < pos - 1; k++) { if (this.canMove(k, pos)) return false; } for (k = pos + 1; k < this.lines[j].length; k++) { if (this.canMove(k, pos)) return false; } } } } } return true; };
有多條路線選擇的時候,我們暫時這樣處理:在每條路線的左邊棋子左邊寫上數字1,2,3...,表示路線編號,這樣用戶只需要點擊有編號旁邊的棋子就可以選擇吃哪條路線的棋子:
// 多重選擇 if (this.chessarray) { // 遮擋層 Canvas.drawFillRect(this.panel, "#000000", 1, 20, 20, cw - 20, cw - 20, "rgba(0,0,0,0.4)"); // 多重棋子 for (i = 0; i < this.chessarray.length; i++) { b = this.chessarray[i][0].bounds; Canvas.drawRect(this.panel, "rgba(255,255,0,0.4)", 2, b.x - 2, b.y - 2, b.x + b.w + 2, b.y + b.h + 2);
// 寫上路線編號 Canvas.drawText(this.panel, i + 1, b.x + b.w + 4, b.y + b.h + 2, "#FFFFFF"); } }
最后每次我方下完棋子后,還需要切換給對方下棋:
player = t.currentPlayer; t.currentPlayer = t.getAnotherPlayer(player); t.changePlayer();
好了,這一章就里沃特先分析到這里。

浙公網安備 33010602011771號