蛇的控制逻辑,增长逻辑,碰撞检测改为后端实现 + 结果计分板实现
This commit is contained in:
@@ -33,7 +33,7 @@ export class GameMap extends AcGameObject {
|
||||
// 上面的 super() 会先将 AcGameObject 先绘制, walls 的绘制在后面执行,因此墙最后会覆盖原棋盘格进行绘制
|
||||
this.walls = [];
|
||||
|
||||
// 创建蛇对象数组
|
||||
// 创建蛇对象数组(可以通过 store.state.pk.game_object.snakes 全局变量调取)
|
||||
this.snakes = [
|
||||
// 注意这里的对象生成方式和传参方式
|
||||
new Snake({ id: 0, color: "#4876ec", r: this.rows - 2, c: 1 }, this),
|
||||
@@ -167,20 +167,35 @@ export class GameMap extends AcGameObject {
|
||||
this.ctx.canvas.focus();
|
||||
|
||||
// 先取出两条蛇对象
|
||||
const [snake0, snake1] = this.snakes;
|
||||
// const [snake0, snake1] = this.snakes;
|
||||
|
||||
// 获取用户信息:绑定 keydown 事件
|
||||
this.ctx.canvas.addEventListener("keydown", (e) => {
|
||||
// 取出移动的方向,需要将方向传给后端
|
||||
let d = -1; // -1 表示没有方向, 0-上, 1-右, 2-下, 3-左
|
||||
|
||||
// 定义 snake0 的键盘绑定事件
|
||||
if (e.key === "w") snake0.set_direction(0);
|
||||
else if (e.key === "d") snake0.set_direction(1);
|
||||
else if (e.key === "s") snake0.set_direction(2);
|
||||
else if (e.key === "a") snake0.set_direction(3);
|
||||
// 定义 snake1 的键盘绑定事件
|
||||
if (e.key === "w") d = 0;
|
||||
else if (e.key === "d") d = 1;
|
||||
else if (e.key === "s") d = 2;
|
||||
else if (e.key === "a") d = 3;
|
||||
|
||||
// 如果进行了合法的移动操作:向后端发送方向
|
||||
if(d>=0){
|
||||
// 使用 socket.send() 传递信息给后端,使用 JSON.stringify() 将一个 JSON 封装成一字符串
|
||||
this.store.state.pk.socket.send(JSON.stringify({
|
||||
event: "move", // 事件类型: move
|
||||
direction : d, // 方向: d
|
||||
}))
|
||||
}
|
||||
|
||||
/*
|
||||
// 定义 snake1 的键盘绑定事件(前端调试时启用)
|
||||
else if (e.key === "ArrowUp") snake1.set_direction(0);
|
||||
else if (e.key === "ArrowRight") snake1.set_direction(1);
|
||||
else if (e.key === "ArrowDown") snake1.set_direction(2);
|
||||
else if (e.key === "ArrowLeft") snake1.set_direction(3);
|
||||
*/
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -104,11 +104,12 @@ export class Snake extends AcGameObject {
|
||||
// 这里需要使用 JSON 方法进行深度复制,以产生新的对象避免数据出错
|
||||
this.cells[i] = JSON.parse(JSON.stringify(this.cells[i - 1]));
|
||||
}
|
||||
|
||||
/* //(改为后端实现)
|
||||
// 如果下一步操作的目标位置碰撞检测不合法,则蛇直接去世
|
||||
if (!this.gamemap.check_valid(this.next_cell)) {
|
||||
this.status = "die";
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
update_move() {
|
||||
|
||||
Reference in New Issue
Block a user