uniapp写一个贪吃蛇小游戏代码
时间: 2023-12-25 14:06:20 浏览: 42
好的,以下是一个简单的贪吃蛇小游戏的代码:
```
<template>
<div class="container">
<canvas id="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
<button @click="startGame">开始游戏</button>
</div>
</template>
<script>
export default {
data() {
return {
canvasWidth: 300,
canvasHeight: 300,
ctx: null,
snake: [],
food: {},
direction: 'right',
score: 0,
gameInterval: null
}
},
mounted() {
this.ctx = this.$refs.canvas.getContext('2d');
},
methods: {
startGame() {
this.initGame();
this.gameInterval = setInterval(() => {
this.draw();
this.move();
this.checkCollision();
this.checkFoodCollision();
}, 100);
},
initGame() {
this.snake = [{x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}];
this.generateFood();
},
draw() {
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.drawSnake();
this.drawFood();
this.drawScore();
},
drawSnake() {
this.ctx.fillStyle = 'green';
this.snake.forEach((segment) => {
this.ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10);
});
},
drawFood() {
this.ctx.fillStyle = 'red';
this.ctx.fillRect(this.food.x * 10, this.food.y * 10, 10, 10);
},
drawScore() {
this.ctx.fillStyle = 'black';
this.ctx.font = '16px Arial';
this.ctx.fillText(`Score: ${this.score}`, 10, 20);
},
move() {
const head = {x: this.snake[0].x, y: this.snake[0].y};
switch (this.direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
this.snake.unshift(head);
this.snake.pop();
},
checkCollision() {
const head = this.snake[0];
if (head.x < 0 || head.x >= this.canvasWidth / 10 || head.y < 0 || head.y >= this.canvasHeight / 10) {
clearInterval(this.gameInterval);
alert('游戏结束!请重新开始!');
}
for (let i = 1; i < this.snake.length; i++) {
if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
clearInterval(this.gameInterval);
alert('游戏结束!请重新开始!');
}
}
},
checkFoodCollision() {
const head = this.snake[0];
if (head.x === this.food.x && head.y === this.food.y) {
this.snake.push(this.snake[this.snake.length - 1]);
this.generateFood();
this.score++;
}
},
generateFood() {
this.food = {
x: Math.floor(Math.random() * (this.canvasWidth / 10)),
y: Math.floor(Math.random() * (this.canvasHeight / 10))
};
},
handleKeydown(event) {
switch (event.keyCode) {
case 38:
this.direction = 'up';
break;
case 40:
this.direction = 'down';
break;
case 37:
this.direction = 'left';
break;
case 39:
this.direction = 'right';
break;
}
}
},
created() {
document.addEventListener('keydown', this.handleKeydown);
},
destroyed() {
document.removeEventListener('keydown', this.handleKeydown);
}
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
canvas {
border: 1px solid black;
}
</style>
```
这个代码使用了uniapp框架,使用canvas元素绘制游戏界面,支持上下左右方向键控制贪吃蛇移动,实现了基本的游戏逻辑,包括蛇的移动、食物的随机生成和碰撞检测等。