用javascript 写个贪吃蛇
时间: 2023-03-13 16:16:58 浏览: 185
用javascript写贪吃蛇其实不是很难,你可以首先创建一个画布,然后使用javascript的绘图函数创建出蛇的身体,最后实现碰撞检测,使得蛇能够吃掉食物,并且随着它吃到食物越多,蛇的身体长度也会变长。
相关问题
用JavaScript写一个贪吃蛇
好的,我可以给你一个JavaScript贪吃蛇的示例代码:
```
<!DOCTYPE html>
<html>
<head>
<style>
#game-board {
width: 500px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script>
const board = document.getElementById("game-board");
const ctx = board.getContext("2d");
let snake = [];
let food = {};
let score = 0;
let direction = "right";
for (let i = 0; i < 5; i++) {
snake.push({x: i, y: 0});
}
function createFood() {
food = {
x: Math.floor(Math.random() * (board.width / 10)),
y: Math.floor(Math.random() * (board.height / 10)),
};
for (let i = 0; i < snake.length; i++) {
if (food.x === snake[i].x && food.y === snake[i].y) {
createFood();
}
}
}
function drawSnake() {
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "red" : "green";
ctx.fillRect(
snake[i].x * 10,
snake[i].y * 10,
10,
10
);
}
}
function updateSnake() {
let x = snake[0].x;
let y = snake[0].y;
if (direction === "right") {
x++;
} else if (direction === "left") {
x--;
} else if (direction === "up") {
y--;
} else if (direction === "down") {
y++;
}
if (x < 0 || x >= board.width / 10 || y < 0 || y >= board.height / 10) {
alert("Game Over");
window.location.reload();
}
if (x === food.x && y === food.y) {
score++;
createFood();
} else {
snake.pop();
}
snake.unshift({x: x, y: y});
}
function drawFood() {
ctx.fillStyle = "yellow";
ctx.fillRect(food.x * 10, food.y * 10, 10, 10);
}
function drawScore() {
ctx.fillStyle = "black";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 10, board.height - 10);
}
document.onkeydown = function (e) {
if (e.keyCode === 37 && direction !== "right") {
direction = "left";
}
可以用JavaScript语言写个贪吃蛇吗
当然可以!JavaScript 是一种强大的编程语言,可以用来开发各种类型的应用,包括贪吃蛇游戏。您可以使用 JavaScript 和 HTML5 Canvas 来创建游戏界面,然后使用 JavaScript 实现游戏的逻辑和交互。
阅读全文