unity3d(人机博弈,棋类相关)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36294146/article/details/82015903

2018/08/26,主要是一个井字棋的实现(人人版),代码用的是c# 

/*不带AI,版本1.0beta*/

using UnityEngine;
using System.Collections;
public class Chess : MonoBehaviour {
	private int turn = 1;//规定是谁的回合,1代表对手,-1代表自己
	private int[,] chess = new int[3, 3];
	
	
	//参数初始化
	void Start()
	{
		reset();
	}
	
	//unity自带图像库OnGUI使用
	void OnGUI()
	{
		if (GUI.Button(new Rect(20, 300, 100, 50), "Reset"))   //重置 ,X,Y,width,height
		  reset();
		int flag = check();  //
		if (flag == 1) {
			GUI.Label (new Rect (50, 230, 100, 50), "是琪琪赢了!");
		} else if (flag == 2) {
			GUI.Label (new Rect (50, 230, 100, 50), "是贝贝赢了!");   //GUI里面显示文字
		} 
		/*
		else if (flag == 0) {
			GUI.Label (new Rect (50, 230, 100, 50), "贝贝琪琪打平,再来一局!");
		}
		*/
		for (int i = 0; i < 3; i++) { 
			for (int j = 0; j < 3; j++)
			{
				if (chess[i, j] == 1)
				{
					GUI.Button(new Rect(50 * i, 50 * j, 50, 50), "O");
					
				}
				if (chess[i, j] == 2)
				{
					GUI.Button(new Rect(50 * i, 50 * j, 50, 50), "X");
				}
				if (GUI.Button(new Rect(50 * i, 50 * j, 50, 50), "")){ 
					
					if (flag == 0)
					{
						if (turn == 1)
							chess[i,j] = 1;
						else 
							chess[i,j] = 2;
						turn = -turn;
					}
				}
				
			}
		}
	}
	
	void reset()
	{
		turn = 1;
		for (int i = 0; i < 3; ++i)
		{
			for (int j = 0; j < 3; ++j)
			{
				chess[i, j] = 0;
			}
		}
	}
	
	
	//判断游戏结束条件
	int check()
	{
		for (int i = 0; i < 3; i++)
		{
			if (chess[i, 0] != 0 &&chess[i,0]== chess[i, 1] && chess[i, 1] == chess[i, 2])
				return chess[i, 2];
			else if (chess[i, 0] != 0 &&chess[0, i] == chess[1, i] && chess[1, i] == chess[2, i])
				return chess[2, i];
			
		}
		if (chess[1, 1] != 0)
		{
			if ((chess[0, 0] == chess[1, 1] && chess[1, 1] == chess[2, 2]) || chess[0, 2] == chess[1, 1] && chess[1, 1] == chess[2, 0])
				return chess[1, 1];
		}
		
		return 0;
	}
	
}

//

猜你喜欢

转载自blog.csdn.net/qq_36294146/article/details/82015903