C#面向對象編程-猜拳游戲,
1.需求
現在要制作一個游戲,玩家與計算機進行猜拳游戲,玩家出拳,計算機出拳,計算機自動判斷輸贏。
2.需求分析
根據需求,來分析一下對象,可分析出:玩家對象(Player)、計算機對象(Computer)、裁判對象(Judge)。 玩家出拳由用戶控制,使用數字代表:1石頭、2剪子、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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class Player
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int ShowFist()
{
Console.WriteLine("請問,你要出什麼拳? 1.剪刀 2.石頭 3.布");
int result = ReadInt(1, 3);
string fist = IntToFist(result);
Console.WriteLine("玩家:{0}出了1個{1}", name, fist);
return result;
}
private string IntToFist(int input)
{
string result = string.Empty;
switch (input)
{
case 1:
result = "剪刀";
break;
case 2:
result = "石頭";
break;
case 3:
result = "布";
break;
}
return result;
}
private int ReadInt(int min,int max)
{
while (true)
{
string str = Console.ReadLine();
int result;
if (int.TryParse(str, out result))
{
if (result >= min && result <= max)
{
return result;
}
else
{
Console.WriteLine("請輸入1個{0}-{1}范圍的數", min, max);
continue;
}
}
else
{
Console.WriteLine("請輸入整數");
}
}
}
}
計算機類示例代碼
?
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
class Computer
{
Random ran = new Random();
public int ShowFist()
{
int result = ran.Next(1, 4);
Console.WriteLine("計算機出了:{0}", IntToFist(result));
return result;
}
private string IntToFist(int input)
{
string result = string.Empty;
switch (input)
{
case 1:
result = "剪刀";
break;
case 2:
result = "石頭";
break;
case 3:
result = "布";
break;
}
return result;
}
}
裁判類示例代碼 這個類通過一個特殊的方式來判定結果
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Judge
{
public void Determine(int p1, int p2)
{
if (p1 - p2 == -2 || p1 - p2 == 1)
{
Console.WriteLine("玩家勝利!");
}
else if (p1 == p2)
{
Console.WriteLine("平局");
}
else
{
Console.WriteLine("玩家失敗!");
}
}
}
4.對象的實現
?
1
2
3
4
5
6
7
8
9
10
11
12
13
static void Main(string[] args)
{
Player p1 = new Player() { Name="Tony"};
Computer c1 = new Computer();
Judge j1 = new Judge();
while (true)
{
int res1 = p1.ShowFist();
int res2 = c1.ShowFist();
j1.Determine(res1, res2);
Console.ReadKey();
}
}