Python 入門指南 5.0

exercise2806.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
# 從 exercise2804 引入 DiceUser
from exercise2804 import DiceUser
# 從 exercise2805 引入 DiceGame
from exercise2805 import DiceGame
# 從 exercise2802 引入 examine_str_list
from exercise2802 import examine_str_list
# 從 exercise2802 引入 examine_int
from exercise2802 import examine_int
# 從 exercise2201 引入 ParameterError
from exercise2201 import ParameterError

# 進行遊戲的函數
def dice_game(names: list, number: int):
    # 檢查參數是否正確的型態
    if examine_str_list(names) and examine_int(number):
        # 建立遊戲
        game = DiceGame(names, number, 500, 100, 50)
        print("莊家是" + game.banker.name)
        # 設定狀態變數
        state = True
        # 遊戲的主迴圈
        while state:
            # 進行遊戲
            game.playgame()
            # 印出玩家下注
            for player in game.players:
                # 跳過莊家
                if player == game.banker:
                    continue
                print(player.name + "下注" + str(game.bet))
            # 逐一印出玩家擲出點數
            for player in game.players:
                print(player.name + "擲出" + str(player.total_points) + "點")
                # 跳過莊家
                if player == game.banker:
                    continue
                else:
                    # 重新分配賭注
                    if game.banker.total_points >= player.total_points:
                        game.banker.asset += 2 * game.bet
                    else:
                        print(player.name + "贏得" + str(game.bet))
                        player.asset += 2 * game.bet
            # 逐一印出玩家最後資產
            for player in game.players:
                print(player.name + "有 " + str(player.asset))
            # 檢測出局
            for player in game.players:
                if player.asset == 0:
                    print(player.name + "出局")
                    state = False
    else:
        raise ParameterError

# 執行部分
if __name__ == '__main__':
    try:
        # 玩家名稱
        names = ["小明", "小美", "小黑", "小愛"]
        # 進行遊戲
        dice_game(names, "2")
    except:
        print("遊戲建立過程中遭遇問題")

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

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