在实现贪吃蛇游戏时,我们可以使用TypeScript结合HTML5的canvas元素来完成。以下是一个简单的贪吃蛇游戏的实现示例:
// game.ts
enum Direction {
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
class Snake {
body: { x: number, y: number }[] = [];
direction: Direction = Direction.Right;
constructor(x: number, y: number) {
this.body.push({ x, y });
}
move(direction: Direction) {
this.direction = direction;
let head = this.body[0];
switch (direction) {
case Direction.Up:
head.y--;
break;
case Direction.Down:
head.y++;
break;
case Direction.Left:
head.x--;
break;
case Direction.Right:
head.x++;
break;
}
this.body.unshift(head);
}
// ... other snake methods (grow, die, etc.)
}
class Game {
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
snake: Snake;
food: { x: number, y: number };
constructor() {
this.canvas = document.getElementById('gameCanvas') as HTMLCanvasElement;
this.ctx = this.canvas.getContext('2d');
this.snake = new Snake(10, 10);
this.food = this.spawnFood();
this.setupInput();
this.loop();
}
setupInput() {
document.addEventListener('keydown', (e) => {
switch (e.keyCode) {
case 37: // Left
if (this.snake.direction !== Direction.Right) {
this.snake.move(Direction.Left);
}
break;
case 38: // Up
if (this.snake.direction !== Direction.Down) {
this.snake.move(Direction.Up);
}
break;
case 39: // Right
if (this.snake.direction !== Direction.Left) {
this.snake.move(Direction.Right);
}
break;
case 40: // Down
if (this.snake.direction !== Direction.Up) {
this.snake.move(Direction.Down);
}
break;