html5 canvas實踐

本文介绍了一个基于Canvas的游戏实现方案,通过自定义JavaScript类和方法来处理游戏逻辑与UI展示,并预留了WebSocket接口以便后续开发对战版本。文章详细展示了如何进行元素匹配、路径查找及图像绘制等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/*这部分是主要的js方面的,只测试过chrome浏览器*/

Array.prototype.S=String.fromCharCode(2);

Array.prototype.in_array=function(e)
{
var r=new RegExp(this.S+e+this.S);
return (r.test(this.S+this.join(this.S)+this.S));
}
Array.prototype.matching_math = function(){
	var re = 0;
	for(var i = 0 ; i < this.length ; i++){
		re += parseInt(this[i]);
	}
	return re;
}
function Region(x,y,width,height){
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
}
function Matching(h_num,v_num,container,level,gamedata){
	this.regions = [];
	this.canvas = document.getElementById("canvas");
	this.ctx = canvas.getContext("2d");
	this.gamedata = gamedata;
	this.t = null;
	this.w = 60;
	this.h = 60;
	this.level = level;
	this.param = (h_num*v_num) / 2;
	this.h_num = h_num;
	this.v_num = v_num;
	this.container = $(container);
	this.linkpath = [];
	this.sourceNode = "";
	this.currentNode = "";
	this.loadcount = 0;
	this.mapdata = (function(){
		var imgarr = [];
		
		for(var i = 0 ; i < level ; i++){
			var temp = i+1;
			imgarr[i] = temp;
		}
		return imgarr;
	})();
	this.paramdata = (function(){ //  返回有對應圖片的對數
		
		var imgarr = [];
		var pushpos = 0;
		var maxData = (function(){
			var r = 0;
			for(var i = 0 ; i < gamedata.length ; i++){
				for(var j = 0 ; j < gamedata[i].length ; j++){
					if(gamedata[i][j] == 0)
						r += 1;
				}
			}
			return r;
		})();
		while(parseInt(imgarr.matching_math()) < maxData/2){
			imgarr[pushpos] = imgarr[pushpos] ? imgarr[pushpos] + 1:1;
			pushpos = pushpos == (level-1) ? 0 : (pushpos +1);
			
		}
		return imgarr;
	})();
	this.couple = (h_num*v_num) / 2;
}

Matching.prototype = {
	getPoint:function(){
		var m = this.gamedata;
		var point = [];
		
		for(var i = 0 ; i < m.length ; i++){
			if(!m[i])
				break;
			for(var j = 0 ; j < m[i].length ; j++){
				if(m[i][j] > -1){
					var p = i+"_"+j;
					point.push(p);
				}
					
			}
		}
		return point;
	},
	getparam:function(){
		return this.paramdata;
	},
	getmapdata:function(){
		return this.mapdata;
	},
	matchingoneline:function(pos,position){
		//console.log("開始查找路徑");
		
		/*
			matching just use one line
			水平判斷
		*/
		var sxpos = this.sourceNode.split(",")[0];
		var sypos = this.sourceNode.split(",")[1];
		var cxpos = this.currentNode.split(",")[0];
		var cypos = this.currentNode.split(",")[1];
		if(position == "yline"){
			//console.log("yline");

			
			
			
			var startpos = parseInt(cypos) > parseInt(sypos) ? sypos:cypos;
			var endpos = parseInt(cypos) < parseInt(sypos) ? sypos:cypos;
			var distance = Math.abs(parseInt(endpos) - parseInt(startpos));
			var loopcount = 0;
			//console.log("start pos:"+startpos+"   end pos:"+endpos);
			for(var i = parseInt(startpos)+1 ; i < parseInt(endpos) ; i++){
				//console.log($("div.map_"+pos+"_"+i).attr("data"));
				if(this.gamedata[pos][i] == "-1"){
					loopcount++;
				}
			}
			if(distance == 1 || loopcount ==  distance-1){
				//console.log("["+cxpos+","+cypos+"] ["+sxpos+","+sypos+"] xline pos="+pos);
				this.drawline(this.sourceNode,pos+","+sypos,pos+","+cypos,this.currentNode);
				return true;
				
			}else
				return false;
		}
		/*
			matching just use one line
			垂直方向判斷
		*/
		
		if(position == "xline"){
			//console.log("xline");
			
			var startpos = parseInt(cxpos) > parseInt(sxpos) ? sxpos:cxpos;
			var endpos = parseInt(cxpos) < parseInt(sxpos) ? sxpos:cxpos;
			
			var distance = Math.abs(parseInt(endpos) - parseInt(startpos));
			
			
			var loopcount = 0;
			//console.log("start pos:"+startpos+"   end pos:"+endpos);
			for(var i = parseInt(startpos)+1 ; i < parseInt(endpos) ; i++){
			
				if(this.gamedata[i][pos] == "-1" ){
					loopcount++;
				}
			}
			if(distance == 1 || loopcount ==  distance-1){
				//console.log("["+cxpos+","+cypos+"] ["+sxpos+","+sypos+"] xline pos="+pos);
				this.drawline(this.sourceNode,sxpos+","+pos,cxpos+","+pos,this.currentNode);
				return true;
				
			}else
				return false;
		}
		
	},
	findit:function(){		
		var sxpos = parseInt(this.sourceNode.split(",")[0]);
		var sypos = parseInt(this.sourceNode.split(",")[1]);
		var cxpos = parseInt(this.currentNode.split(",")[0]);
		var cypos = parseInt(this.currentNode.split(",")[1]);
		/*
			新算法
			先查找對應的水平或者垂直方向的公共區域,然后判斷兩點是否連通
		*/
		var sxEl = [],
			cxEl = [],
			syEl = [],
			cyEl = [];
		// push sxpos and sypos where =-1
		for(var i = sxpos-1 ; i > -1 ; i--){
			if(this.gamedata[i][sypos] == "-1")
				sxEl.push(i);
			else
				break;
		}
		for(var i = sxpos+1 ; i < this.v_num+2 ; i++){
			if(this.gamedata[i][sypos] == "-1")
				sxEl.push(i); 
			else
				break;
		}
		sxEl.push(sxpos);
		
		for(var i = sypos-1 ; i > -1 ; i--){
			if(this.gamedata[sxpos][i] == "-1")
				syEl.push(i); 
			else
				break;
		}
		for(var i = sypos+1 ; i < this.h_num+2; i++){
			if(this.gamedata[sxpos][i] == "-1")
				syEl.push(i); 
			else
				break;
		}
		syEl.push(sypos);
		
		// push cxpos and cypos where =-1
		for(var i = cxpos-1 ; i > -1 ; i--){
			if(this.gamedata[i][cypos] == "-1")
				cxEl.push(i); 
			else
				break;
		}
		for(var i = cxpos+1 ; i < this.v_num+2 ; i++){
			if(this.gamedata[i][cypos] == "-1")
				cxEl.push(i); 
			else
				break;
		}
		cxEl.push(cxpos);
		
		for(var i = cypos-1 ; i > -1 ; i--){
			if(this.gamedata[cxpos][i] == "-1")
				cyEl.push(i); 
			else
				break;
		}
		for(var i = cypos+1 ; i < this.h_num +2; i++){
			if(this.gamedata[cxpos][i] == "-1")
				cyEl.push(i); 
			else
				break;
		}
		cyEl.push(cypos);
		/*
		console.log("cxEl:"+cxEl);
		console.log("cyEl:"+cyEl);
		console.log("sxEl:"+sxEl);
		console.log("syEl:"+syEl);
		*/
		/* 查找X方向相同點 */
		var samexpos = [],sameypos = [];
		for(var i = 0 ; i < sxEl.length ; i++){
			for(var j = 0 ; j < cxEl.length ; j++){
				if(sxEl[i] == cxEl[j])
					sameypos.push(parseInt(cxEl[j]));
			}
		}
		
		
		
		
		/* 查找y方向相同點 */
		for(var i = 0 ; i < syEl.length ; i++){
			for(var j = 0 ; j < cyEl.length ; j++){
				if(syEl[i] == cyEl[j])
					samexpos.push(parseInt(cyEl[j]));
			}
		}
		//console.log("same y pos:"+samexpos);
		//console.log("same x pos:"+sameypos);
		
		for(var i = 0 ; i < samexpos.length ; i++){
			if(this.matchingoneline(samexpos[i],"xline")){
				return true;
				break;
			}
		}
		
		for(var i = 0 ; i < sameypos.length ; i++){
			if(this.matchingoneline(sameypos[i],"yline")){
				return true;
				break;
			}
		}
		
		
		
		return false;
	},
	drawpoint:function(sourceEl,currentEl){

		
		var sxpos = parseInt(sourceEl.split(",")[0]);
		var sypos = parseInt(sourceEl.split(",")[1]);
		var cxpos = parseInt(currentEl.split(",")[0]);
		var cypos = parseInt(currentEl.split(",")[1]);
		if(sxpos == cxpos && sypos == cypos)
			return;
        this.ctx.beginPath();
		this.ctx.lineWidth = 6;
		this.ctx.strokeStyle = "#1b85c1";
        this.ctx.moveTo((sypos+1) * 66  - 30 ,(sxpos+1) * 66  - 30  );
        this.ctx.lineTo((cypos+1) * 66  - 30 ,(cxpos+1) * 66  - 30 );
        this.ctx.stroke();
	},
	playerMp3:function(){
			var p = $("<div></div>");
			p.appendTo("body");
			var player = p.jPlayer({
				ready: function () {
					$(this).jPlayer("setMedia", {
						mp3: "js/dp.mp3"
					}).jPlayer("play");
				},
				ended: function (event) {
					$(this).jPlayer("destroy");
					p.remove();
				},
				swfPath: "js",
				supplied: "mp3"
			});
		
	},
	drawline:function(osEl,sEl,ocEl,cEl){
		//this.ctx.save();
		//console.log(osEl+" to "+sEl+" to "+ocEl+" to "+cEl);
		this.drawpoint(osEl,sEl);
		this.drawpoint(sEl,ocEl);
		this.drawpoint(ocEl,cEl);
		var _this = this;
		setTimeout(function(){
			_this.ctx.clearRect(0,0,_this.canvas.width,_this.canvas.height);

			var sxpos = parseInt(osEl.split(",")[0]);
			var sypos = parseInt(osEl.split(",")[1]);
			var cxpos = parseInt(cEl.split(",")[0]);
			var cypos = parseInt(cEl.split(",")[1]);
			
			_this.sourceNode = "";
			_this.currentNode = "";
			_this.gamedata[sxpos][sypos] =-1;
			_this.gamedata[cxpos][cypos] =-1;
			//重新绘制map
			_this.map();
			_this.drawCurrentMap();
		},200);

		this.playerMp3();
		
	},
	dbparam:function(){
		var param = this.getparam();
		for(var i = 0 ; i < param.length ; i++){
			param[i] *= 2;
		}
		
		return param;
	},
	loadpic:function(){
		var _this = this;
		
		var param = this.getparam();
		var datas = this.getmapdata();
		var dbparam = this.dbparam();
		for(var i = 0 ; i < this.v_num+2 ; i++){
			for(var j = 0 ; j < this.h_num+2;j++){
				for(var m = 0 ; m < this.level ; m++){
					if(parseInt(dbparam[m]) > 0 && this.gamedata[i][j] == 0){
						dbparam[m]--;
						this.gamedata[i][j] = m;
						break;
					}
				}
			}
		}
		var localdata = this.gamedata;
		var allpoint = this.getPoint();
		//console.log(allpoint);
		var pointlen = allpoint.length;
		for(var i = 0 ; i < 2000 ; i++){
			var posrotate1=parseInt(Math.random()*pointlen);
			var posrotate2=parseInt(Math.random()*pointlen);
			var x1 = parseInt(allpoint[posrotate1].split("_")[0]);
			var y1 = parseInt(allpoint[posrotate1].split("_")[1]);
			var x2 = parseInt(allpoint[posrotate2].split("_")[0]);
			var y2 = parseInt(allpoint[posrotate2].split("_")[1]);

			var temp = localdata[x1][y1];
			localdata[x1][y1] = localdata[x2][y2];
			localdata[x2][y2] = temp;
		}
		
		//打亂了之后的數據
		this.drawCurrentMap();
		$(this.canvas).bind("click",{_this:this},this.clickFun);
		this.gamedata = localdata;
		
	},
	drawCurrentMap:function(){
		var _this = this;
		
		if(_this.loadcount == 17){
			for(var i = 0 ; i < _this.v_num+2 ; i++){
				for(var j = 0 ; j < _this.h_num+2;j++){
					if(_this.gamedata[i][j] > -1){
						var p = new Image();
						p.src="images/"+(_this.gamedata[i][j] + 1)+".png";
						_this.ctx.clearRect(j*60+6*(j+1), i*60+6*(i+1), 60, 60);
						_this.ctx.fillStyle="#FFF";
						_this.ctx.fillRect (j*60+6*(j+1), i*60+6*(i+1), 60, 60);
						_this.ctx.drawImage(p,j*60+6*(j+1), i*60+6*(i+1), 60, 60);
							//p = null;
					}
			
				}
			}
		}else{
			for(var i = 1; i <= 17 ; i++){
				var p = new Image();
				p.onload = function(){_this.loadcount++};
				p.src="images/"+i+".png";
			}
			var cc = setInterval(function(){
				if(_this.loadcount == 17){
					for(var i = 0 ; i < _this.v_num+2 ; i++){
						for(var j = 0 ; j < _this.h_num+2;j++){
							if(_this.gamedata[i][j] > -1){
								var p = new Image();
								p.src="images/"+(_this.gamedata[i][j] + 1)+".png";
								_this.ctx.clearRect(j*60+6*(j+1), i*60+6*(i+1), 60, 60);
								_this.ctx.fillStyle="#FFF";
								_this.ctx.fillRect (j*60+6*(j+1), i*60+6*(i+1), 60, 60);
								_this.ctx.drawImage(p,j*60+6*(j+1), i*60+6*(i+1), 60, 60);
								//p = null;
							}
				
						}
					}
					clearInterval(cc);
					cc = null;
				}
			},50);
		}
		
	},
	clickFun:function(e){
		
		var _this = e.data._this;
		//console.log(_this.gamedata);
		var mouseX = e.clientX - canvas.offsetLeft;
		var mouseY = e.clientY - canvas.offsetTop;
		var topStock = parseInt(mouseX / 66,10);	// 判斷左側的格子個數
		var leftStock = parseInt(mouseY / 66,10);	// 判斷頂部的格子個數
		if(_this.gamedata[leftStock][topStock] == "-1")
			return;
		if(_this.sourceNode == ""){
			
			
			_this.drawStoneImage(leftStock,topStock,0.5);
			//console.log("mouseX:"+mouseX + ",mouseY:"+mouseY);
			//console.log("leftStock:"+leftStock + ",topStock:"+topStock);
			
			_this.sourceNode = leftStock+","+topStock;
		}else{
			_this.currentNode = leftStock+","+topStock;
			var sx = parseInt(_this.sourceNode.split(",")[0]);
			var sy = parseInt(_this.sourceNode.split(",")[1]);
			var cx = parseInt(_this.currentNode.split(",")[0]);
			var cy = parseInt(_this.currentNode.split(",")[1]);

			if(_this.currentNode == _this.sourceNode || _this.gamedata[sx][sy] != _this.gamedata[cx][cy]){
				_this.drawStoneImage(cx,cy);
				_this.drawStoneImage(sx,sy);

				_this.currentNode = "";
				_this.sourceNode = "";
				
				//console.log("mouseX:"+mouseX + ",mouseY:"+mouseY);
				//console.log("leftStock:"+leftStock + ",topStock:"+topStock);
			}else{
				_this.drawStoneImage(cx,cy,0.5);
				// _this.findPath()
				if(_this.findit()){
					//console.log("find it");
					_this.clearImage(cx,cy);
					_this.clearImage(sx,sy);
				}else{
					//console.log("findn't it");
					_this.drawStoneImage(cx,cy);
					_this.drawStoneImage(sx,sy);
				}
			}
		}
	},
	drawStoneImage:function(x,y,transparent){
		var trans = transparent || 1;
		var p = new Image();				
		p.src="images/"+(parseInt(this.gamedata[x][y]) + 1)+".png";
		this.ctx.clearRect(y*60+6*(y+1), x*60+6*(x+1), 60, 60);
		this.ctx.fillStyle = "rgba(255, 255, 255, "+trans+")";
		if(trans != 1){
			/*畫上圖片*/
			this.ctx.drawImage(p,y*60+6*(y+1), x*60+6*(x+1), 60, 60);
			/*畫上透明背景*/
			this.ctx.fillRect (y*60+6*(y+1), x*60+6*(x+1), 60, 60);
		}else{
			this.ctx.fillRect (y*60+6*(y+1), x*60+6*(x+1), 60, 60);
			this.ctx.drawImage(p,y*60+6*(y+1), x*60+6*(x+1), 60, 60);
		}
		p = null;
	},
	clearImage:function(x,y){
		return;
		var trans = 1;
		this.ctx.clearRect(y*60+6*(y+1), x*60+6*(x+1), 60, 60);
		this.ctx.fillStyle = "rgba(255, 255, 255, "+trans+")";
		
	
		/*畫上透明背景*/
		this.ctx.fillRect (y*60+6*(y+1), x*60+6*(x+1), 60, 60);
		this.sourceNode = "";
		this.currentNode = "";
		this.gamedata[x][y] = -1;
		
	},
	map:function(){
		var htmlstring = "";
		var box_count = 0;
		
		this.ctx.fillStyle = "rgb(0,0,0)";
		this.ctx.fillRect (0, 0, canvas.width, canvas.height);
		for(var i = 0 ; i < this.v_num+2 ; i++){
			for(var j = 0 ; j < this.h_num+2;j++){
				this.ctx.fillStyle="#FFF";
				this.ctx.fillRect (j*60+6*(j+1), i*60+6*(i+1), 60, 60);
			}
		}
		
	}
}

/*canvas event*/




var mapdata = [
[0,0,0,0,0,0,0,0,0,0,0],
[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
[0,0,0,0,0,0,0,0,0,0,0],
[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
];
var matching = new Matching(9,6,"#canvas",17,mapdata);
matching.map();
$(".console a").click(function(e){
	e.preventDefault();
	matching.loadpic();
			
});



 

再利用websockets就可以做成對戰版本了

源碼下載地址是

 http://www.css-ajax.com/html5/game/usecanvas.zip

CH341A编程器是一款广泛应用的通用编程设备,尤其在电子工程和嵌入式系统开发领域中,它被用来烧录各种类型的微控制器、存储器和其他IC芯片。这款编程器的最新版本为1.3,它的一个显著特点是增加了对25Q256等32M芯片的支持。 25Q256是一种串行EEPROM(电可擦可编程只读存储器)芯片,通常用于存储程序代码、配置数据或其他非易失性信息。32M在这里指的是存储容量,即该芯片可以存储32兆位(Mbit)的数据,换算成字节数就是4MB。这种大容量的存储器在许多嵌入式系统中都有应用,例如汽车电子、工业控制、消费电子设备等。 CH341A编程器的1.3版更新,意味着它可以与更多的芯片型号兼容,特别是针对32M容量的芯片进行了优化,提高了编程效率和稳定性。26系列芯片通常指的是Microchip公司的25系列SPI(串行外围接口)EEPROM产品线,这些芯片广泛应用于各种需要小体积、低功耗和非易失性存储的应用场景。 全功能版的CH341A编程器不仅支持25Q256,还支持其他大容量芯片,这意味着它具有广泛的兼容性,能够满足不同项目的需求。这包括但不限于微控制器、EPROM、EEPROM、闪存、逻辑门电路等多种类型芯片的编程。 使用CH341A编程器进行编程操作时,首先需要将设备通过USB连接到计算机,然后安装相应的驱动程序和编程软件。在本例中,压缩包中的"CH341A_1.30"很可能是编程软件的安装程序。安装后,用户可以通过软件界面选择需要编程的芯片类型,加载待烧录的固件或数据,然后执行编程操作。编程过程中需要注意的是,确保正确设置芯片的电压、时钟频率等参数,以防止损坏芯片。 CH341A编程器1.3版是面向电子爱好者和专业工程师的一款实用工具,其强大的兼容性和易用性使其在众多编程器中脱颖而出。对于需要处理25Q256等32M芯片的项目,或者26系列芯片的编程工作,CH341A编程器是理想的选择。通过持续的软件更新和升级,它保持了与现代电子技术同步,确保用户能方便地对各种芯片进行编程和调试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值