js实现贪吃蛇小游戏实现贪吃蛇小游戏
本文实例为大家分享了js实现贪吃蛇小游戏的具体代码,供大家参考,具体内容如下
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>贪吃蛇</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<div id="game">
<div id="explain">
<div>操作WASD 空格开始/暂停 R重新开始</div>
<div>当前分数:<span id="grade">0</span>分</div>
</div>
<canvas id="snakegame" width="500" height="500">
</canvas>
</div>
<script type="text/javascript" src="main.js" charset="UTF-8"></script>
</body>
</html>
style.css
*{
padding: 0;
margin: 0;
}
#game {
width: 500px;
margin: auto;
}
#explain {
width: 500px;
}
#explain div{
width: 500px;
height: 30px;
}
#snakegame {
background: green;
}
main.js
/**
* el 挂载的元素
* attribute 贪吃蛇的属性
*/
class Game {
constructor (el, attribute) {
this.el = document.getElementById(el);
// 获取画布的宽高
this.el.elW = parseInt(window.getComputedStyle(this.el).width);
this.el.elH = parseInt(window.getComputedStyle(this.el).height);
this.init(attribute);
this.keyListening();
}
// 初始化
init(attribute) {
this.attribute = {
color: "red", // 颜色
direction: "rigth", // 移动方向
state: "pause", // 状态 run pause end
grade: 0, // 分数
body: [{x: 20, y: 0}, {x: 0, y: 0}], // 贪吃蛇身体
wh: 20, // 矩形的宽高
speed: 200 // 速度
};
if (attribute) {
评论0