用html和js写一个简单的贪吃蛇小游戏
时间: 2023-06-07 13:08:49 浏览: 108
好的,我可以帮您编写一个简单的贪吃蛇小游戏。以下是代码示例:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇小游戏</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake_game.js"></script>
</body>
</html>
```
JavaScript代码:
```
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var blockSize = 20;
var widthInBlocks = canvas.width / blockSize;
var heightInBlocks = canvas.height / blockSize;
var score = 0;
var snake = {
segments: [[6,4],[5,4],[4,4]],
direction: "right"
};
var apple = {
position: [10,10]
};
function drawBlock(ctx, position) {
var x = position[0] * blockSize;
var y = position[1] * blockSize;
ctx.fillRect(x, y, blockSize, blockSize);
}
function drawSnake(ctx) {
for (var i = 0; i < snake.segments.length; i++) {
drawBlock(ctx, snake.segments[i]);
}
}
function drawApple(ctx) {
ctx.fillStyle = "red";
drawBlock(ctx, apple.position);
}
function checkCollision(head, array) {
for (var i = 0; i < array.length; i++) {
if (head[0] === array[i][0] && head[1] === array[i][1]) {
return true;
}
}
return false;
}
function checkGameOver() {
var head = snake.segments[0];
var body = snake.segments.slice(1);
if (head[0] < 0 || head[0] >= widthInBlocks || head[1] < 0 || head[1] >= heightInBlocks || checkCollision(head, body)) {
return true;
}
return false;
}
function moveSnake() {
var head = snake.segments[0].slice();
switch (snake.direction) {
case "right":
head[0] += 1;
break;
case "left":
head[0] -= 1;
break;
case "up":
head[1] -= 1;
break;
case "down":
head[1] += 1;
break;
}
snake.segments.unshift(head);
if (checkCollision(head, [apple.position])) {
score++;
generateApple();
} else {
snake.segments.pop();
}
}
function generateApple() {
var newX = Math.floor(Math.random() * widthInBlocks);
var newY = Math.floor(Math.random() * heightInBlocks);
apple.position = [newX, newY];
}
function displayScore() {
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.textAlign = "left";
ctx.textBaseline = "top"
ctx.fillText("Score: " + score, blockSize, blockSize);
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
displayScore();
drawSnake(ctx);
drawApple(ctx);
moveSnake();
if (checkGameOver()) {
clearInterval(gameIntervalId);
ctx.fillStyle = "black";
ctx.font = "60px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Game Over", canvas.width / 2, canvas.height / 2);
}
}
generateApple();
var gameIntervalId = setInterval(gameLoop, 100);
```
注意:此为示例代码,可能存在不足之处。如果您有任何问题或需要进一步帮助,请及时联系我!
阅读全文