Python 入門指南 5.0
exercise2504.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 78 79 80 81 82 83 84 85 | # 從 exercise2503 引入 DiceUser from exercise2503 import DiceUser # 定義骰子遊戲類別 class DiceGame: def __init__(self, names, number, b_asset, p_asset, bet): # 儲存玩家的屬性 self.players = [] # 依參數建立玩家 for i in range(len(names)): self.players.append(DiceUser(names[i], p_asset)) # 設定第一個玩家為莊家 self.banker = self.players[0] # 設定莊家資產 self.banker.asset = b_asset # 設定骰子數量 self.number = number # 設定賭注 self.bet = bet # 進行遊戲 def playgame(self): # 替每名玩家擲骰子 for player in self.players: # 依據設定的骰子數量擲骰子 match self.number: case 1: player.roll1Dice() case 2: player.roll2Dice() case 3: player.roll3Dice() case 4: player.roll4Dice() # 建立贏家屬性 self.winner = [] for player in self.players: # 跳過莊家 if player == self.banker: continue # 玩家下注 player.asset -= self.bet self.banker.asset -= self.bet # 判定玩家輸贏 if self.banker.total_points >= player.total_points: self.winner.append(1) else: self.winner.append(0) # 執行部分 if __name__ == '__main__': # 玩家名稱 names = ["小明", "小美", "小黑", "小愛"] # 建立遊戲 game = DiceGame(names, 2, 500, 100, 50) game.playgame() print("莊家是" + game.banker.name) # 印出玩家下注 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)) # 檔名: exercise2504.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 10 月 |