用JS写一个《俄罗斯方块》小游戏

js 实现俄罗斯方块 实现思路 MVC思路。三个端分工合作。可以仔细看。整个俄罗斯方块为一个二维数组。C控制M, M控制二维数组,V只要把二维数组渲染出来就行 。 视图层 html部分 <canvas id="canvas"></canvas> js部分 // 画背景 function drawBG(){ CTX.lineWidth = 1; CTX.fil... 阅读详情

前言

最近网上上映一部名叫《俄罗斯方块》电影,想起自己学习JS时,编写《俄罗斯方块》小游戏程序作为练习,现在分享一下,看能不能蹭一下热度。: )

效果图

在这里插入图片描述

按键说明

  • ↑:旋转方块
  • ↓:加快方块下坠
  • ←:左移方块
  • →:右移方块
  • D:直接让方块坠底

放马过来

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
		<title>Tetris</title>
		<style type="text/css">
			.basic{
				height:20px;
				width:20px;
				background-color:#DBDBDB;
				float:left;
				margin:1px;
			}
			.row{
				height:20px;
				clear:both;
			}
		</style>
	</head>
	
	<body>
		<div id="main">
			<div id="pool" style="float:left;"></div>
			<div id="nextOne" style="float:left;"></div>
			<div id="sample" class="basic" style='opacity: 0;clear:right;'></div>
			<div style="float:left;width:60px;">score: 
				<span id='score' style="font-size:200%;font-weight:bold;"></span>
				level: 
				<span id='level' style="font-size:200%;font-weight:bold;"></span>
			</div>
			<div style="float:left;width:60px;"> 
				<button id='go'>Start/Restart</button>
			</div>
		<div>
		
		<script type="text/javascript" >
		
			var tetris = {
				alive:true,
				init:function(){
					this.view.loadBackground();
					this.model.initAllFourBlockTemplate();
					
					this.reset();
					
					var self = this;
					
					document.addEventListener('keydown', function(event){
						self.controller.listenKeyDown4UpDownLeftRight(event, self);
					});
					
					document.getElementById('go').addEventListener("click", function(){ 
						if(confirm("Are You Sure?")){
							self.reset();
							
							self.controller.updateTimer(self.model.level2ScoreAndInterval[self.model.level - 1][1], self);
						}
					});
					
					this.controller.startTimer(this);
					
					this.view.refreshAll(this.model);
					
				},
				reset:function(){
					this.model.initAccumulatedBlocks(tetris.view);
					this.model.fallingBlock = this.model.generateFourBlock(this.view);
					this.model.prepareBlock = this.model.generateFourBlock(this.view);
					this.model.centerFourBlock(this.view, this.model.fallingBlock);
					
					this.alive = true;
					
					this.model.score = 0;
					this.model.level = 1;
					this.model.nextScoreLine = this.model.level2ScoreAndInterval[this.model.level][0];
					
					document.removeEventListener('keydown',this.controller.alertGameOver);
				},
				view:{
					rowNum:25,
					colNum:17,
					zoneTwoRowNum:4,
					zoneTwoColNum:4,
					loadBackground:function(){
						var pool = document.getElementById("pool");
						var sample = document.getElementById("sample");
						var nextOne = document.getElementById("nextOne");
						
						var margin = 2;
						var dotWidth = parseFloat(sample.offsetWidth) + margin;//基本方块宽度 + margin
						
						function calcWidth(cNum){
							return (cNum * (dotWidth + margin));
						}
						
						var poolWidth = calcWidth(this.colNum) + 'px';
						var	nextOneWidth = calcWidth(4) + 'px';
						pool.style.width = poolWidth;
						nextOne.style.width = nextOneWidth;
						
						function createBlocks(rNum, idPrefix, cNum, rowWidth, context){
							for(var i = 0; i < rNum; i++){//
								//创建行
								var rDiv = document.createElement("div");
								rDiv.setAttribute('id',idPrefix + 'r' + i);//
								rDiv.setAttribute('class','row');
								
								for(var j = 0; j < cNum; j++){//
									var cDiv = document.createElement("div");
									cDiv.setAttribute('id', idPrefix + 'c' + j + '_r' + i);//
									cDiv.setAttribute('class','basic');
									rDiv.appendChild(cDiv);
								}
								rDiv.setAttribute('width', rowWidth);//
								context.appendChild(rDiv);
							}
						}
						
						createBlocks(this.rowNum, '', this.colNum, poolWidth, pool);
						createBlocks(this.zoneTwoRowNum, 'n', this.zoneTwoColNum, nextOneWidth, nextOne);
						
						document.getElementById("main").style.width 
							= parseFloat(poolWidth) + parseFloat(nextOneWidth) + 'px';
						
					},
					colour:['#DBDBDB','#56A36C','#EFCEE8',
						'#81C2D6','#8192D6','#D9B3E6',
						'#DCF7A1','#83FCD8','#E8F2FF',
						'#91C6FF','#B8F788','#58D2E8',
						'#F2B6B6','#E8ED51','#FFE3FB',
						'#E8FF8C','#FFDEC9','#F5A433',
						'#E6109B','#96C4E6','#E560CD'],
					refreshScore:function(score){
						document.getElementById('score').innerHTML = score;
					},
					refreshLevel:function(level){
						document.getElementById('level').innerHTML = level;
					},
					refreshZoneOne:function(accumulatedBlocks, fallingBlock){
						//显示 积累块组
						for(var i = 0; i < accumulatedBlocks.length; i++){
							for(var j = 0; j < accumulatedBlocks[i].length; j++){
								document.getElementById('c' + j + '_r' + i).style.backgroundColor 
									= this.colour[accumulatedBlocks[i][j]];
							}
						}
						
						//显示下降块
						for(var i = 0; i < fallingBlock.coordinateGroup.length; i++){
							var x = fallingBlock.coordinateGroup[i][0];
							var y = fallingBlock.coordinateGroup[i][1];
							
							if(y >= 0){
								document.getElementById('c' + x + '_r' + y).style.backgroundColor 
									= this.colour[fallingBlock.colorIndex];
							}
						}
						
					},
					refreshZoneTwo:function(fourBlock){
						for(var i = 0; i < this.zoneTwoRowNum; i++){
							for(var j = 0; j < this.zoneTwoColNum; j++){
								document.getElementById('nc' + i + '_r' + j).style.backgroundColor = this.colour[0];
							}
						}
						
						for(var k = 0 ; k < fourBlock.coordinateGroup.length; k++){
							if(fourBlock.coordinateGroup[k][1] >= 0){
								document.getElementById('nc' + fourBlock.coordinateGroup[k][0] + '_r' + fourBlock.coordinateGroup[k][1]).style.backgroundColor = this.colour[fourBlock.colorIndex];
							}
						}
					},
					refreshAll:function(model){
						this.refreshLevel(model.level);
						this.refreshScore(model.score);
						this.refreshZoneOne(model.accumulatedBlocks, model.fallingBlock);
						this.refreshZoneTwo(model.prepareBlock);
					},
					clear:function(){//
						var pool = document.getElementById("pool");
						var nextOne = document.getElementById("nextOne");
						
						while (pool.hasChildNodes()) {
							pool.removeChild(pool.childNodes[0]);
						}			
						
						while(nextOne.hasChildNodes()) {
							nextOne.removeChild(nextOne.childNodes[0]);
						}
					}
				},
				model:{
					score:0,
					level:1,
					nextScoreLine:0,
					accumulatedBlocks:[],//容器内堆积的块 的属性[colorIndex...]
					initAccumulatedBlocks:function(view){
						var result = [];
						
						for(var i = 0; i< view.rowNum; i++){
							var tmp = [];//y
							
							for(var j = 0; j < view.colNum; j++){
								tmp.push(0);//x
							}
							
							result.push(tmp);
						}
						
						this.accumulatedBlocks = result;
					},
					basicFourBlockTemplates:[
						{
							coordinateGroup:[[1,2],[2,2],[1,3],[2,3]],
							type:'T1',
							state:'A',
						},
						{
							coordinateGroup:[[0,3],[1,3],[2,3],[3,3]],
							type:'T2',
							state:'A'
						},//
						{
							coordinateGroup:[[1,2],[2,1],[2,2],[2,3]],
							type:'T3',
							state:'A'
						},
						{
							coordinateGroup:[[0,3],[1,2],[1,3],[2,2]],
							type:'T4',
							state:'A'
						},
						{
							coordinateGroup:[[0,2],[1,2],[1,3],[2,3]],
							type:'T5',
							state:'A'
						},
						{
							coordinateGroup:[[1,1],[1,2],[1,3],[2,1]],
							type:'T6',
							state:'A'
						},
						{
							coordinateGroup:[[1,1],[2,1],[2,2],[2,3]],
							type:'T7',
							state:'A'
						}
					],
					fourBlockTemplates:[],
					initAllFourBlockTemplate:function(){
						var frequencyArray = [0, 2, 4, 2, 2, 4, 4];
						
						for(var i = 0; i < frequencyArray.length; i++){
							//Ti
							this.fourBlockTemplates.push(this.basicFourBlockTemplates[i]);
							
							for(var f = 0; f < frequencyArray[i] - 1; f++){
								var tmp = this.fourBlockTemplates[this.fourBlockTemplates.length - 1];
								var tmp2 = this.createNewFourBlockTemplateByRotating90DegreesClockwise(tmp);
								
								this.fourBlockTemplates.push(tmp2);
							}
						}

					},
					createNewFourBlockTemplate:function(coordinateGroup_, state_, type_){
						return {coordinateGroup:coordinateGroup_, type:type_, state:state_};
					},
					createNewFourBlockTemplateByRotating90DegreesClockwise:function(fourBlock){//用于初始化四连块模板
						var rotatedOne = this.rotate90DegreesClockwise(fourBlock.coordinateGroup, fourBlock.type, fourBlock.state);
						
						var result = rotatedOne.coordinateGroup;
						switch(fourBlock.type){
							case 'T1':break;
							case 'T2':
								if(fourBlock.state == 'A'){
									return this.createNewFourBlockTemplate(result, 'B', fourBlock.type);
								}					
								break;
							case 'T3':
								if(fourBlock.state == 'A'){
									return this.createNewFourBlockTemplate(result, 'B', fourBlock.type);
								}
								if(fourBlock.state == 'B'){
									return this.createNewFourBlockTemplate(result, 'C', fourBlock.type);
								}
								if(fourBlock.state == 'C'){
									return this.createNewFourBlockTemplate(result, 'D', fourBlock.type);
								}
								break;
							case 'T4':
								if(fourBlock.state == 'A'){
									return this.createNewFourBlockTemplate(result, 'B', fourBlock.type);
								}
								break;
							case 'T5':
								if(fourBlock.state == 'A'){
									return this.createNewFourBlockTemplate(result, 'B', fourBlock.type);
								}
								break;
							case 'T6':
								if(fourBlock.state == 'A'){
									return this.createNewFourBlockTemplate(result, 'B', fourBlock.type);
								}
								if(fourBlock.state == 'B'){
									return this.createNewFourBlockTemplate(result, 'C', fourBlock.type);
								}
								if(fourBlock.state == 'C'){
									return this.createNewFourBlockTemplate(result, 'D', fourBlock.type);
								}
								break;
							case 'T7':
								if(fourBlock.state == 'A'){
									return this.createNewFourBlockTemplate(result, 'B', fourBlock.type);
								}
								
								if(fourBlock.state == 'B'){
									return this.createNewFourBlockTemplate(result, 'C', fourBlock.type);
								}
								
								if(fourBlock.state == 'C'){
									return this.createNewFourBlockTemplate(result, 'D', fourBlock.type);
								}
								break;
							default:break;
						}
					},
					rotate90DegreesClockwise:function(coordinateGroup, type, state){//按上键 旋转 四连块
						var result = type == 'T1'?coordinateGroup:this.copyTwoDimensionalIntegerArray(coordinateGroup);
						switch(type){
							case 'T1':break;
							case 'T2':
								if(state == 'A'){
									this.moveLeftestBlock(result, 3, -3);
									this.moveLeftestBlock(result, 2, -2);
									this.moveLeftestBlock(result, 1, -1);
									state = 'B';
									
								}else if(state == 'B'){
									this.moveTopestBlock(result, -3, 3);
									this.moveTopestBlock(result, -2, 2);
									this.moveTopestBlock(result, -1, 1);
									state = 'A';
									
								}
								break;
							case 'T3':
								if(state == 'A'){
									this.moveLeftestBlock(result, 0, 1);
									this.moveTopestBlock(result, 1, 2);
									state = 'B';
									
								}else if(state == 'B'){
									this.moveLeftestBlock(result, 1, -2);
									this.moveRightestBlock(result, 0, -1);
									state = 'C';
									
								}else if(state == 'C'){
									this.moveTopestBlock(result, -1, 1);
									state = 'D';
									
								}else if(state == 'D'){
									this.moveRightestBlock(result, -1, -1);
									state = 'A';
									
								}
								break;
							case 'T4':
								if(state == 'A'){
									this.moveLeftestBlock(result, 1, -2);
									this.moveBottomestBlock(result, 1, 0);
									state = 'B';
									
								}else if(state == 'B'){
									this.moveBottomestBlock(result, -1, 0);
									this.moveTopestBlock(result, -1, 2);
									state = 'A';
									
								}
								
								break;
							case 'T5':
								if(state == 'A'){
									this.moveRightestBlock(result, 0, -2);
									this.moveLeftestBlock(result, 2, 0);
									state = 'B';
									
								}else if(state == 'B'){
									this.moveTopestBlock(result, -2, 1);
									this.moveRightestBlock(result, 0, 1);
									state = 'A';
									
								}
								
								break;
							case 'T6':
								if(state == 'A'){
									this.moveBottomestBlock(result, -1, -1);
									this.moveRightestBlock(result, 0, 2);
									this.moveTopestBlock(result, 1, 1);
									state = 'B';
									
								}else if(state == 'B'){
									this.moveLeftestBlock(result, 2, -1);
									this.moveLeftestBlock(result, 0, 1);
									state = 'C';
									
								}else if(state == 'C'){
									this.moveTopestBlock(result, 1, 2);
									this.moveTopestBlock(result, -1, 0);
									state = 'D';
									
								}else if(state == 'D'){
									this.moveRightestBlock(result, -2, -2);
									this.moveRightestBlock(result, 0, -2);
									state = 'A';
									
								}
								
								break;
							case 'T7':
								if(state == 'A'){
									this.moveLeftestBlock(result, 0, 2);
									this.moveTopestBlock(result, -2, 2);
									state = 'B';
									
								}else if(state == 'B'){
									this.moveTopestBlock(result, -1, 0);
									this.moveLeftestBlock(result, 1, -2);
									state = 'C';
									
								}else if(state == 'C'){
									this.moveRightestBlock(result, 0, -1);
									this.moveTopestBlock(result, 2, 1);
									state = 'D';
									
								}else if(state == 'D'){
									this.moveBottomestBlock(result, 1, 0);
									this.moveLeftestBlock(result, 0, -1);
									this.moveRightestBlock(result, -1, -1);
									state = 'A';
									
								}
								break;
							default:break;
						}
						
						return {"coordinateGroup":result,"state":state};
					},
					moveTopestBlock:function(coordinateGroup, xOffset, yOffset){
						var top = this.getTopestBlock(coordinateGroup);
						this.replace(coordinateGroup, top, [top[0] + xOffset, top[1] + yOffset]);
					},
					moveBottomestBlock:function(coordinateGroup, xOffset, yOffset){
						var bottom = this.getBottomestBlock(coordinateGroup);
						this.replace(coordinateGroup, bottom, [bottom[0] + xOffset, bottom[1] + yOffset]);
					},
					moveLeftestBlock:function(coordinateGroup, xOffset, yOffset){
						var left = this.getLeftestBlock(coordinateGroup);
						this.replace(coordinateGroup, left, [left[0] + xOffset, left[1] + yOffset]);
					},
					moveRightestBlock:function(coordinateGroup, xOffset, yOffset){
						var right = this.getRightestBlock(coordinateGroup);
						this.replace(coordinateGroup, right, [right[0] + xOffset, right[1] + yOffset]);
					},
					getLeftestBlock:function(coordinateGroup){
						//x值最小
						var tmp = coordinateGroup[0];
						for(var i = 0 ; i < coordinateGroup.length; i++){
							if(coordinateGroup[i][0] < tmp[0]){
								tmp = coordinateGroup[i];
							}
						}
						//console.log("leftest: " + tmp);
						return tmp;//返回最后得到
					},
					getRightestBlock:function(coordinateGroup){
						//x值最大
						var tmp = coordinateGroup[0];
						for(var i = 0 ; i < coordinateGroup.length; i++){
							if(coordinateGroup[i][0] > tmp[0]){
								tmp = coordinateGroup[i];
							}
						}
						//console.log("rightest: " + tmp);
						return tmp;//返回最先找到
					},
					getTopestBlock:function(coordinateGroup){
						//y值最小
						var tmp = coordinateGroup[0];
						for(var i = 0 ; i < coordinateGroup.length; i++){
							if(coordinateGroup[i][1] < tmp[1]){
								tmp = coordinateGroup[i];
							}
						}
						//console.log("topest: " + tmp);
						return tmp;//返回最后得到
					},
					getBottomestBlock:function(coordinateGroup){
						var tmp = coordinateGroup[0];
						for(var i = 0 ; i < coordinateGroup.length; i++){
							if(coordinateGroup[i][1] > tmp[1]){
								tmp = coordinateGroup[i];
							}
						}
						//console.log("bottomest: " + tmp);
						return tmp;//返回最先找到
					},
					replace:function(coordinateGroup, A, B){//coordinateGroup replace A with B
						for(var i = 0 ; i < coordinateGroup.length; i++){
							if(coordinateGroup[i][0] == A[0] 
								&& coordinateGroup[i][1] == A[1]){
								coordinateGroup[i] = B;
								break;
							}
						}
					},
					copyTwoDimensionalIntegerArray:function(coordinateGroup){
						var result = [];
						for(var i = 0 ; i < coordinateGroup.length; i++){
							var tmp = [];
							for(var j = 0 ; j < coordinateGroup[i].length; j++){
								tmp[tmp.length] = coordinateGroup[i][j];
							}
							result[result.length] = tmp;
						}
						return result;
					},
					generateFourBlock:function(view, templateIndex){
					
						if(!templateIndex){
							templateIndex = this.makeRandomInteger(this.fourBlockTemplates.length)
						}
						var template = this.fourBlockTemplates[templateIndex];
						var index = this.makeRandomInteger(view.colour.length);
						
						while(index == 0){
							index = this.makeRandomInteger(view.colour.length);
						}
						
						return {coordinateGroup:this.copyTwoDimensionalIntegerArray(template.coordinateGroup),
								type : template.type,
								state : template.state,
								colorIndex : index};
					},
					makeRandomInteger:function(scope){
						return Math.floor(Math.random() * scope);
					},
					fallingBlock:{},//最开始的时候y为负数
					prepareBlock:{},//预备下降块
					checkIfAccumulatedBlocksContain:function(coordinate, view){
						if(coordinate[0] < 0 || coordinate[1] < 0) 
							return false;
						if(coordinate[0] >= view.colNum || coordinate[1] >= view.rowNum) 
							return false;
						return this.accumulatedBlocks[coordinate[1]][coordinate[0]] != 0;
					},
					checkIfOverstepping:function(coordinate, view){
						if(coordinate[0] < 0) 
							return true;
						if(coordinate[0] >= view.colNum || coordinate[1] >= view.rowNum) 
							return true;
						return false;
					},
					canFourBlockMove:function(fourBlock, direction, tetris_){
						var copyOne = fourBlock.coordinateGroup;
						
						var DIRECTION = tetris_.controller.DIRECTION;
						var view = tetris_.view;
						
						//若下一步碰壁,
						if(direction == DIRECTION.LEFT){
							for(var i = 0;i < copyOne.length;i++){
								if(copyOne[i][0] - 1 < 0){
									return false;
								}
								
								//检查 与 积累块 是否有碰撞
								if(this.checkIfAccumulatedBlocksContain([copyOne[i][0] - 1,copyOne[i][1]],view)){
									return false;
								}
							}
						}
							
						if(direction == DIRECTION.RIGHT){
							for(var i = 0;i < copyOne.length;i++){
								if(copyOne[i][0] + 1 >= view.colNum){
									return false;
								}
								if(this.checkIfAccumulatedBlocksContain([copyOne[i][0] + 1,copyOne[i][1]],view)){
									return false;
								}
							}
						}
						
						if(direction == DIRECTION.DOWN){
							for(var i = 0;i < copyOne.length;i++){
								if(copyOne[i][1] + 1 > view.rowNum){
									return false;
								}
							}
						}
						
						//旋转
						if(direction == DIRECTION.UP){
							copyOne = this.rotate90DegreesClockwise(
								fourBlock.coordinateGroup,
								fourBlock.type,
								fourBlock.state);
							
							//尝试矫正
							//this.correctFourBlockAfterRotate(copyOne, type, tetris_);
							this.correctFourBlockAfterRotate2(fourBlock.type, fourBlock.coordinateGroup, copyOne.coordinateGroup, view);
							
							//console.log(copyOne.coordinateGroup);
							
							//尝试矫正后还是碰 左右壁 或  积累块组 ,return false;
							for(var i = 0; i < copyOne.coordinateGroup.length; i++){
								
								var condition = this.checkIfOverstepping(copyOne.coordinateGroup[i], view)
									|| this.checkIfAccumulatedBlocksContain(copyOne.coordinateGroup[i], view);
								
								if(condition){
									return false;
								}
							}
						}
						return true;
					},
					//旋转尝试矫正
					correctFourBlockAfterRotate2:function(type, coordinateGroupBefore, coordinateGroupAfter, view){
						var touchedBlocks = [];
						for(var i = 0; i < coordinateGroupAfter.length; i++){
						
							if(this.checkIfAccumulatedBlocksContain(coordinateGroupAfter[i], view)
									|| this.checkIfOverstepping(coordinateGroupAfter[i], view)){
								touchedBlocks[touchedBlocks.length] = coordinateGroupAfter[i];
							}
						}
						
						if(touchedBlocks.length != 0){
							var sameBlocks = this.findSameBlocks(coordinateGroupBefore, coordinateGroupAfter);
							var direction = touchedBlocks[0][0] - sameBlocks[0][0];
							
							//碰撞块在左边,还是在右边,对应矫正+1,-1
							direction = (direction < 0 ? 1 : (direction > 0 ? -1 : 0));
							
							this.tryToMove(type, coordinateGroupAfter, direction, view);
						}
						
					},
					tryToMove:function(type, coordinateGroupAfter, direction, view){
						var j = 0;
						var limit = (type == 'T2'? 3 : 1);//T2 直线四连块 
						//最多3次
						while(j < limit && direction != 0){
							for(var i = 0; i < coordinateGroupAfter.length; i++){
								coordinateGroupAfter[i][0] += (direction);//direction 值为 -1 or 1
							}
							
							var stillTouched = false;
							
							for(var i = 0; i < coordinateGroupAfter.length; i++){
							
								if(this.checkIfAccumulatedBlocksContain(coordinateGroupAfter[i], view)
									|| this.checkIfOverstepping(coordinateGroupAfter[i], view)){
									stillTouched = true;
									break;
								}
							}
							
							if(!stillTouched){
								break;
							}
							
							j++;
						}
					
					},
					findSameBlocks:function(coordinateGroupBefore, coordinateGroupAfter){
						var result = [];
						
						 for(var i = 0; i < coordinateGroupAfter.length; i++){
							var existed = false;
						
							for(var j = 0;j < coordinateGroupBefore.length; j++){						
								if(coordinateGroupAfter[i][0] == coordinateGroupBefore[j][0]
									&& coordinateGroupAfter[i][1] == coordinateGroupBefore[j][1]){
									existed = true;
									break;
								}
							}
							
							if(existed){
								result[result.length] = 
									[coordinateGroupAfter[i][0], coordinateGroupAfter[i][1]];
							}
						}
						
						return result;
					},
					moveFourBlockOneStep:function(fourBlock, direction, tetris_){
						//考虑是不是将该函数移到controller
						var DIRECTION = tetris_.controller.DIRECTION;

						if(direction == DIRECTION.LEFT){
							for(var i = 0;i < fourBlock.coordinateGroup.length; i++){
								fourBlock.coordinateGroup[i][0]--;
							}
						}
						
						if(direction == DIRECTION.RIGHT){
							for(var i = 0;i < fourBlock.coordinateGroup.length; i++){
								fourBlock.coordinateGroup[i][0]++;
							}
						}

						if(direction == DIRECTION.DOWN){
							for(var i = 0;i < fourBlock.coordinateGroup.length; i++){
								fourBlock.coordinateGroup[i][1]++;
							}
						}
					},
					checkFallingBlockTouchBaseLineOrAccumulatedBlocks:function(view){
						//检测 降落位下一位是否 碰到底线
						for(var i = 0; i < this.fallingBlock.coordinateGroup.length; i++){
							
							var x = this.fallingBlock.coordinateGroup[i][0];
							var y = this.fallingBlock.coordinateGroup[i][1]
							
							if(y + 1 == view.rowNum){
								return true;
							}
							
							if(this.checkIfAccumulatedBlocksContain([x, y+1], view)){
								return true;
							}
						}	

						return false;
					},
					//前提条件checkTouchBaseLineOrAccumulatedBlocks
					addFallingBlockToAccumulatedBlocks:function(fallingBlock, tetris_){
						
						//为 满行 作准备
						var rows = [];
						
						for(var i = 0; i < fallingBlock.coordinateGroup.length; i++){
							
							var row  = fallingBlock.coordinateGroup[i][1];
							
							if(row < 0) continue;
							
							var existed = false;
							for(var r = 0; r < rows.length; r++){
								if(rows[r] == row){
									existed = true;
								}
							}
							
							if(!existed){
								rows.push(row);
							}
							
							var col = fallingBlock.coordinateGroup[i][0];
							
							this.accumulatedBlocks[row][col] = fallingBlock.colorIndex;
						}
						
						//计分
						//检测满行(只需检查下降块的对应y)
						//降序
						rows.sort(function(a,b){return a-b});
						
						var fullCount = 0;
						
						//行满格进行消除
						for(var i = 0;i < rows.length; i++){
							var r = rows[i];
							//console.log(r)
							var isFull = this.checkRowFull(this.accumulatedBlocks[r]);
							//console.log(isFull)
							if(isFull){
								for(var j = 0; j < this.accumulatedBlocks[r].length; j++){//中间的j换成i会造成死循环,害得我要暴力重启几次
									this.accumulatedBlocks[r][j] = 0;
								}
								
								while(r > 0){
									var isLastRowEmpty = this.checkRowEmpty(this.accumulatedBlocks[r - 1]);
									
									if(!isLastRowEmpty){
										//前一行交换
										var tmp = this.accumulatedBlocks[r];
										this.accumulatedBlocks[r] = this.accumulatedBlocks[r - 1];
										this.accumulatedBlocks[r - 1] = tmp;
									}else{
										break;//如果有一行已经是空就没必要换下去
									}	
									r--;
								}

								fullCount++;
							}
						}
						
						this.addScore(fullCount, tetris_);
						
					},
					addScore:function(fullCount, tetris_){
						var append = fullCount * tetris_.view.colNum * this.level * 10;
						
						//一点一点相加
						while(append > 0){
							this.score += (append >= 10 ? 10 : append);
							
							//检查升级
							if(this.score >= this.nextScoreLine){
								
								this.level++;
								
								if(!this.level2ScoreAndInterval[this.level]){
									this.nextScoreLine = Number.MAX_VALUE;
								}else{
									this.nextScoreLine = this.level2ScoreAndInterval[this.level][0];
									//升级后加快四连块速度
									tetris_.controller.updateTimer(this.level2ScoreAndInterval[this.level - 1][1], tetris_);
								}
							}
							append -= 10;
						}
						
					},
					checkRowFull:function(array){//行 满块后 消失
						var isFull = true;
						for(var i = 0;i < array.length;i++){
							if(array[i] == 0){
								isFull = false;
								break;
							}
						}
						return isFull;
					},
					checkRowEmpty:function(array){
						var isEmpty = true;
						for(var i = 0;i < array.length;i++){
							if(array[i] != 0){
								isEmpty = false;
								break;
							}
						}
						return isEmpty;
					},
					centerFourBlock:function(view, fallingBlock){
						//居中降落
						var offset = Math.floor(view.colNum / 2 - this.makeRandomInteger(2));
						
						for(var i = 0; i < fallingBlock.coordinateGroup.length; i++){
							fallingBlock.coordinateGroup[i][0] += offset;
							fallingBlock.coordinateGroup[i][1] -= (view.zoneTwoRowNum - 1);//垂直方向
						}
					},
					makeFallingBlocksFallDirectly:function(view){
						var map = {};
						
						for(var i = 0 ;i < this.fallingBlock.coordinateGroup.length;i++){
							var x = this.fallingBlock.coordinateGroup[i][0];
							var y = this.fallingBlock.coordinateGroup[i][1];
							
							var z = map[x];
							if(!z){
								map[x] = y;
							}else{
								map[x] = Math.max(y, z);
							}
						}
						
						var distance = [];
						
						for(var key in map){
							//console.log("==> "+ key + ", " + map[key]);
							
							var disc = 0;
							
							var x = key;
							var y = map[key];
							
							while(true){
								if(this.checkIfAccumulatedBlocksContain([x, y + disc + 1], view)
									|| y + disc + 1 == view.rowNum){
									break;
								}
								disc++;
							}
							
							distance[distance.length] = disc;
							//console.log("disc: " + disc);
						}
						
						distance.sort(function(a, b){return a-b});//最好指定函数参数,不填的话有时降序,有时升序
						var step = distance[0];
						//console.log("最小距离是:" + step);
						
						for(var i = 0 ;i < this.fallingBlock.coordinateGroup.length;i++){
							this.fallingBlock.coordinateGroup[i][1] += step;
						}

					},
					copyFourBlock:function(fourBlock){
						return {coordinateGroup:this.copyTwoDimensionalIntegerArray(fourBlock.coordinateGroup),
							type:fourBlock.type,
							state:fourBlock.state,
							colorIndex:fourBlock.colorIndex
						};
					},
					level2ScoreAndInterval:[//level is index + 1
						[0,1000],
						[1000,700],
						[5000,500],
						[10000,300],
						[20000,200]
					]
				},
				controller:{
					DIRECTION:{
						LEFT:37,
						RIGHT:39,
						UP:38,
						DOWN:40
					},
					listenKeyDown4UpDownLeftRight:function(event, tetris_){
						if(!tetris_.alive) return;
						
						var keycode = event.keyCode;
						
						var view = tetris_.view;
						var model = tetris_.model;
						
						if(keycode == 68){ //D键 直接下降
							
							model.makeFallingBlocksFallDirectly(view);
							
							//将fallingBlock变成为accumulateBlocks
							this.makeFallingBlocksJoinAccumlatedBlocksAndCheckDeath(tetris_);
							if(tetris_.alive){
								model.moveFourBlockOneStep(model.fallingBlock, this.DIRECTION.DOWN, tetris_);
							}
						}
						
						if(keycode >= 37 && keycode <= 40){
							//console.log(keycode);
							event.preventDefault();
							switch(keycode){
								case this.DIRECTION.LEFT://左
									if(!model.canFourBlockMove(model.fallingBlock, this.DIRECTION.LEFT, tetris_)) return;
									model.moveFourBlockOneStep(model.fallingBlock, this.DIRECTION.LEFT, tetris_);
								
									break;
								case this.DIRECTION.UP://上

									if(!model.canFourBlockMove(model.fallingBlock, this.DIRECTION.UP, tetris_)) 
										return;								
									
									var rotatedOne = model.rotate90DegreesClockwise(
										model.fallingBlock.coordinateGroup,
										model.fallingBlock.type,
										model.fallingBlock.state
									);
									
									model.correctFourBlockAfterRotate2(model.fallingBlock.type
										, model.fallingBlock.coordinateGroup
										, rotatedOne.coordinateGroup, view);
									//只对左右壁碰撞作出矫正,需要作出改正
									//console.log("===>"+rotatedOne.coordinateGroup);
									model.fallingBlock.coordinateGroup = rotatedOne.coordinateGroup;
									model.fallingBlock.state = rotatedOne.state;
									
									break;
								case this.DIRECTION.RIGHT://右
									if(!model.canFourBlockMove(model.fallingBlock, this.DIRECTION.RIGHT, tetris_)) return;
									model.moveFourBlockOneStep(model.fallingBlock, this.DIRECTION.RIGHT, tetris_);
								
									break;
								case this.DIRECTION.DOWN://下
									if(model.checkFallingBlockTouchBaseLineOrAccumulatedBlocks(view)){
										this.makeFallingBlocksJoinAccumlatedBlocksAndCheckDeath(tetris_);
									}
									if(tetris_.alive){
										model.moveFourBlockOneStep(model.fallingBlock, this.DIRECTION.DOWN, tetris_);
									}
									break;
								default:break;
							}
						}
						//刷新界面					
						view.refreshAll(model);
					},
					makeFallingBlocksJoinAccumlatedBlocksAndCheckDeath:function(tetris_){
						if(!tetris_.alive) return;
						
						var model = tetris_.model;
						var view  = tetris_.view;
						
						model.addFallingBlockToAccumulatedBlocks(model.fallingBlock, tetris_);
											
						model.fallingBlock = model.prepareBlock;
						
						model.prepareBlock = model.generateFourBlock(view);
						model.centerFourBlock(view, model.fallingBlock);
						
						if(model.checkFallingBlockTouchBaseLineOrAccumulatedBlocks(view)){
							tetris_.alive = false;
							this.alertGameOver();
							document.addEventListener('keydown', this.alertGameOver);
						}
					},
					alertGameOver:function(){
						alert('Game Over!');
					},
					startTimer:function(tetris_){
						
						//全局变量
						startBasicStep = window.setInterval(function(){
							//console.log(this)//返回window对象
							if(tetris_.alive){
								tetris_.controller.makeFallingBlocksFallOneStepAndRefreshView(tetris_);
							}
						}, tetris_.model.level2ScoreAndInterval[tetris_.model.level - 1][1]);
					},
					updateTimer:function(newInterval, tetris_){
						window.clearInterval(startBasicStep);
						
						console.log("Interval: " + newInterval);
						
						startBasicStep = window.setInterval(function(){
							//console.log(this)//返回window对象
							if(tetris_.alive){
								tetris_.controller.makeFallingBlocksFallOneStepAndRefreshView(tetris_);
							}
						}, newInterval);
					},
					makeFallingBlocksFallOneStepAndRefreshView:function(tetris_){
						var model = tetris_.model;
						var view = tetris_.view;
						
						if(model.checkFallingBlockTouchBaseLineOrAccumulatedBlocks(view)){
							
							this.makeFallingBlocksJoinAccumlatedBlocksAndCheckDeath(tetris_);
							
						}
						model.moveFourBlockOneStep(model.fallingBlock, this.DIRECTION.DOWN, tetris_);
						
						view.refreshAll(model);

					}
				}
			};
			
			//很难用单元测试做测试的测试
			/*
			var forTest = {
				cursor:0,
				lastDirection:0,
				showAllFourBlockTemplate:function(tetris_, colour, direction){//test
					if(direction){
						this.changeCursor(tetris, direction);
					}
					
					for(var i = 0; i < tetris_.view.zoneTwoRowNum; i++){
						for(var j = 0; j < tetris_.view.zoneTwoColNum; j++){
							document.getElementById('nc' + i + '_r' + j).style.backgroundColor = colour[0];//颜色默认灰色
						}
					}
					
					console.log("cursor: " + this.cursor);
					
					var fourBlock = tetris_.model.fourBlockTemplates[this.cursor];
					console.log(fourBlock);
					
					for(var k = 0 ; k < fourBlock.coordinateGroup.length; k++){
						document.getElementById('nc' + fourBlock.coordinateGroup[k][0] + '_r' + fourBlock.coordinateGroup[k][1]).style.backgroundColor = colour[1];
					}
				},
				changeCursor:function(tetris_, direction){
					if(direction == tetris_.controller.DIRECTION.DOWN){
						if(++this.cursor == tetris_.model.fourBlockTemplates.length){
							this.cursor = 0;
						}
						return;
					}
					
					if(direction == tetris_.controller.DIRECTION.UP){
						if(--this.cursor < 0){
							this.cursor = tetris_.model.fourBlockTemplates.length - 1;
						}					
					}
				},
				listenKeyDown4ShowAllFourBlockTemplate:function(tetris_){
					var self = this;
					
					self.showAllFourBlockTemplate(tetris_, tetris_.view.colour);
					
					document.addEventListener('keydown', function(event){
						event.preventDefault();
						var keycode = event.keyCode;
						if(keycode == tetris_.controller.DIRECTION.DOWN){//下
							self.showAllFourBlockTemplate(tetris_, tetris_.view.colour, keycode);
						}
						if(keycode == tetris_.controller.DIRECTION.UP){//上
							self.showAllFourBlockTemplate(tetris_, tetris_.view.colour, keycode);
						}
					});
				},
				listenKeyDown4GenerateFourBlock:function(tetris_){
					var self = this;
					document.addEventListener('keydown', function(event){
						var keycode = event.keyCode;
						if(keycode == tetris_.controller.DIRECTION.DOWN){//下
							event.preventDefault();
							tetris_.view.refreshZoneTwo(tetris_.model.generateFourBlock(tetris_.view));
						}
					});
				},
				listenKeyDown4MoveFourBlock:function(tetris_){
					tetris_.model.fallingBlock = tetris_.model.generateFourBlock(tetris_.view);
					tetris_.model.centerFourBlock(tetris_.view, tetris_.model.fallingBlock);
					tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock);
					
					document.addEventListener('keydown', function(event){
						if (event.keyCode == 67){//C键换一个4连块
							event.preventDefault();
							
							tetris_.model.fallingBlock = tetris_.model.generateFourBlock(tetris_.view);
							tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock)
						}
						tetris_.controller.listenKeyDown4UpDownLeftRight(event, tetris_);
					});
					
				},
				listenKeyDown4Rotate:function(tetris_){
					tetris_.model.fallingBlock = tetris_.model.generateFourBlock(tetris_.view, 2);

					//确认维度要在view 长宽范围内 rows 20, cols 17
					tetris_.model.accumulatedBlocks = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
													[0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,0],
													[0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,0]];
					
					tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock);
				
					document.addEventListener('keydown', function(event){
						if (event.keyCode == 67){//C键换一个4连块
							event.preventDefault();
							
							tetris_.model.fallingBlock = tetris_.model.generateFourBlock(tetris_.view);
							tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock)
						}
						
						tetris_.controller.listenKeyDown4UpDownLeftRight(event, tetris_);
					});
				
				},
				fallingBlock:[],//下降块的记录
				accumulatedBlocks:[],//记录
				prepareBlock:[],
				listenKeyDown4FallDirectly:function(tetris_){
					tetris_.model.fallingBlock = tetris_.model.generateFourBlock(tetris_.view);
					tetris_.model.prepareBlock = tetris_.model.generateFourBlock(tetris_.view);
					
					tetris_.model.centerFourBlock(tetris_.view, tetris_.model.fallingBlock);
					tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock);
					tetris_.view.refreshZoneTwo(tetris_.model.prepareBlock);
					
					var self = this;
					
					document.addEventListener('keydown', function(event){
						
						//TFIX:撤销不成功,因为是 引用 问题
						if (event.keyCode == 67 && self.fallingBlock.length != 0){//C键 撤销下降动作
							console.log('===>I\'m 67');
							//event.preventDefault();
							//console.log(tetris_.model.fallingBlock.coordinateGroup);
							
							tetris_.model.fallingBlock = self.fallingBlock.pop();
							tetris_.model.prepareBlock = self.prepareBlock.pop();
							tetris_.model.accumulatedBlocks = self.accumulatedBlocks.pop();
							
							//console.log(tetris_.model.fallingBlock.coordinateGroup);
							
							tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock);
							tetris_.view.refreshZoneTwo(tetris_.model.prepareBlock);
							return;
						}
						
						if(event.keyCode >= 37 && event.keyCode <= 40 || event.keyCode == 32){//空格键
							self.prepareBlock.push(tetris_.model.copyFourBlock(tetris_.model.prepareBlock));
							self.fallingBlock.push(tetris_.model.copyFourBlock(tetris_.model.fallingBlock));
							self.accumulatedBlocks.push(tetris_.model.copyTwoDimensionalIntegerArray(tetris_.model.accumulatedBlocks));
						}
						
						tetris_.controller.listenKeyDown4UpDownLeftRight(event, tetris_);
						
					});
				},
				startGame:function(tetris_){
					tetris_.model.fallingBlock = tetris_.model.generateFourBlock(tetris_.view);
					tetris_.model.prepareBlock = tetris_.model.generateFourBlock(tetris_.view);
					
					tetris_.model.centerFourBlock(tetris_.view, tetris_.model.fallingBlock);
					tetris_.view.refreshZoneOne(tetris_.model.accumulatedBlocks, tetris_.model.fallingBlock);
					tetris_.view.refreshZoneTwo(tetris_.model.prepareBlock);
					
					document.addEventListener('keydown', function(event){
						
						tetris_.controller.listenKeyDown4UpDownLeftRight(event, tetris_);
					});
					tetris_.controller.startTimer(tetris_);

				},
				updateTimer:function(tetris_){
					tetris_.model.score = 4999;
					tetris_.model.level = 2;
					tetris_.model.accumulatedBlocks[tetris_.model.accumulatedBlocks.length - 1]
						= [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0];
				}
			};*/
			//总结:面向接口编程,而不是面向具体
			var developMode = true;
			
			//main
			window.onload = function(){
				tetris.init();
				
				if(!developMode){
					//console.log('hi');
					//forTest.listenKeyDown4ShowAllFourBlockTemplate(tetris);//pass test
					//forTest.listenKeyDown4GenerateFourBlock(tetris);//pass test
					//forTest.listenKeyDown4MoveFourBlock(tetris);//pass test
					//forTest.listenKeyDown4Rotate(tetris);//pass test
					//forTest.listenKeyDown4FallDirectly(tetris);
					//forTest.startGame(tetris);
					//window.setInterval(alert("hello"), 1000);//Doesn't work
					//window.setInterval(function(){console.log('hi! '+ new Date() )},2000);
					//forTest.updateTimer(tetris);
				}
			};

		</script>
		
		<!-- 单元测试
		<script src="assert.js"></script>
		<script src="testCase.js"></script>
		-->
		
		<!--
			J.Kwong
			18-04-26
		-->
	</body>
</html> 

HTML+JavaScript案例分享: 打造经典俄罗斯方块,详解实现全过程 本文阐述了用 JavaScript 实现俄罗斯方块游戏。涵盖界面构建及游戏逻辑,包括形状颜色定义、状态变量设置、游戏板操作、方块移动旋转固定、满行消除等功能,还介绍了开始游戏与按键事件处理,呈现了 JavaScript 在网页游戏开发中的应用实例。 阅读详情

相关推荐

JavaScript新手实现俄罗斯方块

以下是一个使用纯JavaScript实现的俄罗斯方块游戏,可直接在浏览器中运行: 主要功能特点: 纯JavaScript实现:无需安装任何依赖,直接在浏览器中运行 控制方式: ←→键:左右移动 ↑键:旋转方块 ↓键:加速下落 游戏机制: 自动下落系统(每秒下落一格) 行消除得分(每行100分) 游戏结束检测 视觉效果: 彩色方块渲染 实时得分显示 网格背景系统 实现亮点: 碰撞检测系统:使用方法实现精准碰撞判断 方块旋转算法:通过数组转置实现矩阵旋转 性能优化:使用实现流畅动画 状态

jjjjjjjeffliu的博客 1171

用javascript写俄罗斯方块

【代码】用javascript写俄罗斯方块。

2301_78098294的博客 667

unity小游戏实践(一) 俄罗斯方块

写这个的原因是 我从网上download了一个俄罗斯的小游戏,源码是js写的  在我看来相当的混乱而且有少量bug,然后我就改成了c#的版本,在此途中认真学习到了yield在c#中的用法和俄罗斯方块的设计思路。 首先说说我设计这种游戏的话肯定不会用到yield,因为我自认为不用这样的设计也能运行得很好,就是可能代码量会多一点。 然后看看js中的 yield,作用是挂起线程,等下次运行的

DJY2130的专栏 7930

html+css+js实现俄罗斯方块

俗话说用最朴素的代码,写最炫酷的代码,没错说的正是在下下面将从几个部分开始介绍我写俄罗斯方块的几个部分。

weixin_62981580的博客 1109

前端技术搭建俄罗斯方块(内含源码)

通过前端基础HTML、CSS、JS来搭建一个俄罗斯方块小游戏,内附源码直接拷贝即可运行!

商务合作欢迎私信我 2万+

用JavaScript写的俄罗斯方块小游戏(很简单,很详细)

效果 编写外部框架 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } #box{ width:320px; height:450px; position:absolute; margin:0 auto

编程界明世隐的博客 9949

80行js代码写一个俄罗斯方块小游戏

1.俄罗斯方块 之前收藏了一个html页面的小游戏,觉得挺好玩的,也特别有学习价值,所以分享给大家,先来张效果图。 俄罗斯方块 2.代码 先看代码,然后在简单说几句,源码会在最下方的微信公众号里,关注一下,回复“俄罗斯方块”即可获取。 var map=eval("["+Array(23).join("0x801,")+"0xfff]"); var tatris=[[0x660...

李公子的博客 563

HTML5实现俄罗斯方块小游戏

HTML5实现俄罗斯方块小游戏,俄罗斯方块源码,全网最全小游戏源码,游戏界面酷炫,按键提示操作,该俄罗斯方块游戏使用html5和jQuery制作,具有使用简单、响应式、可定制、速度快、有积分记录和自动游戏的特点。代码注释完整,书写规范,各种风格都有,代码上手简单,代码独立,可以直接运行使用。也可直接预览效果。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 5万+

60行代码:Javascript 写的俄罗斯方块游戏

60行代码:Javascript 写的俄罗斯方块游戏 先看效果图:   游戏结束图:   javascript实现源码: [javascript] view plaincopyprint?    俄罗斯方块   "Description" content="俄罗斯方块Javascr

逍遥飞鹤的专栏 1818

JS俄罗斯方块游戏代码

JS俄罗斯方块游戏代码,《俄罗斯方块》的基本规则是移动、旋转和摆放游戏自动输出的各种方块,使之排列成完整的一行或多行并且消除得分。游戏注释:用键盘控制方块的下落和变形↑:变形;←:左移;↓:下移(有自定义的下落速度);→:右移;空格:速降(会直接到达最下层)。

JS和HTML和JAVAScript写简单的翻牌游戏小游戏 .html

JS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JAVAScript写简单的翻牌游戏小游戏 .htmlJS和HTML和JA

从入门到精通 JavaScript 1000例实战开发专栏--教你做经典小游戏--实例2:俄罗斯方块

俄罗斯方块是一款经典的益智游戏,玩家需要操控不同形状的方块,使其在屏幕上排列成完整的行,从而消除这些行并获得分数。本教程将带你一步步实现这个经典游戏,使用HTML5和JavaScript来创建一个可以在网页上运行的俄罗斯方块游戏。通过本教程,你学会了如何使用HTML5和JavaScript创建一个经典的俄罗斯方块游戏。你可以进一步扩展这个游戏,添加更多功能,如不同的难度级别、更复杂的图形和动画效果等。希望你在编写游戏的过程中享受乐趣,并继续探索更多有趣的项目!

MHD0815的博客 504

【TestNG自动化测试框架详解】

TestNG是一款设计测试用例执行流程的测试框架。

weixin_43936332的博客 1556

javascript实现俄罗斯方块

以前一直想写俄罗斯方块,连连看,坦克大战等经典的小游戏,不过本人太浮躁,每次写一半遇到问题就放弃了。 这次是自己第一次坚持写完了这个俄罗斯方块。 对javascript不是很熟,所以一些编程的格式,用法什么的不太规范,还需继续努力,加油,学习学习在学习,练习练习在练习。 您的浏览器不支持canvas标签 score: level:

liufeng0103 1137

浙大数值分析lab2

最可怕的一道题,题目是这样的 Root of a Polynomial A polynomial of degree nnn has the common form as p(x)=cnxn+cn−1xn−1+⋯+c1x+c0p(x)=c_n x^n + c_{n-1} x^{n-1} + \cdots + c_1 x + c_0p(x)=c​n​​x​n​​+c​n−1​​x​

yao_zou的博客 4806

FPGA:将FIFO封装成AXI接口的IP

封装AXI_stream的接口IP核

m0_46830519的博客 4224

大道至简 html + js 实现最朴实的小游戏俄罗斯方块

前言 老实说这其实是自己写的第二个俄罗斯方块。 本次的重写,除了复习一下以前自己写的代码的同时,也有一些新的考量。 其中最重要的一个目的就是渲染层与逻辑层在代码层面的分离。 正题 先复习一下俄罗斯方块的一些概念 方块 先上一张效果图 ...

苹果蜀黍与福尔猫斯 428

红日-VulnStack靶场-ATT&CK(二):从Weblogic漏洞到域控渗透实战

本文详细解析了红日安全团队VulnStack靶场中从Weblogic漏洞到域控渗透的完整攻击链。通过实战演示Weblogic反序列化漏洞利用、Cobalt Strike持久化控制、域内信息收集及PsExec横向移动等关键技术,复现了企业内网渗透的典型场景,并提供了防御建议。

tgb3456789的博客 949

用js写网页版俄罗斯方块小游戏

6.玩家可以通过点击"开始游戏"按钮开始新游戏,当方块堆积到顶部时游戏结束。可以通过调整代码中的常量(如BLOCK_SIZE、下落速度等)来自定义游戏参数。2.键盘控制(A/D左右移动,M旋转,空格加速下落)4.支持连续得分(消除多行有额外奖励)1.使用HTML5 Canvas渲染。1.经典俄罗斯方块规则和计分系统。3.自动下落速度(每秒一格)5.简单的碰撞检测和旋转逻辑。3.得分统计和游戏状态显示。5.多种颜色和形状的方块。

2401_86427160的博客 425

Android 白名单保活实战:主流厂商适配指南

本文详细解析了Android应用白名单保活的实战策略,重点针对华为、小米、OPPO、vivo等主流厂商的系统特性,提供了精准的后台设置页面跳转适配方案。文章从基础的前台服务实现讲起,深入讲解了白名单的判断、申请与厂商适配的核心代码与避坑指南,旨在帮助开发者合规、稳定地提升应用后台存活率。

motor的博客 1875

Windows 11下用Ollama一键部署DeepSeek-R1大模型(附8B/14B版本选择建议)

本文详细介绍了在Windows 11环境下使用Ollama工具一键部署DeepSeek-R1大模型的完整指南,包括8B和14B版本的选择建议。通过硬件评估、安装配置、性能优化等步骤,帮助开发者高效实现本地部署,提升AI应用体验。

weixin_29079643的博客 284

(小游戏)详解前端俄罗斯方块代码:HTML+JS+CANVAS实现原理

喜欢就给我点个星吧:https://github.com/Chenyating/easyGame 想写个俄罗斯方块的小游戏,发现网上的各位大佬的代码,我看不明白。 好吧,其实我一直都看不懂别人的代码。 可是,flag已经立了,写肯定是要写的啦。 嗯……还是自力更生,自给自足。撸起袖子,说写就写。现在就说说我自己的经验; 查看效果,请点击这个地址哦~,你们可以玩一把,告诉我需要改进的地...

认真和努力总没有错 7522

第17章 后端开发最佳实践 —— OpenSpec + 智能体的工程化实战

后端开发有大量重复性的"样板代码"工作。我们可以创建自定义 Skill,让 AI 自动生成标准的三层架构代码。创建 Skill:后端 CRUD 生成器以 CodeBuddy 为例,在创建:其他工具用户请参考各自文档,了解如何创建自定义 Skills 或类似机制。skill.md## 描述根据实体定义自动生成标准的三层架构代码(Controller-Service-Repository)## 适用场景- 快速创建实体的 CRUD 接口- 保持代码结构一致性- 减少重复性编码工作## 使用方法。

快乐的修补匠的专栏 330

JS写俄罗斯方块完美注释版

JS写俄罗斯方块完美注释版/************************************************************* JS俄罗斯方块完美注释版 v 1.01* 作者: sunxing007* 转载请说明来自: http://blog.csdn.net/sunxing007*********************************************

sunxing007的专栏 2万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

用html写游戏,Html5写一个简单的俄罗斯方块小游戏

导言在一个风和日丽的一天,看完了疯狂HTML 5+CSS 3+JavaScript讲义,跟着做了书里最后一章的俄罗斯方块小游戏,并做了一些改进,作为自己前端学习的第一站。游戏效果:制作思路因为书里的俄罗斯方块比较普通,太常规了,不是很好看,所以我在网上找了上面那张图片,打算照着它来做。(请无视成品和原图的差距)然后便是游戏界面和常规的俄罗斯方块游戏逻辑。接着便是游戏结束界面了。原本想做个弹出层,但...

weixin_36285931的博客 2729

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

上一篇: 《集体智慧编程》笔记(4 / 12):搜索与排名
下一篇: Python函数参数前的单星号(*)和双星号(**)的作用
巨輪
博客等级 码龄13年 3万+粉丝 335原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值