写一个贪吃蛇 JS代码
时间: 2024-01-07 20:03:17 浏览: 5
js贪吃蛇网页版游戏特效代码分享(挑战十关)
我可以给你一些基本的代码:// 设置画布大小
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let box = 32;
let score = 0;// 创建蛇
let snake = [];
snake[0] = {
x : 9 * box,
y : 10 * box
};// 创建食物
let food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}// 画出蛇
function draw() {
ctx.fillStyle = "white";
ctx.fillRect(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.fillStyle = "red";
ctx.fillRect(food.x,food.y,box,box);
}// 创建控制蛇移动的函数
let d;document.addEventListener("keydown",direction);function direction(event){
let key = event.keyCode;
if( key == 37 && d != "RIGHT"){
d = "LEFT";
}else if(key == 38 && d != "DOWN"){
d = "UP";
}else if(key == 39 && d != "LEFT"){
d = "RIGHT";
}else if(key == 40 && d != "UP"){
d = "DOWN";
}
}// 控制蛇移动
function move(){
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()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
}else{
// 否则去掉尾部,移动蛇头
snake.pop();
} let newHead = {
x : snakeX,
y : snakeY
} // 添加新头
snake.unshift(newHead);
}// 开始游戏
let game = setInterval(draw,100);
阅读全文