我:写一个贪吃蛇源码
AI:kua、kua、kua
不到10s给我写完了,而且还能完美运行,不得不说,这效率真的高。
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇</title>
<style>
body {
background-color: #333;
color: #fff;
font-family: Arial, sans-serif;
text-align: center;
}
canvas {
border: 1px solid #fff;
}
</style>
</head>
<body>
<h1>贪吃蛇</h1>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取画布和上下文
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 定义蛇的初始位置和大小
var snake = [{x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}];
var snakeSize = 10;
// 定义食物的初始位置和大小
var food = {x: 5, y: 5};
var foodSize = 10;
// 定义蛇的移动方向
var direction = "right";
// 定义游戏是否结束
var gameOver = false;
// 定义游戏循环
function gameLoop() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制蛇
ctx.fillStyle = "#fff";
for (var i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x * snakeSize, snake[i].y * snakeSize, snakeSize, snakeSize);
}
// 绘制食物
ctx.fillStyle = "#f00";
ctx.fillRect(food.x * foodSize, food.y * foodSize, foodSize, foodSize);
// 移动蛇
var head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case "up":
head.y--;
break;
case "down":
head.y++;
break;
case "left":
head.x--;
break;
case "right":
head.x++;
break;
}
snake.unshift(head);
// 判断是否吃到食物
if (head.x === food.x && head.y === food.y) {
food.x = Math.floor(Math.random() * canvas.width / foodSize);
food.y = Math.floor(Math.random() * canvas.height / foodSize);
} else {
snake.pop();
}
// 判断游戏是否结束
if (head.x < 0 || head.x >= canvas.width / snakeSize || head.y < 0 || head.y >= canvas.height / snakeSize) {
gameOver = true;
}
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver = true;
}
}
// 如果游戏结束,显示游戏结束信息
if (gameOver) {
ctx.fillStyle = "#f00";
ctx.font = "bold 30px Arial";
ctx.fillText("Game Over", canvas.width / 2 - 80, canvas.height / 2);
return;
}
// 延迟执行游戏循环
setTimeout(gameLoop, 100);
}
// 监听键盘事件,改变蛇的移动方向
document.addEventListener("keydown", function(event) {
switch (event.keyCode) {
case 37:
if (direction !== "right") {
direction = "left";
}
break;
case 38:
if (direction !== "down") {
direction = "up";
}
break;
case 39:
if (direction !== "left") {
direction = "right";
}
break;
case 40:
if (direction !== "up") {
direction = "down";
}
break;
}
});
// 开始游戏循环
gameLoop();
</script>
</body>
</html>
- 运行效果