贪吃蛇小游戏

贪吃蛇小游戏
闲来无事就可以玩玩
代码直接复制粘贴就可以玩, 拿去不谢

<!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>Document</title>
	<style>
		html,body {
			margin: 0;
			padding: 0;
			background-color: #333;
		}
		.content {
			width: 900px;
			height: 500px;
			margin: 0 auto;
			background-color: #f0f0f0;
			margin-top: 40px;
			margin-bottom: 10px;
			position: relative;
		}
		.start {
			text-align: center;
		}
		.start-game {
			width: 100px;
			height: 50px;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<div class="content"></div>
	<div class="start">
		<button class="start-game">点击开始游戏</button>
	</div>
	<script>
		let beforeFood  //表示一个之前的food dom
		let box = document.querySelector('.content')
		let btn = document.querySelector('.start')
		// 创建食物的类
		class Food {
			constructor(options) {
				options = options || {}
				this.width = options.width || 20
				this.height = options.height || 20
				this.x = options.x || 0
				this.y = options.y || 0
				this.color = options.color || this._randomColor()
			}

			// 食物的渲染函数
			render(box) {
				// 先删除之前创建的食物
				if(beforeFood) {
					box.removeChild(beforeFood)
				}

				// 再创建一个食物
				let newFood = document.createElement('div')
				beforeFood = newFood //让这个食物赋值给外面的food
				newFood.style.width = `${this.width}px`
				newFood.style.height = `${this.height}px`
				newFood.style.backgroundColor = this.color
				newFood.style.borderRadius = '20px'
				newFood.style.position = 'absolute'
				box.appendChild(newFood) //加入到 content 里面
				this.x = this._randomPosition(0, box.offsetWidth / newFood.offsetWidth - 1) * newFood.offsetWidth
				this.y = this._randomPosition(0, box.offsetHeight / newFood.offsetHeight - 1) * newFood.offsetHeight
				newFood.style.left = `${ this.x }px`
				newFood.style.top = `${ this.y }px`
			}

			// 内置函数,随机获取一种颜色
			_randomColor() {
				return `rgb(${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)})`
			}
			// 内置函数,随机一个位置
			_randomPosition(min,max) {
				return Math.floor(Math.random() * (max - min + 1)) + min;
			}
		}

		// 创建蛇的类
		class Snake {
			constructor(options) {
				options = options || {}
				this.width = options.width || 20
				this.height = options.height || 20
				this.direction = options.direction || 'right' //默认的方向
				this.body = [
					{x:4,y:4},
					{x:3,y:4},
					{x:2,y:4},
					{x:1,y:4},
				]
				this._arr = []
			}

			// 将snake渲染到页面上
			render(box) {
				// 先删除
				this.remove(box)
				this.body.forEach( (item,i) => {
					let snakeBody = document.createElement('div')
					this._arr.push(snakeBody) //这个是添加数组
					snakeBody.style.width = `${this.width}px`
					snakeBody.style.height = `${this.height}px`
					snakeBody.style.position = `absolute`
					if(i % 2 === 0) {
						if(i === 0) {
							snakeBody.style.backgroundColor = `red`
						}else {
							snakeBody.style.backgroundColor = `#fff`
						}
					}else {
						snakeBody.style.backgroundColor = `#333`
					}
					
					snakeBody.style.border = `1px solid red`
					snakeBody.style.borderRadius = `20px`
					snakeBody.style.left = `${ item.x * this.width }px`
					snakeBody.style.top = `${ item.y * this.height }px`
					box.appendChild(snakeBody) //这个是添加dom
				})
			}

			// 蛇的移动
			move() {
				for(let i = this.body.length - 1; i > 0; i--) {
					this.body[i].x  = this.body[i - 1].x
					this.body[i].y  = this.body[i - 1].y
				}
				// 判断,通过按着不同的按钮给不同的
				switch (this.direction) {
					case 'left':
						this.body[0].x -= 1
						break;
					case 'top':
						this.body[0].y -= 1
						break;
					case 'right':
						this.body[0].x += 1
						break;
					case 'bottom':
						this.body[0].y += 1
						break;
					default:
						break;
				}
			}
			// 先删除最后一个
			remove(box) {
				for(let i = 0,len = this._arr.length; i < len; i++) {
					box.removeChild(this._arr[0])
					this._arr.splice(0, 1)
				}
			}
		}

		// 创建游戏的类
		class Game {
			constructor(box) {
				this.box = box
				this.food =  new Food()
				this.snake = new Snake() 
				this._score = 0
				this._id;
			}
			// 游戏开始的函数
			start() {
				this.food.render(this.box)
				this.snake.render(this.box)
				this.autoMove()
				// 键盘监听事件
				document.onkeydown = (e) => {
					switch (e.keyCode) {
						case 37:
						// 判断是否按下去的键是否跟移动的方向是一样的,如果一样, return
							if(this.snake.direction === 'right') return
							this.snake.direction = 'left'
							break;
							case 38:
							if(this.snake.direction === 'bottom') return
							this.snake.direction = 'top'
							break;
							case 39:
							if(this.snake.direction === 'left') return
							this.snake.direction = 'right'
							break;
							case 40:
							if(this.snake.direction === 'top') return
							this.snake.direction = 'bottom'
							break;
						default:
							throw new Error(`只能按上下左右`)
					}
				}
			}
			// 自动移动事件
			autoMove() {
				this._id = setInterval(() => {
					this.snake.move()
					// 判断是否撞墙
					let flag = this.isGameOver()
					if(flag) return
					let head = this.snake.body[0]
					// 判断是否吃到食物
					if(head.x * this.snake.width === this.food.x && head.y * this.snake.height === this.food.y) {
						// 重新渲染
						this.food.render(box)
						this._score++
						// 让蛇变长
						let last = this.snake.body[this.snake.body.length - 1]
						this.snake.body.push({
							x : last.x,
							y : last.y
						})
					}
					// 重新渲染蛇皮
					this.snake.render(box)
				}, 150);
			}
			// 判断是否撞墙
			isGameOver() {
				let head = this.snake.body[0]
				let maxX = this.box.offsetWidth / this.snake.width - 1
				let maxY = this.box.offsetHeight / this.snake.height - 1
				if(head.x < 0 || head.y < 0|| head.x > maxX  || head.y > maxY) {
					clearInterval(this._id)
					alert(`游戏结束,得分为 ${ this._score } ,请再接再厉!!`)
					return true
				}
			}
		}

		// 点击开始按钮, 让游戏开始
		btn.addEventListener('click',function(){
			var game = new Game(box)
			game.start()
		})
	</script>
</body>
</html>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值