用js写一个贪吃蛇的代码
时间: 2023-06-05 12:08:54 浏览: 97
贪吃蛇js代码
好的,以下是一个基本的 JavaScript 贪吃蛇游戏的代码:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇游戏</title>
<style>
body {
background-color: #f1f1f1;
}
canvas {
background-color: #fff;
border: 1px solid #ddd;
margin: 0 auto;
display: block;
}
</style>
</head>
<body>
<canvas id="snakeboard" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript 代码:
```js
var canvas = document.getElementById("snakeboard");
var ctx = canvas.getContext("2d");
var speed = 100; // 游戏速度
var cellSize = 10; // 每个方块的尺寸
var snake = {
body: [[6, 4], [5, 4], [4, 4]], // 蛇身初始位置
direction: "right" // 蛇初始方向
};
var food = []; // 食物位置
function drawCell(x, y) {
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
function drawSnake() {
ctx.fillStyle = "#333";
snake.body.forEach(function (cell) {
drawCell(cell[0], cell[1]);
});
}
function move() {
var dx = 0;
var dy = 0;
switch (snake.direction) {
case "up":
dy = -1;
break;
case "down":
dy = 1;
break;
case "left":
dx = -1;
break;
case "right":
dx = 1;
break;
}
var newHead = [snake.body[0][0] + dx, snake.body[0][1] + dy];
if (newHead[0] < 0 || newHead[0] >= canvas.width / cellSize ||
newHead[1] < 0 || newHead[1] >= canvas.height / cellSize) {
endGame();
return;
}
if (checkCollision(newHead)) {
endGame();
return;
}
snake.body.unshift(newHead);
if (newHead[0] === food[0] && newHead[1] === food[1]) {
addFood();
} else {
snake.body.pop();
}
}
function checkCollision(cell) {
return snake.body.some(function (c) {
return c[0] === cell[0] && c[1] === cell[1];
});
}
function addFood() {
food = [Math.floor(Math.random() * canvas.width / cellSize),
Math.floor(Math.random() * canvas.height / cellSize)];
if (checkCollision(food)) {
addFood();
}
}
function drawFood() {
ctx.fillStyle = "#f00";
drawCell(food[0], food[1]);
}
function endGame() {
clearInterval(gameLoop);
alert("游戏结束!");
}
function handleKeyPress(evt) {
switch (evt.keyCode) {
case 37: // 左
if (snake.direction !== "right") {
snake.direction = "left";
}
break;
case 38: // 上
if (snake.direction !== "down") {
snake.direction = "up";
}
break;
case 39: // 右
if (snake.direction !== "left") {
snake.direction = "right";
}
break;
case 40: // 下
if (snake.direction !== "up") {
snake.direction = "down";
}
break;
}
}
canvas.addEventListener("keydown", handleKeyPress);
addFood();
var gameLoop = setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
move();
drawSnake();
drawFood();
}, speed);
```
运行代码后,就可以在页面中看到贪吃蛇游戏啦!左、上、右、下方向键可以控制蛇的移动。
阅读全文