基于vue框架使用canvas实现井字棋小游戏

引言:最近实现了一个图片上传压缩的功能,使用了canvas,所以学习一下canvas的语法,实现一个井字棋小游戏,这个小游戏可以人人对弈,如果大家有兴趣,可以对代码进行迭代,比如采用极大值极小值搜索法来实现人机对弈或者机机对弈。

1. 创建画布

<div id="app" >
			<div style="border: solid 1px #000000 ;width: 600px;height: 600px;" @click="getLocation">
				<canvas id="mycanvas" width="600px" height="600px"></canvas>
			</div>
			<div style="margin: 15px;">
				<button type="button" @click="drawBoard()" >清空棋盘</button>
			</div>
			
		</div>

2. 初始画棋盘
首先需要画出四条线,我定义的棋盘大小为600,

drawBoard(){
						this.clearAll();
						this.context.beginPath();
						this.context.moveTo(0, 200);
						this.context.lineTo(600, 200);
						this.context.moveTo(0, 400);
						this.context.lineTo(600, 400);
						this.context.moveTo(200, 0);
						this.context.lineTo(200, 600);
						this.context.moveTo(400, 0);
						this.context.lineTo(400, 600);
						this.context.strokeStyle = 'pink';
						this.context.closePath();
						this.context.stroke();
					},

3. 画O

drawO(x,y){
						this.context.beginPath();
						this.context.arc(x, y, 60, 0, Math.PI * 2, true);
						this.context.fillStyle = 'rgba(0,255,0,0.25)'
						this.context.fill();
						this.context.closePath();
						this.context.stroke();
					},

4. 画X

drawX(x,y){
						 this.context.beginPath();
						 this.context.moveTo(x-40, y-40);
						 this.context.lineTo(x+40, y+40);
						 this.context.moveTo(x+40, y-40);
						 this.context.lineTo(x-40, y+40);
						 this.context.strokeStyle = 'orange';
						 this.context.closePath();
						 this.context.stroke();
					},

5.将棋子画到棋盘
那么如何将O和X画到每个格子的中心位置呢,我是这样解决的:首先获取鼠标点击位置的坐标,设我的棋盘步长为step=200,这样就可以算出点击任意一个格子的中心点(x,y):

			let arr_x = parseInt(e.clientX/this.step);
			let arr_y = parseInt(e.clientY/this.step);
			let x = arr_x * this.step+(this.step/2);
			let y = arr_y * this.step+(this.step/2);

例如:鼠标点击坐标为(158,120),那么arr_x=0,arr_y=0,这就代表他点击了第一个格子,第一个格子中心点就为(100,100),以此类推。

6. 判断输赢
如何判断输赢呢,我们都知道三个相同的连成一条线就代表赢,我这里初始化了一个二维数组,二维数组的每一项的值都为零。

//棋盘初始化
					initBoard() {
						this.arr = ''
						let t = new Array()
						for(let p = 0;p<3;p++){
							t[p] = new Array()
						}
						for(let i=0;i<3;i++){
							for(let j=0;j<3;j++){
								t[i][j] = 0
							}
						}
					},

当下棋的时候,这个数组的位置就设置为1或者2,当三个1连成一条线这就代表一方赢,我这里给出一种情况判断输赢,其他情况可以自行完善。

if(this.arr[0][0] == 1 && this.arr[0][1] == 1&& this.arr[0][2] == 1){
		alert("O方获胜")
		return
	}

7. 交换下棋方
如何判断哪一方下棋呢,我定义了一个flag,初始值为true,当一方下完,就将flag设置为false,以此类推,判断一下就可以了。

8. 下完棋后,需要清空棋盘

clearAll(){
				this.initBoard()//初始化棋盘数组
				this.context.clearRect(0,0,600,600)//清空画布
				//重设高度也可以清空画布
				this.mycanvas.height = 600;
				this.mycanvas.width = 600;
			},

此代码仅仅是练习使用,有好多处可以优化的地方,欢迎大家来谈论~
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失忆症患者_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值