Python 入門指南 5.0

exercise2306.py

 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
# 從 exercise2303 引入 Dice
from exercise2303 import Dice
# 從 exercise2202 引入 higher
from exercise2202 import higher

# 定義骰子玩家類別
class DiceUser:
    def __init__(self, name):
        # 設定玩家名稱
        self.name = name
        # 設定骰子
        self.dice1 = None
        self.dice2 = None
        self.dice3 = None
        self.dice4 = None
        # 設定總點數
        self.total_points = 0
        # 設定擲出骰子數量
        self.dice_state = 0

    def __str__(self):
        return self.name

    # 擲出一顆骰子
    def roll1Dice(self):
        self.dice_state = 1
        self.dice1 = Dice()
        self.total_points = self.dice1.point

    # 擲出兩顆骰子
    def roll2Dice(self):
        self.dice_state = 2
        self.dice1 = Dice()
        self.dice2 = Dice()
        self.total_points = self.dice1.point + self.dice2.point

    # 擲出三顆骰子
    def roll3Dice(self):
        self.dice_state = 3
        self.dice1 = Dice()
        self.dice2 = Dice()
        self.dice3 = Dice()
        self.total_points = self.dice1.point + self.dice2.point + self.dice3.point

    # 擲出四顆骰子
    def roll4Dice(self):
        self.dice_state = 4
        self.dice1 = Dice()
        self.dice2 = Dice()
        self.dice3 = Dice()
        self.dice4 = Dice()
        self.total_points = self.dice1.point + self.dice2.point + self.dice3.point + self.dice4.point

# 執行部分
if __name__ == '__main__':
    # 建立第一個玩家
    player1 = DiceUser("莊家")
    player1.roll2Dice()
    print(player1.name + "擲骰子,擲出 " + str(player1.total_points) + " 點")
    # 建立第二個玩家
    player2 = DiceUser("玩家")
    player2.roll2Dice()
    print(player2.name + "擲骰子,擲出 " + str(player2.total_points) + " 點")
    # 判定輸贏
    if player1.total_points == player2.total_points:
        print("平手")
    else:
        if higher(player1.total_points, player2.total_points):
            print(player1.name + "贏")
        else:
            print(player2.name + "贏")

# 檔名: exercise2306.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 10 月

回到練習題目
上一頁 exercise2305.py
回 Python 入門指南 5.0 首頁
下一頁 exercise2307.py
回 Python 教材首頁
回程式語言教材首頁