[英]python - Where do I check for valid input in my rock paper scissors game
當用戶輸入'r','p','s'之間的選擇時,我想檢查有效輸入我將如何 go 這樣做? 我把它放在我的代碼的什么地方?
我已經嘗試在開始時添加它,但它沒有用:
possible_choices = ["r", "p", "s"]
def play():
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
).lower
computer = random.choice(["r", "p", "s"])
if user not in possible_choices:
print('Uh oh! Please select a valid option', play())
整個代碼:
import random
game_loop = True
def play():
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
).lower
computer = random.choice(["r", "p", "s"])
if user == computer:
return f"Tie! Computer chose {computer}"
# r > s, s > p, p > r
if win_or_lose(user, computer):
return f"You won! Computer chose {computer}"
return f"You lost! Computer chose {computer}"
def win_or_lose(player, opponent):
if (
(player == "r" and opponent == "s")
or (player == "s" and opponent == "p")
or (player == "p" and opponent == "r")
):
return True
def play_again():
p_a = input("Play again? (y/n): ")
if p_a == "y":
print(play())
elif p_a == "n":
quit()
else:
print("oof! Please choose correct option: (y/n)")
play_again()
print(play())
while game_loop == True:
play_again()
我推薦一個while循環,實現如下:
def play():
choices = ['r','p','s']
while True:
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
).lower()
if user in choices:
break
else:
print('choose again')
continue
...
這個結構檢查輸入是否在選項列表中,如果不是,用戶再試一次。 還添加了 the.lower() 上的括號。
可以在此處找到有關此類事物的更多信息
回答:
def play():
choices = ["r", "p", "s"]
computer = random.choice(["r", "p", "s"])
while True:
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
)
if user in choices:
break
else:
print("Please choose a correct choice.")
continue
if user == computer:
return f"Tie! Computer chose {computer}"
# r > s, s > p, p > r
if win_or_lose(user, computer):
return f"You won! Computer chose {computer}"
return f"You lost! Computer chose {computer}"
def win_or_lose(player, opponent):
if (
(player == "r" and opponent == "s")
or (player == "s" and opponent == "p")
or (player == "p" and opponent == "r")
):
return True
def play_again():
while True:
p_a = input("Play again? (y/n): ")
if p_a == "y":
print(play())
elif p_a == "n":
quit()
else:
print("Please choose correct option..")
play_again()
print(play())
while True:
play_again()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.