#20250407 我寫的底下有二個版本,改善跟OOP版
import random
g=["","石頭","剪刀","布"]
game_end=0
win_count=0
try:
while game_end<3:
i=int(input(">1,石頭 2.剪刀 3.布 "))
j=random.randint(1,3)
# print(f' you {g[i]}, computer {g[j]}')
if j==i:
print(f' you {g[i]}, computer {g[j]} 平手再一次')
continue
if (i==1 and j==2) or (i==2 and j==3) or (i==3 and j==1):
print(f' you {g[i]}, computer {g[j]} you 贏')
win_count+=1
else:
print(f' you {g[i]}, computer {g[j]} you 輸')
game_end+=1
print("you 總共 贏 了 %d次"%win_count,end=" ")
if win_count>=2:
print("挑戰成功")
else:
print("挑戰失敗")
except :
print("Error")
# 2025/04/07-改善版本
import random
choices = ["", "石頭", "剪刀", "布"] # index 1~3 對應輸入
rounds_played = 0
win_count = 0
print("=== 剪刀石頭布遊戲:三戰兩勝 ===")
try:
while rounds_played < 3:
user_input = input("> 請輸入 1.石頭 2.剪刀 3.布:")
if not user_input.isdigit():
print("⚠️ 請輸入數字 1~3!")
continue
user = int(user_input)
if user not in [1, 2, 3]:
print("⚠️ 請輸入有效選項(1, 2, 3)")
continue
computer = random.randint(1, 3)
print(f"你出 {choices[user]},電腦出 {choices[computer]}")
if user == computer:
print("🤝 平手,再來一次!")
continue
# 玩家勝利的三種情況
win = (user == 1 and computer == 2) or \
(user == 2 and computer == 3) or \
(user == 3 and computer == 1)
if win:
print("🎉 你贏了!")
win_count += 1
else:
print("😢 你輸了。")
rounds_played += 1
print(f"\n🏁 總共贏了 {win_count} 次!", end=" ")
if win_count >= 2:
print("✅ 挑戰成功!")
else:
print("❌ 挑戰失敗,再接再厲!")
except Exception as e:
print("⚠️ 發生錯誤:", e)
# 2025/04/07-OOP版
import random
class RPSGame:
def __init__(self):
self.choices = ["", "石頭", "剪刀", "布"] # 1~3 對應
self.rounds_played = 0
self.win_count = 0
self.max_rounds = 3
def get_user_choice(self):
try:
user_input = input("> 請輸入 1.石頭 2.剪刀 3.布:")
if user_input.isdigit():
choice = int(user_input)
if 1 <= choice <= 3:
return choice
print("⚠️ 請輸入有效數字(1~3)!")
return None
except:
return None
def play_round(self):
user = self.get_user_choice()
if user is None:
return False # 輸入錯誤,不進行這回合
computer = random.randint(1, 3)
print(f"你出 {self.choices[user]},電腦出 {self.choices[computer]}")
if user == computer:
print("🤝 平手,再來一次!")
return False # 不算一回合
win = (user == 1 and computer == 2) or \
(user == 2 and computer == 3) or \
(user == 3 and computer == 1)
if win:
print("🎉 你贏了!")
self.win_count += 1
else:
print("😢 你輸了。")
self.rounds_played += 1
return True
def show_result(self):
print(f"\n🏁 總共贏了 {self.win_count} 次!", end=" ")
if self.win_count >= 2:
print("✅ 挑戰成功!")
else:
print("❌ 挑戰失敗,再接再厲!")
def start(self):
print("=== 剪刀石頭布遊戲(物件導向版) ===")
while self.rounds_played < self.max_rounds:
self.play_round()
self.show_result()
# 程式入口
if __name__ == "__main__":
game = RPSGame()
game.start()