Demo介绍
用prototype构造函数写的贪吃蛇。直接复制代码到html文件就可以运行。学任何一门语言 练习逻辑都会写个贪吃蛇啥的,这不来了嘛
这个demo通过几个方法基本无HTML和css完全动态生成界面元素。基本注释都在代码中
源码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document</title>
</head>
<body>
<button>开始</button>
</body>
<script>
// 地图
function Map() {
// 创建一个div
this.map = document.createElement('div')
this.setStyle(this.map, {
width: "700px",
height: '500px',
border: "10px solid #ccc",
backgroundColor: "#abcdef",
position: "relative"
})
// 将div放到body中
document.body.appendChild(this.map)
}
// 添加一个设置样式的函数
Map.prototype.setStyle = function (ele, styleObj) {
for (var attr in styleObj) {
ele.style[attr] = styleObj[attr]
}
}
// 添加一个获取随机数的方法
Map.prototype.getRandom = function (a, b = 0) {
var max = Math.max(a, b);
var min = Math.min(a, b)
return Math.floor(Math.random() * (max - min)) + min
}
var m = new Map()
// 食物
function Food() {
// 创建一个小div
this.food = document.createElement('div')
m.setStyle(this.food, {
width: "10px",
height: "10px",
backgroundColor: "blue",
position: "absolute",
left: parseInt(m.getRandom(m.map.clientWidth - 10)