石頭剪刀布的遊戲規則:
1.玩家是輸入,電腦是隨機數
2.通過if語句進行判斷
3.當輸入字符串和浮點數時,報錯。循環執行。
import random
class Game(object):
def __init__(self, name, player, computer):
self.name = name
self.player = player
self.computer = computer
def Game(self):
if (self.player == 1 and self.computer == 2) or (self.player == 2 and self.computer == 3) or (self.player == 3 and self.computer == 1):
print(f"玩家{self.name}出{self.player},電腦出{self.computer}。玩家贏了。")
elif self.player == self.computer:
print(f"雙方出的均是{self.player},平局。")
elif (self.player == 3 and self.computer == 2) or (self.player == 1 and self.computer == 3) or (self.player == 2 and self.computer == 1):
print(f"玩家“{self.name}”出{self.player},電腦出{self.computer}。玩家輸了。")
else:
print("輸入錯誤,只能輸入1 2 3!")
while True:
try:
name = input("請輸入您的名字:")
player1 = int(input("請輸入對應的數字,1(石頭)、2(剪刀)、3(布):"))
computer1 = random.randint(1,3)
PlayGame = Game(name, player1, computer1).Game()
break
except ValueError:
print("輸入錯誤,只能輸入1 2 3!")
print("-" *30)
運行結果:
請輸入您的名字:王怕怕
請輸入對應的數字,1(石頭)、2(剪刀)、3(布):王怕怕
輸入錯誤,只能輸入1 2 3!
------------------------------
請輸入您的名字:王怕怕
請輸入對應的數字,1(石頭)、2(剪刀)、3(布):2
雙方出的均是2,平局。