ts练习项目-贪吃蛇(位置类)
项目介绍
学习了typescript语法。教程中的练习项目是贪吃蛇。项目中是利用元素的绝对定位来实现蛇与食物的动作。个人觉得不是很好,于是自己设计了一套实现方法。
项目代码已全部完成,并放到了github。
效果演示
一、设计构思
在贪吃蛇游戏中,我们可以把整个游戏界面看成由一组正方形格子组成的一个 x * y 的矩形。每个格子只有两种状态:白色或黑色。白色表示空白,黑色表示蛇或者食物。我们把整个界面看成一个二维数组。
我们先把这个二维数组暂且叫做 rows 。那每一个格子可以表示成 rows[y][x] 。其中 y 表示行索引, x 表示列索引。此时每个格子就可以由 x 和 y 表示。是不是很像一个坐标 (x, y) ?
我们把这个二维数组放到一个坐标系中,横轴从左向右用 x 表示,纵轴从上向下用 y 表示。这样每个格子就可以使用坐标表示成 (x, y) 。把这个坐标抽象成一个位置类 Position ,这样食物就可以用一个 Position 表示,而蛇可以用一个 Position 数组表示。
二、基本功能
这个类中需要有哪些属性和方法呢?
当然是其对应的坐标 x 和 y 了。
class Position {
private _x: number;//横向坐标
private _y: number;//纵向坐标
constructor(x: number, y: number) {
this._x = x;
this._y = y;
}
get x() {
return this._x;
}
set x(x) {
this._x = x;
}
get y() {
return this._y;
}
set y(y) {
this._y = y;
}
}
三、其他功能
因为蛇和食物都是由 Position 组成的,所以蛇和食物的关系可以用 Position 的关系表示。 现在我们需要使用 Position 类解决如下三个问题。
- 1、判断蛇是否吃到食物。
- 2、计算蛇头的移动。
- 3、计算蛇身体的移动。
1、判断蛇是否吃到食物
判断蛇是否吃到食物只要判断蛇头的位置是不是和食物的位置相等。 所以 Position 类中需要一个比较相等的方法。
equals(position: Position) {
return this._x === position.x && this._y === position.y;
}
2、计算蛇头的移动
蛇的运动有上下左右四个方向,可以分解到横轴和纵轴两个方向。横轴方向正一表示向右,负一表示向左。纵轴方向正一表示向下,负一表示向上。这样我们也可以用一个 Position 表示蛇运动的方向。
- (1, 0) 表示向右
- (-1, 0) 表示向左
- (0, 1) 表示向下
- (0, -1) 表示向上
此时蛇头的运动就可以看成是蛇头的坐标加上方向。所以 Position 类中需要一个相加的方法。
add(position: Position) {
return new Position(this._x + position.x, this._y + position.y);
}
3、蛇身体的移动
蛇身体的运动就很简单了,只需要从蛇尾向蛇头遍历(不包括蛇头),每一截都复制下一截的位置即可。所以 Position 类中需要一个复制方法。
copy() {
return new Position(this._x, this._y);
}
四、完整代码
class Position {
private _x: number;//横向坐标
private _y: number;//纵向坐标
constructor(x: number, y: number) {
this._x = x;
this._y = y;
}
get x() {
return this._x;
}
set x(x) {
this._x = x;
}
get y() {
return this._y;
}
set y(y) {
this._y = y;
}
add(position: Position) {
return new Position(this._x + position.x, this._y + position.y);
}
copy() {
return new Position(this._x, this._y);
}
equals(position: Position) {
return this._x === position.x && this._y === position.y;
}
}
export default Position;
转载自:https://juejin.cn/post/7369481217030750217