经典贪吃蛇游戏 - 在线玩
<html>
<head>
<title>经典贪吃蛇游戏 - 在线玩</title>
</head>
<body>
<canvas id="snakeCanvas" width="400" height="400"></canvas>
<script type="text/javascript">
// Create the canvas
var canvas = document.getElementById("snakeCanvas");
var ctx = canvas.getContext("2d");
// Create the snake
var snakeSize = 10;
var snake;
var snakeLength;
// Create the food
var food;
// Create the score
var score;
<pre><code> // Initialize the game
function init() {
createSnake();
createFood();
score = 0;
// If the snake hits the wall it will restart
if (checkCollision(snakeHead.x, snakeHead.y, canvas.width, canvas.height)) {
// Restart the game
init();
}
// Call the main loop every 60 fps
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
// Create the snake
function createSnake() {
var length = 5;
snake = [];
for (var i = length - 1; i >= 0; i--) {
snake.push({ x: i, y: 0 });
}
}
// Create the food
function createFood() {
food = {
x: Math.round(Math.random() * (canvas.width - snakeSize) / snakeSize),
y: Math.round(Math.random() * (canvas.height - snakeSize) / snakeSize),
};
}
// Check for collision
function checkCollision(x, y, w, h) {
if (x < 0 || x > w || y < 0 || y > h) return true;
return false;
}
// Paint the snake
function paint() {
// Paint the canvas
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, canvas.width, canvas.height);
// Make the snake move
var snakeX = snake[0].x;
var snakeY = snake[0].y;
// Change the snake direction
if (direction == "right") snakeX++;
else if (direction == "left") snakeX--;
else if (direction == "up") snakeY--;
else if (direction == "down") snakeY++;
// If the snake eats food it will grow
if (snakeX == food.x && snakeY == food.y) {
var tail = { x: snakeX, y: snakeY };
score++;
// Create new food
createFood();
} else {
var tail = snake.pop();
tail.x = snakeX;
tail.y = snakeY;
}
// Put the tail as the first cell
snake.unshift(tail);
// Paint the snake
for (var i = 0; i < snake.length; i++) {
var c = snake[i];
// Paint the food
paintCell(food.x, food.y);
// Paint the snake
paintCell(c.x, c.y);
}
// Paint the score
var scoreText = "Score: " + score;
ctx.fillText(scoreText, 5, canvas.height - 5);
}
// Paint a cell
function paintCell(x, y) {
ctx.fillStyle = "blue";
ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
ctx.strokeStyle = "white";
ctx.strokeRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
}
// Handle keyboard controls
var direction;
document.onkeydown = function (e) {
var key = e.which;
if (key == "37" && direction != "right") direction = "left";
else if (key == "38" && direction != "down") direction = "up";
else if (key == "39" && direction != "left") direction = "right";
else if (key == "40" && direction != "up") direction = "down";
};
// Start the game
init();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lf3u 著作权归作者所有。请勿转载和采集!