unity提供了通过C#脚本来控制游戏的进程。
同时也提供了Immediate Mode GUI (IMGUI)来在脚本中绘制简单的UI,主要通过OnGUI()事件来实现。
利用C#脚本和IMGUI,我们可以实现编写一些简单的棋类游戏并在unity中运行。
创建脚本“wuziqi.cs”并书写代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class wuziqi : MonoBehaviour
{
private static int player;
private int winner;
private int x;
private int y; //记录当前棋子的位置
private int[,] chessBoard = new int[8, 12];//记录棋盘状态
// Start is called before the first frame update
void Start()
{
Init();
}
// Update is called once per frame
void OnGUI() {
GUI.Box(new Rect(10, 10, 600, 400), "");
if (GUI.Button(new Rect(610, 400, 100, 30), "Restart")) Init();
if (!GameOver()) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 12; j++) {
if (chessBoard[i, j] == 0 && GUI.Button(new Rect(10 + j * 50, 10 + i * 50, 50, 50), "")) {
PutChess(i,j);
}
else if (chessBoard[i, j] == 1) GUI.Button(new Rect(10 + j * 50, 10 + i * 50, 50, 50), "O");
else if (chessBoard[i, j] == 2) GUI.Button(new Rect(10 + j * 50, 10 + i * 50, 50, 50), "X");
}
}//如果游戏尚未结束,则绘制整个棋盘
}
else {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 12; j++) {
if (chessBoard[i, j] == 0 && GUI.Button(new Rect(10 + j * 50, 10 + i * 50, 50, 50), "")) {
}
else if (chessBoard[i, j] == 1) GUI.Button(new Rect(10 + j * 50, 10 + i * 50, 50, 50), "O");
else if (chessBoard[i, j] == 2) GUI.Button(new Rect(10 + j * 50, 10 + i * 50, 50, 50), "X");
}}
GUI.Box(new Rect(10, 10, 600, 400), "\n\n\n\n\nCongratulations!\n Player "+winner+" has won.");
}//如果游戏结束,则提示胜者
}//ui绘制函数
void Init() {
player = 1;
winner = 0;
x=0;
y=0;
for(int i = 0; i < 8; i++)
for(int j = 0; j < 12; j++)
chessBoard[i, j] = 0;
}//初始化游戏
void PutChess(int i,int j) {
chessBoard[i, j] = player;
x=i; y=j;
player = 3 - player;
}//放下棋子
bool GameOver() {
int b=1;
int c=1;
for(;x+b<8&&chessBoard[x+b,y]==3-player;b++);
for(;x-c>=0&&chessBoard[x-c,y]==3-player;c++);
if (b+c>=6) {winner=3-player; return true;}//数竖向的同色棋子,超过5就返回true
for(b=1;y+b<12&&chessBoard[x,y+b]==3-player;b++);
for(c=1;y-c>=0&&chessBoard[x,y-c]==3-player;c++);
if (c+b>=6) {winner=3-player; return true;}//数横向的同色旗子,超过5就返回true
for(b=1;x+b<8&&y+b<12&&chessBoard[x+b,y+b]==3-player;b++);
for(c=1;x-c>=0&&y-c>=0&&chessBoard[x-c,y-c]==3-player;c++);
if (c+b>=6) {winner=3-player; return true;}//数从右上斜向到左下的同色棋子,超过5就返回true
for(b=1;x+b<8&&y-b>=0&&chessBoard[x+b,y-b]==3-player;b++);
for(c=1;x-c>=0&&y+c<12&&chessBoard[x-c,y+c]==3-player;c++);
if (c+b>=6) {winner=3-player; return true;}//数从左上斜向到右下的同色棋子,超过5就返回true
return false;
}//判断是否有一方已经获得了胜利
}
运行后效果如下:
通过unity脚本编写简单的五子棋游戏-效果展示