我寫了一個小程序來模擬紙,剪刀,搖滾遊戲。Python縮進For,While和Try
我正在使用for-loop來控制3的行爲,我正在使用while並嘗試控制用戶輸入。
我不相信python運行遊戲評估邏輯中的代碼,但我不太確定爲什麼。我認爲這可能與範圍/縮進有關,但我不確定?已經用完了想法!
如果有人能指出我以前的答案的方向,資源或幫助澄清我的代碼中的問題,我會非常感激。
# module packages
import random
def rockpaperscissor():
# data structures and primary variables
state = ["Rock", "Paper", "Scissor"]
user_points = []
computer_points = []
round_counter = 1
# game loop (best of three rounds)
for i in range(3):
print("Round " + str(round_counter) + ":")
computer_choice = random.choice(state)
# user input
while True:
try:
print("You: ", end='')
user_input = input().strip()
if user_input not in {"Rock", "rock", "Paper", "paper", "Scissor", "scissor"}:
raise Exception
except Exception:
print("You have not entered a valid choice. Please re-enter.")
else:
break
print("Computer: ", end='')
print(computer_choice + "\n")
# game evaluation logic
if user_input in {"Rock" or "rock"}:
if computer_choice == "Paper":
computer_points.append(1)
elif computer_choice == "Scissor":
user_points.append(1)
elif computer_choice == user_input:
computer_points.append(0)
user_points.append(0)
elif user_input in {"Paper" or "paper"}:
if computer_choice == "Rock":
print('test')
user_points.append(1)
elif computer_choice == "Scissor":
computer_points.append(1)
print('test')
elif computer_choice == user_input:
computer_points.append(0)
user_points.append(0)
print('test')
elif user_input in {"Scissor" or "scissor"}:
if computer_choice == "Paper":
user_points.append(1)
elif computer_choice == "Rock":
computer_points.append(1)
elif computer_choice == user_input:
computer_points.append(0)
user_points.append(0)
round_counter = round_counter + 1
print(user_points)
print(computer_points)
print("Your final score: ", end='')
print(sum(user_points))
print("The Computer's final score: ", end='')
print(sum(computer_points))
# outcome logic
if user_points < computer_points:
print("\nSorry, you lost! Better luck next time!")
elif user_points > computer_points:
print("\nCongratulations, you won!")
else:
print("\nYou drew with the computer!")
# repeat logic
print("\nDo you want to play again? Yes or No?")
play_again = input().strip()
print("\n")
if play_again in {"Yes", "yes"}:
rockpaperscissor()
elif play_again in {"No", "no"}:
print("Not a problem. Thanks for playing. Catch you next time!")
rockpaperscissor()
# end of code
最後一行不應縮進,例如。 – Andras
附註:爲什麼要設置一個*昂貴的*嘗試/除非你只打印一些信息。爲什麼不在'if'中打印消息,並使用簡單的'if/else'來打破'else'。 –
@Moses Koledoye ...因爲我是新來的Python我只是試圖練習一個嘗試/除了;是的,if/else可能更合適。 – PS94