unity3d(人機博弈,棋類相關)
阿新 • • 發佈:2018-12-14
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; } } //