通过上一篇的代码,我们已经实现了五子棋这个游戏,并且可以开始人机大战了。不过js的代码部分还是新手写法,扩展性也不强,也不容易修改,假如我们把棋盘大小改一下要修改很多地方,要加入别的功能也会很困难,所以后续又改成了面向对象的写法,想必这样做的有点我不用再赘述了,直接上代码:
function chess(){ var self=this; this.canvas=document.getElementById("canvas"); this.context=this.canvas.getContext('2d'); this.bootWidth=30; this.bootHeight=this.bootWidth; this.canvasWidth=this.bootWidth*15; this.canvasHeight=this.bootHeight*15; this.me=true; //表示棋盘位置的二维数组 this.chessBoard=[]; //定义一个赢法数组 this.wins=[]; //赢法种类索引 this.count=0; //定义我和电脑的赢法数组 this.myWin=[]; this.computerWin=[]; this.over=false; this.canvas.width=this.canvasWidth; this.canvas.height=this.canvasHeight; this.img=new Image(); this.img.src="Images/logo.png"; this.img.οnlοad=function(){ self.context.drawImage(self.img,0,0,self.canvasWidth,self.canvasHeight); self.drawChessBoard(self.bootWidth,self.bootHeight); } //将棋盘位置二维数组初始化为0 this.initChessBoard(); //初始化赢法数组 this.initWins(); //初始化我和电脑的赢法数组 this.initMeAndComputerWin(); this.canvas.οnclick=function(e){ if(self.over){ return; } var x= e.offsetX; var y= e.offsetY; var i=Math.floor(x/self.bootWidth); var j=Math.floor(y/self.bootHeight); </