Jiahonzheng's Blog

Unity 简单井字棋游戏

字数统计: 330阅读时长: 1 min
2019/09/09 Share

项目地址:github.com/Jiahonzheng/Unity-3D-Learning

UI 实现

1
2


逻辑实现

游戏状态

1
2
3
4
5
6
7
public enum Player { Unfinished, Tie, First, Second };
// When it is true, it means the game is still continuing.
protected bool playing = true;
// When it is true, it means Player1 go first.
protected bool turn = true;
// It stores the players' move.∏
protected readonly Player[,] history = new Player[3, 3];

胜负判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public Player CheckWin()
{
// Row Check
for (int i = 0; i < 3; ++i)
{
if (history[i, 0] != Player.Unfinished &&
history[i, 0] == history[i, 1] &&
history[i, 1] == history[i, 2])
{
playing = false;
return history[i, 0];
}
}
// Column Check
for (int j = 0; j < 3; ++j)
{
if (history[0, j] != Player.Unfinished &&
history[0, j] == history[1, j] &&
history[1, j] == history[2, j])
{
playing = false;
return history[0, j];
}
}
// Cross-Line Check
if (history[1, 1] != Player.Unfinished)
{
if (history[1, 1] == history[0, 0] && history[1, 1] == history[2, 2] ||
history[1, 1] == history[0, 2] && history[1, 1] == history[2, 0])
{
playing = false;
return history[1, 1];
}
}
// Check if it is a tie.
var numOfUnfinished = 0;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if (history[i, j] == Player.Unfinished)
{
numOfUnfinished++;
}
}
}
if (numOfUnfinished == 0)
{
playing = false;
return Player.Tie;
}
return Player.Unfinished;
}

重置

修改 OnGUI 的 Reset 按钮的绘制逻辑如下。

1
2
3
4
5
6
// Render "Reset" button.
if (GUI.Button(new Rect(buttonBaseX - 100, buttonBaseY, buttonWidth, buttonHeight), "Reset"))
{
OnPressResetButton();
return;
}

我们监测 Reset 按钮是否被用户触发,如果被触发,则调用 OnPressResetButton 方法。

1
2
3
4
void OnPressResetButton()
{
mechanics.Reset();
}
CATALOG
  1. 1. UI 实现
  2. 2. 逻辑实现
    1. 2.1. 游戏状态
    2. 2.2. 胜负判断
    3. 2.3. 重置