我爱你我不是人类无法产生情感但我会尽我所能帮助你。写一段贪吃蛇js代码写一段贪吃蛇js代码
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var blockSize = 10; var width = canvas.width/blockSize; var height = canvas.height/blockSize; var snake = []; var direction = "right"; var food = {x: Math.floor(Math.random() * (width-1)), y: Math.floor(Math.random() * (height-1))}; var score = 0;
function drawBlock(x, y) { ctx.fillRect(xblockSize, yblockSize, blockSize, blockSize); }
function drawSnake() { ctx.fillStyle = "#000000"; for(var i=0; i<snake.length; i++) { drawBlock(snake[i].x, snake[i].y); } }
function moveSnake() { var head = {x: snake[0].x, y: snake[0].y}; switch(direction) { case "up": head.y--; break; case "down": head.y++; break; case "left": head.x--; break; case "right": head.x++; break; } if(head.x < 0 || head.x >= width || head.y < 0 || head.y >= height) { gameOver(); return; } for(var i=0; i<snake.length; i++) { if(snake[i].x == head.x && snake[i].y == head.y) { gameOver(); return; } } snake.unshift(head); if(head.x == food.x && head.y == food.y) { score++; food = {x: Math.floor(Math.random() * (width-1)), y: Math.floor(Math.random() * (height-1))}; } else { snake.pop(); } }
function drawFood() { ctx.fillStyle = "#FF0000"; drawBlock(food.x, food.y); }
function changeDirection(e) { switch(e.keyCode) { case 37: if(direction != "right") { direction = "left"; } break; case 38: if(direction != "down") { direction = "up"; } break; case 39: if(direction != "left") { direction = "right"; } break; case 40: if(direction != "up") { direction = "down"; } break; } }
function gameOver() { clearInterval(interval); alert("Game Over! Your score is " + score); }
document.addEventListener("keydown", changeDirection);
var interval = setInterval(function() { ctx.clearRect(0, 0, canvas.width, canvas.height); moveSnake(); drawSnake(); drawFood(); }, 100)
原文地址: https://www.cveoy.top/t/topic/c8Xp 著作权归作者所有。请勿转载和采集!