上代码
希望大家喜欢
在线演示
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>snake</title>
<style>
div {height: 400px;width: 400px;border: 1px solid #000;margin: 40px auto 0 auto;}
</style>
</head>
<body>
<div><canvas id="canvas" height="400" width="400"></canvas></div>
<button id="asd" style="margin: auto;display: block">开始</button>
</body>
</html>
js部分
! function snake() {
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
var snake = [25, 24, 23]
var direction = 1 //1向右 20向下 -20向上 -1向左
var speed = 300
var nextPosition,foodPosition
var foodPool = new Array(400)
!function () {
foodPool.fill(1)
for (var i = 0; i < foodPool.length; i++) {
foodPool[i] = i + 1
}
}()
function addFood() {
//从食物池中剔除蛇身所占用的位置,防止食物出现在蛇身上
for(var i=0;i<snake.length;i++){
foodPool.splice(foodPool.indexOf(snake[i]),1)
}
speed = speed - Math.floor(snake.length/2)
console.log(speed);
foodPosition = getRandomItemFromArray(foodPool)
draw(foodPosition)
}
//辅助函数,随机从数组中取出一个值
function getRandomItemFromArray(arr) {
var ss = Math.floor(Math.random() * (arr.length))
var result = arr[ss]
var ss = arr.splice(ss, 1)
return ss[0]
}
//传入 数值 颜色(可选),渲染到页面
function draw(num, color) {
ctx.fillStyle = color || "pink";
var x = num % 20
var y = Math.floor(num / 20)
ctx.fillRect(x * 20, y * 20, 18, 18);
}
//初始化蛇
function render(arr,color) {
ctx.fillStyle = color || "red";
arr.forEach(element => {
var x = element % 20
var y = Math.floor(element / 20)
ctx.fillRect(x * 20, y * 20 , 18, 18);
});
}
//添加事件,通过上下左右改变方向
document.getElementById("asd").onclick = move
document.addEventListener("keydown",function(e){
var oppositeDirection = -direction
var newDirection = [-1, -20, 1, 20 ][e.which - 37]
if(oppositeDirection == newDirection){
return
}
direction = newDirection
})
//蛇身移动
function move(){
nextPosition = snake[0] + direction
//判断失败条件
if (snake.indexOf(nextPosition) > 0 || nextPosition<0 || nextPosition>399 || (direction == 1 && nextPosition % 20 == 0) || direction == -1 && nextPosition % 20 == 19)
{return alert("GAME OVER");}
snake.unshift(nextPosition);
draw(nextPosition, "red");
if(nextPosition == foodPosition){
addFood()
}else{
draw(snake.pop(), "white");
}
setTimeout(arguments.callee, speed);
}
function init() {
addFood()
render(snake)
}
init()
}()