用javascript语言写一个贪吃蛇游戏
时间: 2024-05-02 13:20:53 浏览: 99
由于语言实在是太长了,我这里只提供一个基础的代码框架,供您参考:
HTML部分:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style type="text/css">
#game-board {
width: 600px;
height: 600px;
margin: auto;
border: 1px solid black;
position: relative;
}
.snake-body {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript部分:
```javascript
// 获取游戏面板
var gameBoard = document.getElementById("game-board");
// 设置游戏面板的宽高
var boardWidth = gameBoard.offsetWidth;
var boardHeight = gameBoard.offsetHeight;
// 设置每个方格的宽度和高度
var squareSize = 20;
// 计算水平和垂直方向上的方格数
var numX = boardWidth / squareSize;
var numY = boardHeight / squareSize;
// 初始化蛇的位置和长度
var snake = [{x: 5, y: 5}, {x: 4, y: 5}, {x: 3, y: 5}];
// 初始化蛇的移动方向
var direction = "right";
// 随机生成食物的初始位置
var foodX = Math.floor(Math.random() * numX);
var foodY = Math.floor(Math.random() * numY);
// 绘制蛇和食物
drawSnake();
drawFood();
// 监听键盘事件
document.addEventListener("keydown", function(event) {
if (event.keyCode === 37 && direction !== "right") { // 左箭头
direction = "left";
}
if (event.keyCode === 38 && direction !== "down") { // 上箭头
direction = "up";
}
if (event.keyCode === 39 && direction !== "left") { // 右箭头
direction = "right";
}
if (event.keyCode === 40 && direction !== "up") { // 下箭头
direction = "down";
}
});
// 定时器,每隔一段时间移动蛇
setInterval(moveSnake, 100);
// 移动蛇
function moveSnake() {
// 获取蛇头的位置
var head = snake[0];
var x = head.x;
var y = head.y;
// 根据移动方向更新蛇头的位置
if (direction === "right") {
x++;
}
if (direction === "left") {
x--;
}
if (direction === "up") {
y--;
}
if (direction === "down") {
y++;
}
// 判断是否撞墙或撞到自己
if (x < 0 || x >= numX || y < 0 || y >= numY || checkCollision(x, y)) {
alert("游戏结束!");
location.reload();
}
// 判断是否吃到食物
if (x === foodX && y === foodY) {
// 在蛇头添加一个新的方块
snake.unshift({x: x, y: y});
// 重新生成食物的位置
foodX = Math.floor(Math.random() * numX);
foodY = Math.floor(Math.random() * numY);
drawFood();
} else {
// 在蛇头添加一个新的方块,并删除蛇尾
snake.pop();
snake.unshift({x: x, y: y});
}
// 重新绘制蛇
drawSnake();
}
// 绘制蛇
function drawSnake() {
// 清空游戏面板
gameBoard.innerHTML = "";
// 绘制蛇的每个方块
snake.forEach(function(segment) {
var snakeBody = document.createElement("div");
snakeBody.className = "snake-body";
snakeBody.style.left = segment.x * squareSize + "px";
snakeBody.style.top = segment.y * squareSize + "px";
gameBoard.appendChild(snakeBody);
});
}
// 绘制食物
function drawFood() {
var food = document.createElement("div");
food.className = "food";
food.style.left = foodX * squareSize + "px";
food.style.top = foodY * squareSize + "px";
gameBoard.appendChild(food);
}
// 检查蛇是否撞到自己
function checkCollision(x, y) {
return snake.some(function(segment, index) {
if (index === 0) {
return false;
}
return segment.x === x && segment.y === y;
});
}
```
阅读全文