从0开始学web-day38-js进阶08

18 篇文章 0 订阅

1.复习
day37-js07复习
2.贪吃蛇案例
index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}
			.box {
				width: 600px;
				height: 600px;
				border: 1px solid #ccc;
				margin: 0 auto;
			}
			.box > .row {
				display: flex;
				
			}
			.box > .row span {
					width: 30px;
					height: 30px;
					border: 1px solid #ccc;
					box-sizing: border-box;
					/* 自适应背景图片 */
					background-size: cover;
				}
		</style>
	</head>
	<body>
		<!-- 引入各个类 -->
		<script src="./js/Snake.js" type="text/javascript" charset="utf-8"></script>
		<script src="./js/Block.js" type="text/javascript" charset="utf-8"></script>
		<script src="./js/Food.js" type="text/javascript" charset="utf-8"></script>
		<script src="./js/Game.js" type="text/javascript" charset="utf-8"></script>
		<script src="./js/Map.js" type="text/javascript" charset="utf-8"></script>
		
		<script type="text/javascript">
			// 定义蛇类所需要的所以图片
			var snakeObj = {
				// 头部
				head_pic: ['./img/1.png', './img/2.png', './img/3.png', './img/4.png'],
				// 身体
				body_pic: ['./img/5.png'],
				// 尾部
				tail_pic: ['./img/6.png', './img/7.png', './img/8.png', './img/9.png']
			}
			
			// 实例化各个类
			var snake = new Snake(snakeObj);
			// 传递图片
			var food = new Food(2, 6, './img/food.jpg');
			var map = new Map(20, 20, 600, 600);
			
			// 实例化的时候 传递图片
			var block = new Block('./img/block.png');
			
			// 实例化游戏类
			var g = new Game(map, snake, food, block);
			console.log(g);
		</script>
	</body>
</html>

Game.js

/***
* Game类   整个游戏类
* @map      map的实例化对象
* @snake    蛇类的实例化对象
* @food     食物的实例
* @block    障碍物的实例
**/
function Game(map, snake, food, block) {
	// 接收数据
	this.map = map;
	this.snake = snake;
	this.food = food;
	this.block = block;
	// 定时器句柄
	this.time = null;
	// 定义标记
	this.flag = null;
	
	// 执行初始化方法
	this.init();
}

// 定义初始化方法
Game.prototype.init = function() {
	// 渲染地图
	this.renderMap();
	// 渲染食物
	this.renderFood();
	// 渲染蛇
	this.renderSnake();
	// 渲染障碍物
	this.renderBlock();
	// 开始游戏
	this.start();
	// 绑定事件方法
	this.bindEvent();
}

// 渲染地图的方法
Game.prototype.renderMap = function() {
	// 本质上是找到map原型中的fill方法
	this.map.fill();
}
// 渲染食物的方法
Game.prototype.renderFood = function() {
	// 获取食物的左边
	var x = this.food.x;
	var y = this.food.y;
	// 渲染食物就是找到地图中食物的坐标系
	// console.log(this.map.dom.children[this.food.x].children[this.food.y]);
	// this.map.dom.children[this.food.x].children[this.food.y].style.backgroundColor = 'red';
	// 利用二维数组简化代码
	// this.map.arr[this.food.x][this.food.y].style.backgroundColor = 'red';
	
	// 替换成背景图片
	this.map.arr[x][y].style.backgroundImage = 'url('+ this.food.img_url +')';
}

// 定义渲染蛇的方法
Game.prototype.renderSnake = function() {
	// 获取蛇的头部
	var head = this.snake.arr[this.snake.arr.length - 1];
	// 替换头部图片
	this.map.arr[head.x][head.y].style.backgroundImage = 'url('+ this.snake.head_pic[this.snake.head_idx] +')';
	// 遍历蛇类中的数组
	for (var i = 1; i < this.snake.arr.length - 1; i++) {
		// 定义变量 简化书写
		var one = this.snake.arr[i];
		
		// 从地图中找到对应的元素并渲染
		// this.map.arr[one.x][one.y].style.backgroundColor = 'green';
		// 替换成背景图片
		this.map.arr[one.x][one.y].style.backgroundImage = 'url('+ this.snake.body_pic[0] +')';
	}
	// 获取蛇的尾部
	var tail = this.snake.arr[0];
	// 替换尾部图片
	this.map.arr[tail.x][tail.y].style.backgroundImage = 'url('+ this.snake.tail_pic[this.snake.tail_idx] +')';
}

// 绑定事件
Game.prototype.bindEvent = function() {
	// 缓存this
	var _this = this;
	// 为document绑定键盘事件
	document.onkeydown = function(e) {
		// 获取对应的编码
		var key = e.keyCode;
		// 判断
		if(key === 37 || key === 38 || key === 39 || key === 40) {
			// 调用蛇转向的方法
			_this.snake.change(key);
		}
	}
}

// 游戏开始
Game.prototype.start = function() {
	// 改变标记
	this.flag = true;
	// 缓存this
	var _this = this;
	// 赋值定时器
	this.time = setInterval(function() {
		// 移动
		_this.snake.move();
		// 检测是否撞墙
		_this.checkMap();
		
		// 检测是否吃到食物
		_this.checkFood();
		
		// 检测蛇是否撞到自己
		_this.checkSnake();
		
		// 检测是否撞到障碍物
		_this.checkBlock();
		
		// 判断游戏是否正常进行
		if(_this.flag) {
			// 清屏
			_this.map.clear();
			// 渲染食物
			_this.renderFood();
			// 渲染蛇
			_this.renderSnake();
			// 渲染障碍物
			_this.renderBlock();
		}
		
		
	}, 200)
}

// 游戏结束
Game.prototype.gameOver = function() {
	// 改变标记
	this.flag = false;
	// 终止定时器
	clearInterval(this.time);
	// 弹框提示
	alert("游戏结束");
}

// 边界判断
Game.prototype.checkMap = function() {
	// 获取蛇的头部
	var head = this.snake.arr[this.snake.arr.length - 1];
	
	// 判断是否撞向墙壁
	if(head.x < 0 || head.x >= this.map.row || head.y < 0 || head.y >= this.map.col) {
		// 终止游戏
		this.gameOver();
	}
}
// 定义重置食物的方法
Game.prototype.resetFood = function() {
	// 定义随机值
	var x = parseInt(Math.random() * this.map.row);
	var y = parseInt(Math.random() * this.map.col);
	
	// 检验与蛇之间的关系
	for(var i = 0; i < this.snake.arr.length; i++) {
		// 获取一节身体
		var one = this.snake.arr[i];
		// 拿着x和y值与蛇的每一节身体做比较
		if(one.x === x && one.y === y) {
			// 说明食物重合到蛇的身上
			// 递归处理
			
			// 终止执行
			alert("食物重合到了蛇身上");
			return;
			this.renderFood();
		}
	}
	
	// 检验与障碍物之间的关系
	for(var i = 0; i < this.block.arr.length; i++) {
		// 获取一节障碍物
		var one = this.block.arr[i];
		// 拿着x和y值与障碍物的每一节做比较
		if(one.x === x && one.y === y) {
			// 说明食物重合到障碍物的身上
			// 递归处理
			this.renderFood();
			// 终止执行
			alert("食物重合到了障碍物上了");
			return;
		}
	}
	
	// 本质上找到的是food中重置食物的方法
	this.food.resetFood(x, y);
}

// 检测是否吃到食物
Game.prototype.checkFood = function() {
	// 获取蛇的头部
	var head = this.snake.arr[this.snake.arr.length - 1];
	// 获取食物坐标系
	var x = this.food.x;
	var y = this.food.y;
	
	// 判断是否吃到食物
	if(head.x === x && head.y === y) {
		console.log("吃到食物了");
		
		// 调用重置食物的方法
		this.resetFood();
		
		// 调用蛇生长的方法
		this.snake.growUp();
	}
}

// 检测蛇是否吃到自己
Game.prototype.checkSnake = function() {
	// 获取蛇的头部
	var head = this.snake.arr[this.snake.arr.length - 1];
	
	// 遍历蛇数组
	// 注意:由于需要拿着数组的最后一项做匹配,所以要减一处理
	for(var i = 0; i < this.snake.arr.length - 1; i++) {
		// 获取蛇的一节身体
		var one = this.snake.arr[i];
		// 判断
		if(one.x === head.x && one.y === head.y) {
			console.log("蛇撞到自己了");
			// 执行游戏结束的方法
			this.gameOver();
			
		}
	}
}

// 渲染障碍物
Game.prototype.renderBlock = function() {
	// 遍历障碍物数组
	for(var i = 0; i < this.block.arr.length; i++) {
		// 获取x值
		var x = this.block.arr[i].x;
		// 获取x值
		var y = this.block.arr[i].y;
		
		// 在地图中找到对应的元素坐标并渲染
		// this.map.arr[x][y].style.backgroundColor = 'blue';
		// 渲染背景图片
		this.map.arr[x][y].style.backgroundImage = 'url('+ this.block.url +')';
		
	}
}

// 定义检测是否撞到障碍物
Game.prototype.checkBlock = function() {
	// 获取蛇的头部
	var head = this.snake.arr[this.snake.arr.length - 1];
	
	// 遍历障碍物数组
	for(var i = 0; i < this.block.arr.length; i++) {
		// 获取x值
		var x = this.block.arr[i].x;
		// 获取y值
		var y = this.block.arr[i].y;
		
		// 匹配
		if(head.x === x && head.y === y) {
			// 调用游戏结束函数
			this.gameOver();
		}
	}
	
}

Snake.js

/***
* Snake类     蛇类
* @pic_obj    蛇类所需的所有图片
**/
function Snake(pic_obj) {
	// 数组属性 用于存储蛇的每一节身体
	this.arr = [
		{x: 4, y: 4},
		{x: 4, y: 5},
		{x: 4, y: 6},
		{x: 4, y: 7},
		{x: 4, y: 8}
	];
	
	// 定义方向属性
	this.direction = 39;  // e.keyCode 左箭头37 上箭头38 右箭头39 下箭头40默认向右走
	
	// 定义锁
	this.lock = true;
	
	// 定义头部图片
	this.head_pic = pic_obj.head_pic;
	// 定义身体部图片
	this.body_pic = pic_obj.body_pic;
	// 定义尾部图片  
	this.tail_pic = pic_obj.tail_pic;
	
	// 定义头部图片的索引值
	this.head_idx = 2;
	// 定义尾部图片的索引值
	this.tail_idx = 0;
	
}

// 蛇移动的方法
Snake.prototype.move = function() {
	// 移动之后就可以开锁
	this.lock = true;
	
	// 根据老的头部创建新的头部
	var newHead = {
		x: this.arr[this.arr.length - 1].x,
		y: this.arr[this.arr.length - 1].y
	}
	
	// 判断蛇的方向
	if(this.direction === 37) {
		// 向左 此时x值不变y--
		newHead.y--;
	} else if(this.direction === 38) {
		// 向上 此时x--,y不变
		newHead.x--;
	} else if(this.direction === 39) {
		// 向右 此时x值不变,y++
		newHead.y++;
	} else if(this.direction === 40) {
		// 向下 此时y值不变,x++
		newHead.x++;
	}
	
	// 根据移动方向追加头部
	this.arr.push(newHead);
	// 删除尾部(数组的头一项)
	this.arr.shift();
	
	// 在移动的时候判断
	// 获取尾部
	var tail = this.arr[0];
	// 获取尾部的前一项
	var pg = this.arr[1];
	// 判断是否在同一行
	if(tail.x === pg.x) {
		// 判断y值的关系
		// if(tail.y > pg.y) {
		// 	this.tail_idx = 2;
		// } else {
		// 	this.tail_idx = 0;
		// }
		// 简写
		this.tail_idx = tail.y > pg.y ? 2 : 0;
	} else {
		// 说明在同一列
		// 判断x值的关系
		// if(tail.x > pg.x) {
		// 	this.tail_idx = 3;
		// } else {
		// 	this.tail_idx = 1;
		// }
		// 简写
		this.tail_idx = tail.x > pg.x ? 3 : 1;
	}
	
}
// 蛇转向的方法
Snake.prototype.change = function(direction) {
	// 判断锁的状态
	if(!this.lock) return;
	
	// 把锁关闭
	this.lock = false;
	
	// console.log(54, direction);
	
	// 判断用户传递的值是否合法
	// 如果蛇在水平方向移动 此时用户传递过来的37 或者是39都是不合法的
	var result = Math.abs(direction - this.direction);
	// 判断
	if(result === 2 || result === 0) return;
	
	// 赋值
	this.direction = direction;
	
	// 当蛇转向的时候更改蛇头部的图片索引
	// if(direction === 37) {
	// 	this.head_idx = 0;
	// } else if(direction === 38) {
	// 	this.head_idx = 1;
	// } else if(direction === 39) {
	// 	this.head_idx = 2;
	// } else if(direction === 40) {
	// 	this.head_idx = 3;
	// }
	
	// 当值匹配的比较多的时候还可以使用switch语句
	switch(+direction) {
		case 37:
			this.head_idx = 0;
			break;
		case 38:
			this.head_idx = 1;
			break;
		case 39:
			this.head_idx = 2;
			break;
		case 40:
			this.head_idx = 3;
			break;
			
	}
}

// 蛇生长的方法
Snake.prototype.growUp = function() {
	// 获取蛇的尾部
	var tail = this.arr[0];
	// 追加到数组的第一项
	this.arr.unshift(tail);
	
}

Map.js

/***
* Map类     地图类
* @row      行属性
* @col      列属性
* @width    总宽度属性
* @height   总高度属性
**/
function Map(row, col, width, height) {
	// 接收数据
	this.row = row;
	this.col = col;
	this.width = width;
	this.height = height;
	// 定义容器元素
	this.dom = document.createElement('div');
	this.dom.className = 'box';
	// 定义数组属性
	this.arr = [];
}
// 定义渲染方法
Map.prototype.fill = function() {
	// 遍历并创建20行
	for(var j = 0; j < this.row; j++) {
		// 创建行元素
		var row_dom = document.createElement('div');
		// 设置类名
		row_dom.className = 'row';
		
		// 创建一个行数组
		var row_arr = [];
		
		// 遍历并将行容器填满
		for(var i = 0; i < this.col; i++) {
			// 创建小方格元素
			var grad = document.createElement('span');
			// 设置类名
			grad.className = 'grad';
			
			// 追加元素
			row_dom.appendChild(grad);
			
			// 追加元素到行数组中
			row_arr.push(grad);
		}
		// 将填满的每一行追加到dom容器中
		this.dom.appendChild(row_dom);
		// 将填满的行数组放入到大数组中
		this.arr.push(row_arr);
	}
	// 上树
	document.body.appendChild(this.dom);
}

// 清屏方法
Map.prototype.clear = function() {
	// 遍历数组
	for(var i = 0; i < this.arr.length; i++) {
		// 二次遍历
		for(var j = 0; j < this.arr[i].length; j++) {
			// 找到对应元素来清除背景颜色
			this.arr[i][j].style.backgroundColor = '';
			// 清除背景图片
			this.arr[i][j].style.backgroundImage = '';
		}
	}
}

Block.js

/***
* block类    障碍物类
* @map       map的实例化对象
* @snake     蛇类的实例化对象
* @food      食物的实例
* @block     障碍物的实例
* @url       图片路径
**/
function Block(url) {
	// 数组属性 空数组用于存储每一节障碍物
	this.arr = [
		{ x: 8, y: 8 },
		{ x: 8, y: 9 },
        { x: 8, y: 10 },
        { x: 9, y: 10 },
        { x: 10, y: 10 },
        { x: 11, y: 10 },
        { x: 12, y: 10 }
	];
	// 接收图片
	this.url = url;
}

Food.js

/***
* Food类    食物类
* @x        食物的x值
* @y        食物的y值
* @img_url  图片的路径
**/
function Food(x, y, img_url) {
	this.x = x;
	this.y = y;
	// 接收
	this.img_url = img_url;
}
// 定义重置食物的方法
Food.prototype.resetFood = function(x, y) {
	// 重新赋值
	this.x = x;
	this.y = y;
}

3.Bom对象

<!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>
</head>
<body>
    <script>
    // 定义变量
    var a = 10;

    // 定义方法
    function demo() {
        console.log('demo');
    }


    // 内置构造函数
    console.log(window.Object);
    console.log(window.Array);
    console.log(window.Function);
    console.log(window.Number);
    console.log(window.String);
    console.log(window.Boolean);
    console.log(window.RegExp);

    // 顶级对象 (浏览器窗口对象)
    console.log(window);
    </script>
</body>
</html>

4.location

<!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>
</head>
<body>
    <button id="btn">点我重定向页面</button>
    <script>
    // location 对象:用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。
    // location.href = 'url地址' 
    // location.hostname 返回 web 主机的域名
    // location.pathname 返回当前页面的路径和文件名
    // location.port 返回 web 主机的端口 (80 或 443)
    // location.protocal 返回页面使用的web协议。 http:或https:


    // console.log(location);


    // 点击按钮 跳转页面
    btn.onclick = function() {
        location.href = 'https://www.baidu.com';
    }


    </script>
</body>
</html>

5.navigator对象

<!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>
</head>
<body>
    <script>
    // 获取浏览器信息
    console.log(window.navigator.userAgent);

    // 判断是否是火狐
    // console.log(/Firefox/.test(navigator.userAgent));

    // 字符串的形式验证
    console.log(navigator.userAgent.indexOf('Chrome') >= 0);
    </script>
</body>
</html>

6.screen对象

<!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>
</head>
<body>
    <script>
    // screen 对象:用来获取用户的屏幕信息。
    // height: 获取整个屏幕的高。
    console.log(screen.height);
    // width : 获取整个屏幕的宽。
    console.log(screen.width);
    // availHeight: 整个屏幕的高减去系统部件的高( 可用的屏幕宽度 )
    console.log(screen.availHeight);
    // availWidth : 整个屏幕的宽减去系统部件的宽(可用的屏幕高度 )
    console.log(screen.availWidth);


    console.log(window.screen);
        

    </script>
</body>
</html>

7.history对象

<!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>
</head>
<body>
    <script>
    // history 对象:包含浏览器的历史记录。
    // back() 返回上一页。
    // forward() 返回下一页。
    // go(“参数”) -1表示上一页,1表示下一页。

    console.log(window.history);
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值