|
|
当然可以帮你生成一个贪吃蛇游戏的网页代码!下面是一个简单的示例代码:
- <!DOCTYPE html>
- <html>
- <head>
- <title>贪吃蛇游戏</title>
- <style>
- canvas {
- border: 1px solid black;
- background-color: #f0f0f0;
- }
- </style>
- </head>
- <body>
- <canvas id="gameCanvas" width="400" height="400"></canvas>
- <script>
- const canvas = document.getElementById("gameCanvas");
- const ctx = canvas.getContext("2d");
- const snakeSize = 10;
- let snake = [
- { x: 200, y: 200 },
- { x: 190, y: 200 },
- { x: 180, y: 200 },
- ];
- function drawSnakePart(snakePart) {
- ctx.fillStyle = 'green';
- ctx.fillRect(snakePart.x, snakePart.y, snakeSize, snakeSize);
- ctx.strokeStyle = 'darkgreen';
- ctx.strokeRect(snakePart.x, snakePart.y, snakeSize, snakeSize);
- }
- function drawSnake() {
- snake.forEach(drawSnakePart);
- }
- function main() {
- setTimeout(function onTick() {
- clearCanvas();
- drawSnake();
- moveSnake();
- main();
- }, 100);
- }
- function clearCanvas() {
- ctx.fillStyle = 'lightgrey';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- }
- function moveSnake() {
- const head = { x: snake[0].x, y: snake[0].y };
- switch (direction) {
- case 'UP':
- head.y -= snakeSize;
- break;
- case 'DOWN':
- head.y += snakeSize;
- break;
- case 'LEFT':
- head.x -= snakeSize;
- break;
- case 'RIGHT':
- head.x += snakeSize;
- break;
- }
- snake.unshift(head);
- snake.pop();
- }
- let direction = 'RIGHT';
- document.addEventListener('keydown', changeDirection);
- function changeDirection(event) {
- const LEFT_KEY = 37;
- const RIGHT_KEY = 39;
- const UP_KEY = 38;
- const DOWN_KEY = 40;
- const keyPressed = event.keyCode;
- const goingUp = direction === 'UP';
- const goingDown = direction === 'DOWN';
- const goingRight = direction === 'RIGHT';
- const goingLeft = direction === 'LEFT';
- if (keyPressed === LEFT_KEY && !goingRight) {
- direction = 'LEFT';
- }
- if (keyPressed === UP_KEY && !goingDown) {
- direction = 'UP';
- }
- if (keyPressed === RIGHT_KEY && !goingLeft) {
- direction = 'RIGHT';
- }
- if (keyPressed === DOWN_KEY && !goingUp) {
- direction = 'DOWN';
- }
- }
- main();
- </script>
- </body>
- </html>
复制代码
你可以将这段代码复制粘贴到一个新建的 HTML 文件中,然后用浏览器打开该文件,就可以开始玩贪吃蛇游戏了!游戏目前只实现了蛇的移动和基本显示,你可以进一步完善游戏功能,比如添加食物、碰撞检测等。祝游戏愉快!如果你有问题,随时来问我哦! |
|