原生js实现canvas打砖块游戏代码

代码语言:html

所属分类:游戏

代码描述:原生js实现canvas打砖块游戏代码

代码标签: 打砖块 游戏 canvas

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">

	</head>

	<body>
		<div id="stage" style="margin: 0 auto; width: 850px; height: 661px; text-align: center; vertical-align: middle" >
			<canvas id="canvas" style="border:0px solid red;" width="850" height="661">
				不支持画板对象
			</canvas>
		</div>
		<script>
            //画笔画布的导入
			var canvas = document.getElementById('canvas');
			var ctx = canvas.getContext('2d');
			//游戏图片的导入
			var bg = new Image();
			bg.src = "//repo.bfw.wiki/bfwrepo/game/1/bg.jpg";
			//板图片
			var board = new Image();
			board.src = "//repo.bfw.wiki/bfwrepo/game/1/board.png";
			//游戏结束
			var gameOver = new Image();
			gameOver.src = "//repo.bfw.wiki/bfwrepo/game/1/GAME_OVER.png";
			//成功
			var success = new Image();
			success.src = "//repo.bfw.wiki/bfwrepo/game/1/success.png";
			//球图片
			var ball = new Image();
			ball.src = "//repo.bfw.wiki/bfwrepo/game/1/ball.png";
			//砖块图片数组的创建
			var zk = [];
			zk[0] = new Image();
			zk[0].src = "//repo.bfw.wiki/bfwrepo/game/1/0.png";
			zk[1] = new Image();
			zk[1].src = "//repo.bfw.wiki/bfwrepo/game/1/1.png";
			zk[2] = new Image();
			zk[2].src = "//repo.bfw.wiki/bfwrepo/game/1/2.png";
			zk[3] = new Image();
			zk[3].src = "//repo.bfw.wiki/bfwrepo/game/1/3.png";
			zk[4] = new Image();
			zk[4].src = "//repo.bfw.wiki/bfwrepo/game/1/4.png";
			//坐标点
			var x = 552 / 2 - 195 / 2;
			var y = 622;
			//随机数(球的弹射方向-不确定性)
			var n = Math.random() * 2 + 2;
			var m = Math.random() * 2 + 2;
			//初始状态设置
			var score = 0;
			var life = 3;
			// p层数
			var p = 0;

			//球对象(对象固有属性的书写 对象直接量)
			var b = {
				x : 552 / 2 - 46 / 2,
				y : 622 - 46,
				width : 46,
				height : 46,
				//调用paint方法绘制球
				paint : function() {
					ctx.drawImage(ball, this.x, this.y);
				}
			}
		//确保游戏每时每刻都在发生变化
			var zks = [];//砖块数
			var s = setInterval(function() {
				ctx.drawImage(bg, 0, 0);
				ctx.drawImage(board, x, y);
				paint();
				move();
				check();
			}, 1);

			//砖块的构造方法(属性及其应用方法的定义)
			function Zk(x, y, width, height, img) {
				this.x = x;
				this.y = y;
				this.height = height;
				this.width = width;
				this.img = img;
				this.paint = function() {
					ctx.drawImage(this.img, this.x, this.y);
				}
			}
			//for循环:初始值为0,如果i<10,i就会每次都加1
			//直到i<10不成立.p代表砖块层数
			for (var i = 0; i < 10; i++) {
				if (i <= 4) {
					zks[zks.length] = 
					new Zk(i * 98 + 30, 30, 98, 34, zk[i]);
				} else {
					zks[zks.length] = 
					new Zk(p * 98 + 30, 30 + 40, 46, 46, zk[p]);
					p++;
				}
			}
			//绘画.........完整代码请登录后点击上方下载按钮下载查看

网友评论0