写一个贪吃蛇 js代码
时间: 2023-08-31 13:27:53 浏览: 106
### 回答1:
```
答:// 定义贪吃蛇的变量
var snakeX = 100;
var snakeY = 100;
var snakeSize = 10;// 定义食物的变量
var foodX;
var foodY;// 初始化一个canvas
function setup() {
createCanvas(400, 400);
background(220);
frameRate(10);
placeFood();
}// 每帧重新绘制画布
function draw() {
background(220); // 画出贪吃蛇
fill(255);
rect(snakeX, snakeY, snakeSize, snakeSize); // 画出食物
fill(255, 0, 0);
rect(foodX, foodY, snakeSize, snakeSize); // 移动贪吃蛇
moveSnake(); // 检查是否吃到食物
checkFood();
}// 移动贪吃蛇
function moveSnake() {
snakeX = snakeX + 10;
snakeY = snakeY + 10;
}// 放置食物
function placeFood() {
foodX = random(width);
foodY = random(height);
}// 检查是否吃到食物
function checkFood() {
if (dist(snakeX, snakeY, foodX, foodY) == 0) {
placeFood();
}
}
```
### 回答2:
贪吃蛇是一款经典的游戏,通过控制蛇的移动让它吃到食物,并避免撞到边界或自身。以下是一个使用JavaScript编写的简易贪吃蛇游戏的代码示例:
```javascript
// 创建画布
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const box = 20;
// 初始化蛇的位置和长度
let snake = [];
snake[0] = { x: 10 * box, y: 10 * box };
// 初始化食物的位置
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
// 初始化分数
let score = 0;
// 监听用户输入控制蛇的方向
document.addEventListener("keydown", direction);
let d;
function direction(event) {
if (event.keyCode == 37 && d != "RIGHT") {
d = "LEFT";
} else if (event.keyCode == 38 && d != "DOWN") {
d = "UP";
} else if (event.keyCode == 39 && d != "LEFT") {
d = "RIGHT";
} else if (event.keyCode == 40 && d != "UP") {
d = "DOWN";
}
}
// 绘制游戏画面
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制蛇的身体
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "green" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "black";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
// 绘制食物
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
// 移动蛇的位置
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (d == "LEFT") snakeX -= box;
if (d == "UP") snakeY -= box;
if (d == "RIGHT") snakeX += box;
if (d == "DOWN") snakeY += box;
// 当蛇吃到食物时
if (snakeX === food.x && snakeY === food.y) {
score++;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
// 移除蛇的尾部
snake.pop();
}
// 创建新的蛇头
const newHead = { x: snakeX, y: snakeY };
// 检查游戏结束条件
if (
snakeX < 0 ||
snakeX >= canvas.width ||
snakeY < 0 ||
snakeY >= canvas.height ||
checkCollision(newHead, snake)
) {
clearInterval(game);
}
// 将新的蛇头添加到蛇的数组中
snake.unshift(newHead);
// 绘制分数
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, box, box);
}
// 检查蛇是否碰撞到自身
function checkCollision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
// 调用绘制函数,设置游戏循环
let game = setInterval(draw, 150);
```
以上是一个基于HTML5 Canvas元素和JavaScript编写的简单贪吃蛇游戏代码示例。该代码实现了基本的游戏逻辑,包括蛇的移动、吃食物、判断游戏结束等功能,玩家可通过键盘控制蛇的方向。
### 回答3:
贪吃蛇是一个经典的游戏,下面是一个简单的贪吃蛇的JS代码实现。
首先,我们需要定义贪吃蛇的各种属性和初始化位置:
```javascript
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var blockSize = 10;
var snake = [];
snake[0] = {x: 10, y: 10};
var direction = 'right';
function drawSnake() {
for (var i = 0; i < snake.length; i++) {
context.fillStyle = (i === 0) ? 'green' : 'white';
context.fillRect(snake[i].x * blockSize, snake[i].y * blockSize, blockSize, blockSize);
context.strokeStyle = 'black';
context.strokeRect(snake[i].x * blockSize, snake[i].y * blockSize, blockSize, blockSize);
}
}
```
然后,我们需要定义贪吃蛇的运动和吃食物的行为:
```javascript
function moveSnake() {
var headX = snake[0].x;
var headY = snake[0].y;
if (direction === 'right') headX++;
else if (direction === 'left') headX--;
else if (direction === 'up') headY--;
else if (direction === 'down') headY++;
var newHead = {
x: headX,
y: headY
};
snake.unshift(newHead);
snake.pop();
}
function eatFood() {
if (snake[0].x === food.x && snake[0].y === food.y) {
var tail = {
x: snake[snake.length - 1].x,
y: snake[snake.length - 1].y
}
snake.push(tail);
generateFood();
}
}
```
最后,我们需要定义游戏结束和重新开始的行为:
```javascript
function checkCollision() {
for (var i = 1; i < snake.length; i++) {
if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
gameOver();
}
}
if (snake[0].x === -1 || snake[0].x === canvas.width / blockSize || snake[0].y === -1 || snake[0].y === canvas.height / blockSize) {
gameOver();
}
}
function restartGame() {
snake = [];
snake[0] = {x: 10, y: 10};
direction = 'right';
generateFood();
gameLoop();
}
function gameOver() {
clearInterval(interval);
alert('游戏结束!');
restartGame();
}
```
最后,我们需要定义游戏循环函数和生成食物的函数:
```javascript
function generateFood() {
food = {
x: Math.floor(Math.random() * (canvas.width / blockSize)),
y: Math.floor(Math.random() * (canvas.height / blockSize))
}
}
function gameLoop() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
moveSnake();
eatFood();
checkCollision();
drawFood();
var interval = setInterval(gameLoop, 100);
}
function drawFood() {
context.fillStyle = 'red';
context.fillRect(food.x * blockSize, food.y * blockSize, blockSize, blockSize);
context.strokeStyle = 'black';
context.strokeRect(food.x * blockSize, food.y * blockSize, blockSize, blockSize);
}
```
这样就完成了一个简单的贪吃蛇的JS代码实现,你可以将上述代码复制到一个HTML文件中,然后通过浏览器打开这个HTML文件,就可以玩贪吃蛇游戏了。
阅读全文