HTML贪吃蛇游戏代码 - 带开始和结束功能
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 500px;
height: 500px;
border: 1px solid black;
position: relative;
margin: 0 auto;
}
<pre><code> .snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</code></pre>
</head>
<body>
<button onclick='start()'>开始游戏</button>
<button onclick='stop()'>结束游戏</button>
<div id='game-board'></div>
<script>
var board = document.getElementById('game-board');
var snake = [{x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}];
var food = null;
var direction = 'right';
var timer = null;
<pre><code> function start() {
snake = [{x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}];
food = null;
direction = 'right';
timer = setInterval(move, 100);
document.addEventListener('keydown', changeDirection);
render();
}
function stop() {
clearInterval(timer);
document.removeEventListener('keydown', changeDirection);
board.innerHTML = '';
}
function move() {
var head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case 'right':
head.x++;
break;
case 'left':
head.x--;
break;
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
generateFood();
} else {
snake.pop();
}
render();
}
function changeDirection(event) {
switch (event.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 render() {
board.innerHTML = '';
snake.forEach(function(segment) {
var div = document.createElement('div');
div.className = 'snake';
div.style.left = segment.x * 20 + 'px';
div.style.top = segment.y * 20 + 'px';
board.appendChild(div);
});
if (food === null) {
generateFood();
}
var div = document.createElement('div');
div.className = 'food';
div.style.left = food.x * 20 + 'px';
div.style.top = food.y * 20 + 'px';
board.appendChild(div);
}
function generateFood() {
var x = Math.floor(Math.random() * 25);
var y = Math.floor(Math.random() * 25);
if (snake.some(function(segment) {
return segment.x === x && segment.y === y;
})) {
generateFood();
} else {
food = {x: x, y: y};
}
}
</script>
</code></pre>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/mKql 著作权归作者所有。请勿转载和采集!