创建js文件和css文件还有一个html文件放于同一目录下可以制作一个简单的贪吃蛇游戏。代码和效果图如下:
food.js
编写蛇对象Snake.js
编写游戏主对象Game.js
将以上三个js文件放到一个文件夹scripts下面
最后一步,小编使用的是visual studio code应用程序写的一个html文件如下:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<title>贪吃蛇</title>
<link rel="stylesheet" href="../css/bootstrap.min.css" />
<style>
.container{
width: 100%;
padding-top: 10px;
position: relative;
}
.map{
width: 600px;
height: 600px;
background-color: white;
position: relative;
margin: 0 auto;
padding-top: 10px;
border: 1px #ccc solid;
background: -webkit-linear-gradient(top,transparent 19px,#ccc 20px),
-webkit-linear-gradient(left,transparent 19px,#ccc 20px);
background: -moz-linear-gradient(top,transparent 19px,#ccc 20px),
-moz-linear-gradient(left,transparent 19px,#ccc 20px);
background: -o-linear-gradient(top,transparent 19px,#ccc 20px),
-o-linear-gradient(left,transparent 19px,#ccc 20px);
background: -ms-linear-gradient(top,transparent 19px,#ccc 20px),
-ms-linear-gradient(left,transparent 19px,#ccc 20px);
background: linear-gradient(top,transparent 19px,#ccc 20px),
linear-gradient(left,transparent 19px,#ccc 20px);
-webkit-background-size: 19px 20px;
-moz-background-size: 20px 20px;
background-size: 20px 20px;
}
.btn-operation{
width: 600px;
margin: 0 auto;
height: 40px;
line-height: 40px;
text-align: center;
}
</style>
<body>
<div class="container">
<div id="map" class="map"></div>
<div class="btn-operation">
<button type="button" class="btn btn-danger" οnclick="startGame()">
开始
</button>
<button type="button" class="btn btn-warning" οnclick="pauseGame()">
暂停
</button>
<button type="button" class="btn btn-info" οnclick="restartGame()">
重新开始
</button>
</div>
</div>
<script src="../scripts/food.js"></script>
<script src="./scripts/snake.js"></script>
<script src="./scripts/game.js"></script>
<script>
var game = new Game(document.getElementById('map'));
game.init();
function startGame(){
game.start();
this.disabled = !this.disabled;
}
function pauseGame(){
game.pause();
}
function restartGame(){
game._init();
game.init();
}
</script>
</body>
</html>