使用模型通义千问
提示词:
用js html css 做一个贪吃蛇的动画
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Snake Game</title><link rel="stylesheet" href="css/test023.css">
</head>
<body>
<div id="gameBoard"></div>
<script src="js/test023.js"></script>
</body>
</html>
body {display: flex;justify-content: center;align-items: center;height: 100vh;background-color: #f0f0f0;margin: 0;
}#gameBoard {display: grid;width: 400px;height: 400px;grid-template-columns: repeat(20, 1fr);grid-template-rows: repeat(20, 1fr);border: 5px solid #333;
}.cell {width: 100%;height: 100%;background-color: #ccc;border: 1px solid #ddd;
}.snake {background-color: #28a745;
}.food {background-color: #dc3545;
}
const board = document.getElementById('gameBoard');
const rows = 20, cols = 20;
let snake = [{ x: 10, y: 10 }];
let direction = { x: 0, y: -1 };
let food = createFood();
let gameOver = false;function createBoard() {for (let row = 0; row < rows; row++) {for (let col = 0; col < cols; col++) {const cell = document.createElement('div');cell.classList.add('cell');board.appendChild(cell);}}
}function updateBoard() {const cells = document.querySelectorAll('.cell');cells.forEach(cell => cell.className = 'cell');snake.forEach(segment => {const index = segment.y * cols + segment.x;cells[index].classList.add('snake');});const foodIndex = food.y * cols + food.x;cells[foodIndex].classList.add('food');
}function createFood() {let newFood;do {newFood = { x: Math.floor(Math.random() * cols), y: Math.floor(Math.random() * rows) };} while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));return newFood;
}function moveSnake() {const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };if (head.x < 0 || head.x >= cols || head.y < 0 || head.y >= rows || snake.some(segment => segment.x === head.x && segment.y === head.y)) {gameOver = true;return;}snake.unshift(head);if (head.x === food.x && head.y === food.y) {food = createFood();} else {snake.pop();}
}document.addEventListener('keydown', event => {switch (event.key) {case 'ArrowUp':if (direction.y === 0) direction = { x: 0, y: -1 };break;case 'ArrowDown':if (direction.y === 0) direction = { x: 0, y: 1 };break;case 'ArrowLeft':if (direction.x === 0) direction = { x: -1, y: 0 };break;case 'ArrowRight':if (direction.x === 0) direction = { x: 1, y: 0 };break;}
});createBoard();const gameLoop = setInterval(() => {if (gameOver) {clearInterval(gameLoop);alert('Game Over!');return;}moveSnake();updateBoard();
}, 100);
这段代码创建了一个基础的贪吃蛇游戏,包括了游戏区域的渲染、蛇的移动与增长、食物的生成及蛇吃到食物后的增长逻辑。通过监听键盘事件改变蛇的方向,并使用setInterval函数控制游戏循环。请注意,这只是一个基础示例,实际开发中可能需要添加更多功能如分数统计、游戏重置等。