场景:
制作一个简单html贪吃蛇游戏
方法
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇</title>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取画布
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 定义变量
var snake = [];
var snakeLength = 5;
var snakeSize = 20;
var food = {};
var score = 0;
var direction = "right";
// 初始化
function init() {
createSnake();
createFood();
drawSnake();
drawFood();
document.addEventListener("keydown", changeDirection);
setInterval(gameLoop, 100);
}
// 创建蛇
function createSnake() {
for (var i = snakeLength - 1; i >= 0; i--) {
snake.push({ x: i, y: 0 });
}
}
// 创建食物
function createFood() {
food.x = Math.floor(Math.random() * (canvas.width / snakeSize));
food.y = Math.floor(Math.random() * (canvas.height / snakeSize));
}
// 绘制蛇
function drawSnake() {
for (var i = 0; i < snake.length; i++) {
ctx.fillStyle = "green";
ctx.fillRect(snake[i].x * snakeSize, snake[i].y * snakeSize, snakeSize, snakeSize);
}
}
// 绘制食物
function drawFood() {
ctx.fillStyle = "red";
ctx.fillRect(food.x * snakeSize, food.y * snakeSize, snakeSize, snakeSize);
}
// 改变方向
function changeDirection(event) {
var key = event.keyCode;
if (key == 37 && direction != "right") {
direction = "left";
} else if (key == 38 && direction != "down") {
direction = "up";
} else if (key == 39 && direction != "left") {
direction = "right";
} else if (key == 40 && direction != "up") {
direction = "down";
}
}
// 游戏循环
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
// 移动蛇
var headX = snake[0].x;
var headY = snake[0].y;
if (direction == "right") {
headX++;
} else if (direction == "left") {
headX--;
} else if (direction == "up") {
headY--;
} else if (direction == "down") {
headY++;
}
var tail = snake.pop();
tail.x = headX;
tail.y = headY;
snake.unshift(tail);
// 检测碰撞
if (headX == food.x && headY == food.y) {
snake.push({ x: 0, y: 0 });
score++;
createFood();
}
if (headX < 0 || headX >= canvas.width / snakeSize || headY < 0 || headY >= canvas.height / snakeSize) {
alert("游戏结束,得分:" + score);
window.location.reload();
}
for (var i = 1; i < snake.length; i++) {
if (headX == snake[i].x && headY == snake[i].y) {
alert("游戏结束,得分:" + score);
window.location.reload();
}
}
}
// 开始游戏
init();
</script>
</body>
</html>
保存为html文件,直接打开
更多推荐
10秒钟,chatgpt帮你生成简单贪吃蛇游戏
发布评论