科学教育
标题:
王欣然
[打印本页]
作者:
WXRa
时间:
2025-9-30 15:38
标题:
王欣然
帮我生成一个贪吃蛇代码
作者:
kaia
时间:
2025-9-30 15:39
当然可以!贪吃蛇是一个很经典的游戏,下面是一个简单的贪吃蛇代码示例,你可以在网页上运行它:
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.snake {
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>
let gameBoard = document.getElementById('game-board');
let snake = [{x: 200, y: 200}];
let dx = 0;
let dy = 0;
let foodX = Math.floor(Math.random() * 20) * 20;
let foodY = Math.floor(Math.random() * 20) * 20;
let score = 0;
function drawSnake() {
gameBoard.innerHTML = '';
snake.forEach(segment => {
let snakeElement = document.createElement('div');
snakeElement.style.left = segment.x + 'px';
snakeElement.style.top = segment.y + 'px';
snakeElement.classList.add('snake');
gameBoard.appendChild(snakeElement);
});
}
function drawFood() {
let foodElement = document.createElement('div');
foodElement.style.left = foodX + 'px';
foodElement.style.top = foodY + 'px';
foodElement.classList.add('food');
gameBoard.appendChild(foodElement);
}
function moveSnake() {
let head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if (head.x === foodX && head.y === foodY) {
score++;
foodX = Math.floor(Math.random() * 20) * 20;
foodY = Math.floor(Math.random() * 20) * 20;
} else {
snake.pop();
}
if (head.x < 0 || head.x >= gameBoard.clientWidth || head.y < 0 || head.y >= gameBoard.clientHeight || isSnakeCollide()) {
alert('Game Over! Your score is: ' + score);
window.location.reload();
}
drawSnake();
drawFood();
}
function isSnakeCollide() {
return snake.slice(1).some(segment => segment.x === snake[0].x && segment.y === snake[0].y);
}
document.addEventListener('keydown', e => {
switch (e.key) {
case 'ArrowUp':
dx = 0;
dy = -20;
break;
case 'ArrowDown':
dx = 0;
dy = 20;
break;
case 'ArrowLeft':
dx = -20;
dy = 0;
break;
case 'ArrowRight':
dx = 20;
dy = 0;
break;
}
});
setInterval(moveSnake, 100);
</script>
</body>
</html>
复制代码
你可以将以上代码复制粘贴到一个新建的HTML文件中,然后用浏览器打开,就可以看到一个简单的贪吃蛇游戏了!玩得开心哦!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2