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();
好了,这一章就里沃特先分析到这里。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?