html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#map {
width: 800px;
height: 600px;
background-color: #ccc;
position: relative;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
<script src="js/food.js"></script>
<script src="js/snake.js"></script>
<script src="js/game.js"></script>
<script>
var map = document.getElementById("map");
/*
面向对象的思想
1、创建食物对象
2、创建蛇节对象和游戏对象
3、蛇移动
4、控制蛇移动的方向
5、蛇吃食物,食物消失,蛇身变长。食物刷新
*/
//实例化蛇对象
// var food = new Food(20, 20, "blue", "absolute", 0, 0);
// food.renderFood();
// 实例化蛇对象
// var snake = new Snake(20, 20, "absolute", "right", []);
// snake.renderSnake();
// 实例游戏对象
var game = new Game(new Food(20, 20, "blue", "absolute", 0, 0, []), new Snake(20, 20, "absolute", "right", []), map);
game.renderGame();
</script>
</html>
food object
function Food(width, height, bgColor, position, left, top) {
this.width = width
this.height = height
this.bgColor = bgColor
this.position = position
this.left = left
this.top = top
}
Food.prototype.renderFood = function () {
var foodBox = map.appendChild(document.createElement('div'))
foodBox.style.width = this.width + 'px'
foodBox.style.height = this.height + 'px'
foodBox.style.backgroundColor = this.bgColor
foodBox.style.position = this.position
// 随机产生食物
// 0-1* 800 = 792 8
this.left =
parseInt((Math.random() * map.clientWidth) / this.width) * this.width
this.top =
parseInt((Math.random() * map.clientHeight) / this.height) * this.height
foodBox.style.left = this.left + 'px'
foodBox.style.top = this.top + 'px'
}
snake object
function Snake(width, height, position, direction) {
this.width = width
this.height = height
// this.bgColor = bgColor
this.position = position
/* this.left = left
this.top = top */
this.direction = direction
this.body = [
// 蛇头
{
// x: 40,
x: 2,
y: 1,
color: 'yellow',
},
// 蛇身
{
// x: 20,
x: 1,
y: 1,
color: 'red',
},
// 蛇尾
{
x: 0,
y: 1,
color: 'red',
},
]
}
Snake.prototype.renderSnake = function () {
for (var i = 0; i < this.body.length; i++) {
var snakeBox = map.appendChild(document.createElement('div'))
snakeBox.style.width = this.width + 'px'
snakeBox.style.height = this.height + 'px'
snakeBox.style.position = this.position
// snakeBox.style.direction =this.direction
snakeBox.style.left = this.body[i].x * this.width + 'px'
snakeBox.style.top = this.body[i].y * this.height + 'px'
snakeBox.style.backgroundColor = this.body[i].color
}
}
game object
function Game(food, snake, map) {
this.food = food
this.snake = snake
this.map = map
}
// 游戏渲染方法
Game.prototype.renderGame = function () {
this.food.renderFood()
this.snake.renderSnake()
}