html加css加js生成贪吃蛇小游戏
时间: 2023-05-22 08:01:38 浏览: 102
html+js+css实现的贪吃蛇游戏
可以使用HTML、CSS和JavaScript来生成贪吃蛇小游戏。首先,需要创建一个HTML页面,然后使用CSS来设计游戏界面,最后使用JavaScript编写游戏逻辑。以下是一个简单的示例代码:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇小游戏</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="game"></div>
<script src="script.js"></script>
</body>
</html>
```
CSS代码:
```
#game {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
}
.snake {
width: 10px;
height: 10px;
background-color: green;
position: absolute;
}
.food {
width: 10px;
height: 10px;
background-color: red;
position: absolute;
}
```
JavaScript代码:
```
var game = document.getElementById("game");
var snake = [{x: 0, y: 0}];
var food = {x: 0, y: 0};
var direction = "right";
var score = 0;
function createSnake() {
for (var i = 0; i < snake.length; i++) {
var div = document.createElement("div");
div.className = "snake";
div.style.left = snake[i].x + "px";
div.style.top = snake[i].y + "px";
game.appendChild(div);
}
}
function createFood() {
food.x = Math.floor(Math.random() * 40) * 10;
food.y = Math.floor(Math.random() * 40) * 10;
var div = document.createElement("div");
div.className = "food";
div.style.left = food.x + "px";
div.style.top = food.y + "px";
game.appendChild(div);
}
function moveSnake() {
var head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case "right":
head.x += 10;
break;
case "left":
head.x -= 10;
break;
case "up":
head.y -= 10;
break;
case "down":
head.y += 10;
break;
}
snake.unshift(head);
if (head.x == food.x && head.y == food.y) {
score++;
createFood();
} else {
snake.pop();
}
for (var i = 0; i < snake.length; i++) {
var div = document.getElementsByClassName("snake")[i];
div.style.left = snake[i].x + "px";
div.style.top = snake[i].y + "px";
}
}
function checkCollision() {
var head = snake[0];
if (head.x < 0 || head.x >= 400 || head.y < 0 || head.y >= 400) {
clearInterval(interval);
alert("游戏结束,得分:" + score);
}
for (var i = 1; i < snake.length; i++) {
if (head.x == snake[i].x && head.y == snake[i].y) {
clearInterval(interval);
alert("游戏结束,得分:" + score);
}
}
}
createSnake();
createFood();
var interval = setInterval(function() {
moveSnake();
checkCollision();
}, 100);
document.addEventListener("keydown", function(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;
}
});
```
阅读全文