Python 入門指南 5.0
exercise2501.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 86 87 88 89 90 91 92 | # 從 exercise2303 引入 Dice from exercise2303 import Dice # 從 exercise2202 引入 higher from exercise2202 import higher # 定義骰子玩家類別 class DiceUser: def __init__(self, name, asset): # 設定玩家名稱 self.name = name # 設定玩家資產 self.asset = asset # 設定骰子 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, bet): self.dice_state = 1 self.dice1 = Dice() self.total_points = self.dice1.point self.asset -= bet # 擲出兩顆骰子 def roll2Dice(self, bet): self.dice_state = 2 self.dice1 = Dice() self.dice2 = Dice() self.total_points = self.dice1.point + self.dice2.point self.asset -= bet # 擲出三顆骰子 def roll3Dice(self, bet): 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 self.asset -= bet # 擲出四顆骰子 def roll4Dice(self, bet): 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 self.asset -= bet # 執行部分 if __name__ == '__main__': # 固定賭注 bet = 10 # 建立第一個玩家 player1 = DiceUser("莊家", 100) player1.roll2Dice(bet) print(player1.name + "擲骰子,擲出 " + str(player1.total_points) + " 點") # 建立第二個玩家 player2 = DiceUser("玩家", 100) player2.roll2Dice(bet) print(player2.name + "擲骰子,擲出 " + str(player2.total_points) + " 點") # 判定輸贏 if player1.total_points == player2.total_points: player1.asset += bet player2.asset += bet print("平手") else: if higher(player1.total_points, player2.total_points): player1.asset += bet * 2 print(player1.name + "贏") else: player2.asset += bet * 2 print(player2.name + "贏") # 印出玩家最後資產 print(player1.name + "有" + str(player1.asset)) print(player2.name + "有" + str(player2.asset)) # 檔名: exercise2501.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 10 月 |