Python 入門指南 5.0
exercise2308.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 | # 從 exercise2306 引入 DiceUser from exercise2306 import DiceUser # 定義骰子遊戲類別 class DiceGame: def __init__(self, names, number): # 儲存玩家的屬性 self.players = [] # 依參數建立玩家 for i in range(len(names)): self.players.append(DiceUser(names[i])) # 設定骰子數量 self.number = number # 進行首次遊戲 self.playgame() # 進行遊戲 def playgame(self): # 暫存最高點數 max_points = 0 # 暫存擲出最高點數的玩家 max_player = None # 暫存所有擲出點數 all_points = [] # 替每名玩家擲骰子 for player in self.players: # 依據設定的骰子數量擲骰子 match self.number: case 1: player.roll1Dice() case 2: player.roll2Dice() case 3: player.roll3Dice() case 4: player.roll4Dice() # 收集骰子點數 all_points.append(player.total_points) # 判定是否為最大點數 if player.total_points > max_points: max_points = player.total_points max_player = player # 判定遊戲贏家或平手 if all_points.count(max_points) != 1: self.winner = "平手" else: self.winner = max_player.name # 執行部分 if __name__ == '__main__': # 玩家名稱 names = ["小明", "小美", "小黑", "小愛"] # 建立遊戲 game = DiceGame(names, 2) # 逐一印出玩家擲出點數 for player in game.players: print(player.name + str(player.total_points)) print() # 判定輸贏或平手 if game.winner == "平手": print("平手") else: print("贏家是" + game.winner) # 檔名: exercise2308.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 10 月 |