[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#map {
width: 800px;
height: 600px;
background-color: #ccc;
position: relative;
}
</style>
</head>
<body>
<div id=" map "></div>
<script src ="tools.js" ></script>
<script src ="food.js" ></script>
<script>
var map = document.getElementById('div');
var food = new Food();
food.render();
</script>
</body>
</html>
[JavaScript] 纯文本查看 复制代码
// 关于食物对象代码
function Food(obj) {
obj = obj || {};
this.width = obj.width || 20;
this.height = obj.height || 20;
this.bgc = obj.bgc || 'green';
this.x = obj.x || 0;
this.y = obj.y || 0;
}
// 将食物渲染上页面的代码
Food.prototype.render = function () {
var div = document.createElement('div');
div.style.width = this.width + 'px';
div.style.height = this.height + 'px';
div.style.backgroundColor = this.bgc;
/*
* 由于在贪吃蛇的游戏中,Food只new一次,所以获取随机数的代码不卸载构造函数中,
* 而是要卸载render中,为什么要卸载render中呢?
* 是因为,如果蛇吃到了食物,我们还要调用render方法
* */
this.x = Tool.getRandom(0, map.offsetWidth - this.width);
this.y = Tool.getRandom(0, map.offsetHeight - this.height);
div.style.left = this.x + 'px';
div.style.top = this.y + 'px';
div.style.position = 'absolute';
map.appendChild('div');
}