JQuery代码实现 Canvas贪吃蛇

JQuery代码实现 Canvas贪吃蛇

HTML长代码预警

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script>
	<style>
		canvas{
			box-shadow: 0 0 10px #000;
			margin: 0 auto;
			display: block;
		}
	</style>
</head>
<body>
	<canvas width="800" height="600" id="canvas"></canvas>
</body>
<script>
//jq语法
	$(function(){
		/**
		 * [Draw description] canvas绘图的构造函数
		 * @param {[type]} canvas [description]
		 */
		//Draw函数
		



		/**
		 * [Rect description]
		 * @param number x      矩形起始点坐标X
		 * @param number y      矩形起始点坐标Y
		 * @param number width  矩形的宽度
		 * @param number height 矩形的高度
		 * @param string color  矩形的填充颜色
		 * @param object xt  画笔  上下文
		 */
		//定义变量
		function Rect(x,y,width,height,color){
			//变量X
			this.x = x;
			//变量Y
			this.y = y;
			//变量宽
			this.width = width;
			//变量高
			this.height = height;
			//变量颜色
			this.color = color;
		}
		/**
		 * [draw description] 画矩形
		 * @return
		 */
		//draw函数  用来使用变量
		Rect.prototype.draw = function(){
			//清除画笔
			Draw.prototype.xt.beginPath();
			//使用颜色变量
			Draw.prototype.xt.fillStyle = this.color;
			//蛇头变量
			Draw.prototype.xt.fillRect(this.x,this.y,this.width,this.height);
			//边框线变量
			Draw.prototype.xt.strokeRect(this.x,this.y,this.width,this.height);
		}
		//创建蛇的对象
		function Snake(obj){
			//蛇头
			this.head = new Rect(obj.canvas.width/2-20,obj.canvas.height/2,20,20,'red');
			//蛇身
			this.body = [];//表示多个身体
			//每个蛇身的X轴
			var x = this.head.x - 20;
			//每个蛇身的Y轴
			var y = this.head.y;

			//循环创建身体实例
			for(var i=0;i<3;i++){
				//蛇身的属性
				var rect = new Rect(x,y,20,20,'gray');
				//加入蛇身
				this.body.push(rect);
				//为下一个蛇身设定好X轴
				x -=20;
			}
		}
		//添加蛇默认的移动方向,向右  共有的属性,任何的地方能够修改访问并且和实例共享
		Snake.prototype.direction = 1;


		//定义一个是否吃到食物的标记
		Snake.prototype.isEatFood = false;
		//画蛇的方法
		Snake.prototype.draw = function(){
			//画蛇头
			this.head.draw();
			//画蛇身
			for(var i=0;i<this.body.length;i++){
				this.body[i].draw();
			}
		}
		//让蛇动起来
		Snake.prototype.move = function(){
			//给身体加一个头
			for(item in this.body){
			 	if(isRectHit(this.head,this.body[item])){
					return false;
				}
			}
			// for(var i=0;i<this.body.length;i++){
			//  	if(isRectHit(this.head,this.body[i])){
			// 		return false;
			// 	}
			// }
			//检测碰撞到墙壁
			//
			if(this.head.x<20 || this.head.y<20 ||
				this.head.x>$('#canvas')[0].width-20-20 || this.head.y>$('#canvas')[0].height-20-20){
				return false;
			}


			var rect = new Rect(this.head.x,this.head.y,20,20,'gray');
			//添加到身体开始的地方
			this.body.splice(0,0,rect);
			//去掉一个尾巴
			//下节课的内容
			if(Snake.prototype.isEatFood){
				Snake.prototype.isEatFood = false;
				//重新随机产生食物
				//food.draw();
				
			}else{
				this.body.pop();

			}

			switch(this.direction){
				case 0:
					this.head.y -=20;
					break;
				case 1:
					this.head.x +=20;
					break;
				case 2:
					this.head.y +=20;
					break;
				case 3:
					this.head.x -=20;
					break;
			}
			return true;
		}
		//添加键盘监听
		$(window).keydown(function(e){
			switch(e.keyCode){
				case 37:
					//向右不能改为向左
					if(Snake.prototype.direction == 1){
						return;
					}
					Snake.prototype.direction = 3;
					break;
				case 38:
					//向下不能改为向上
					if(Snake.prototype.direction == 2){
						return;
					}
					Snake.prototype.direction = 0;
					break;
				case 39:
					if(Snake.prototype.direction == 3){
						return;
					}
					Snake.prototype.direction = 1;
					break;
				case 40:
					if(Snake.prototype.direction == 0){
						return;
					}
					Snake.prototype.direction = 2;
					break;
			}
		});




		function Draw(canvas){
			this.canvas = canvas;
			/**
			 * [check description] 检测浏览器是否支持canvas
			 * @return bool false表示不支持  true表示支持
			 */
			//网页打开时运行函数
			this.check = function(){
				//检测浏览器是否支持canvas
				//判断是否有getContext这个属性
				if(!this.canvas.getContext){
					//返回否
					return false;
				//否则
				}else{
					//返回是
					return true;
				}
			}
			/**
			 * [main description] canvas 绘图的主函数
			 * @return {[type]} [description]
			 */
			this.main = function(){
				//检测兼容
				if(!this.check()){
					//打印
					console.log('浏览器不支持canvas');
					//返回否
					return false;
				}
				//canvas不解释
				Draw.prototype.xt = this.canvas.getContext('2d');
				//....
				//设定蛇的对象函数
				//绘制蛇的基本图形
				var snake = new Snake(this);
				//调用蛇的对象函数
				snake.draw();
				//随机产生一个食物
				var food = randFood(snake);
				food.draw();
				//做一个动画的定时器
				Draw.prototype.timer = setInterval(function(){
					//清除旧的图像
					Draw.prototype.xt.clearRect(0,0,this.canvas.width,this.canvas.height);
					//改变蛇的位置
					if(!snake.move()){
						clearInterval(Draw.prototype.timer);
						alert('游戏结束');
					}
					//重新绘制图形
					snake.draw();

					food.draw();
					if(isRectHit(food,snake.head)){
						Snake.prototype.isEatFood = true;
						food = randFood(snake);
					}

				},80);
			}
		}

		//随机产生食物
		function randFood(snake){
			//是否在蛇身上
			isInSnake = true;
			

			while(isInSnake){
				isInSnake = false;
				//产生两个位置 x,y
				var x = getRandPosition(0,($('#canvas')[0].width-20)/20)*20;
				var y = getRandPosition(0,($('#canvas')[0].height-20)/20)*20;
				//创建食物矩形
				var food = new Rect(x,y,20,20,'green');
				//判断这个位置是否在蛇上
				//是否是蛇头
				if(isRectHit(food,snake.head)){
					isInSnake = true;
					continue;
				}
				//是否是蛇身
				for(var i=0;i<snake.body.length;i++){
					if(isRectHit(food,snake.body[i])){
						isInSnake = true;
						break;
					};
				}
			}
			return food;
		}
		//产生随机数的函数
		function getRandPosition(min,max){
			return Math.round(Math.random()*(max-min)+min);
		}
		//判断矩形是否重合
		function isRectHit(rect1,rect2){
			var R1_min_x = rect1.x;
			var R2_min_x = rect2.x;

			var R1_min_y = rect1.y;
			var R2_min_y = rect2.y;


			var R1_max_x = rect1.x+20;
			var R2_max_x = rect2.x+20;

			var R1_max_y = rect1.y+20;
			var R2_max_y = rect2.y+20;


			var min_x = Math.max(R1_min_x,R2_min_x);
			var max_x = Math.min(R1_max_x,R2_max_x);

			var min_y = Math.max(R1_min_y,R2_min_y);
			var max_y = Math.min(R1_max_y,R2_max_y);

			if(min_x<max_x && min_y<max_y){
				return true;
				//这里就是碰到了
			}else{
				return false;
			}
		}
		//this.prototype.isEatFood = true;

		//创建一个绘图的实例对象
		var draw = new Draw($('#canvas')[0]);
		//调用实例对象
		draw.main();



	});
</script>
</html>

粗糙的动图

贪吃蛇动图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 JavaScript 代码实现贪吃蛇的示例: ```javascript // 定义画布大小和格子大小 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var gridSize = 10; var canvasWidth = 400, canvasHeight = 400; // 定义蛇的初始状态 var snake = [{x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}]; var direction = "right"; // 定义食物的初始位置 var food = {x: 15, y: 15}; // 绘制函数 function draw() { // 清空画布 ctx.clearRect(0, 0, canvasWidth, canvasHeight); // 绘制蛇 ctx.fillStyle = "green"; for (var i = 0; i < snake.length; i++) { ctx.fillRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize, gridSize); } // 绘制食物 ctx.fillStyle = "red"; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); } // 移动函数 function move() { // 更新蛇头位置 var head = {x: snake[0].x, y: snake[0].y}; if (direction == "right") head.x++; else if (direction == "left") head.x--; else if (direction == "up") head.y--; else if (direction == "down") head.y++; snake.unshift(head); // 判断是否吃到食物 if (head.x == food.x && head.y == food.y) { food.x = Math.floor(Math.random() * (canvasWidth / gridSize)); food.y = Math.floor(Math.random() * (canvasHeight / gridSize)); } else { snake.pop(); } // 判断是否撞墙或自撞 if (head.x < 0 || head.x * gridSize >= canvasWidth || head.y < 0 || head.y * gridSize >= canvasHeight) { clearInterval(intervalId); alert("Game over!"); } for (var i = 1; i < snake.length; i++) { if (head.x == snake[i].x && head.y == snake[i].y) { clearInterval(intervalId); alert("Game over!"); } } } // 键盘监听函数 document.addEventListener("keydown", function(event) { if (event.keyCode == 37 && direction != "right") direction = "left"; else if (event.keyCode == 38 && direction != "down") direction = "up"; else if (event.keyCode == 39 && direction != "left") direction = "right"; else if (event.keyCode == 40 && direction != "up") direction = "down"; }); // 游戏主循环函数 var intervalId = setInterval(function() { move(); draw(); }, 100); ``` 以上是一个简单的示例,实现贪吃蛇的基本功能,但还有很多优化和扩展的空间,比如添加分数、难度等级等。希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值