贪吃蛇游戏四个按钮控制方向
源代码在图片后面 点赞❤️关注收藏⭐️
互粉必回
源代码
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
margin: 0;
font-family: Arial, sans-serif;
}
.game-container {
width: 300px;
text-align: center;
}
table {
border-collapse: collapse;
margin-top: 20px;
border: 1px solid gray;
}
td {
width: 10px;
height: 10px;
border: 1px solid gray;
}
.snake {
background-color: green;
}
.food {
background-color: red;
}
.control-buttons {
display: flex;
justify-content: space-around;
margin-bottom: 10px;
}
button {
width: 50px;
height: 50px;
border-radius: 10px;
border: none;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
cursor: pointer;
}
#score {
font-size: 1.5em;
margin-bottom: 10px;
}
const board = document.getElementById('game-board');
const scoreDisplay = document.getElementById('score');
let snake = [{x: 10, y: 10}];
let food = {x: 15, y: 15};
let direction = 'right';
let score = 0;
function drawBoard() {
board.innerHTML = '';
for (let i = 0; i < 20; i++) {
let row = '
for (let j = 0; j < 20; j++) {
if (snake.some(part => part.x === j && part.y === i)) {
row += '
} else if (food.x === j && food.y === i) {
row += '
} else {
row += '
}
}
row += '
board.innerHTML += row;
}
}
function updateSnake() {
const head = {x: snake[0].x + (direction === 'right' ? 1 : direction === 'left' ? -1 : 0),
y: snake[0].y + (direction === 'down' ? 1 : direction === 'up' ? -1 : 0)};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score++;
scoreDisplay.textContent = `当前分数: ${score}`;
food = {x: Math.floor(Math.random() * 20), y: Math.floor(Math.random() * 20)};
} else {
snake.pop();
}
}
function checkCollision() {
const head = snake[0];
if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20 || snake.slice(1).some(part => part.x === head.x && part.y === head.y)) {
alert('Game Over!');
location.reload();
}
}
function gameLoop() {
updateSnake();
checkCollision();
drawBoard();
setTimeout(gameLoop, 200);
}
document.getElementById('up-btn').addEventListener('click', () => direction = 'up');
document.getElementById('right-btn').addEventListener('click', () => direction = 'right');
document.getElementById('down-btn').addEventListener('click', () => direction = 'down');
document.getElementById('left-btn').addEventListener('click', () => direction = 'left');
gameLoop();