gpt4 book ai didi

python - 石头、剪刀、布 - Python

转载 作者:行者123 更新时间:2023-11-30 22:58:28 26 4
gpt4 key购买 nike

我正在尝试完成类里面的石头、剪刀、布作业。

我收到“UnboundLocalError:赋值前引用的局部变量“绑定(bind)”” 错误。

有人可以告诉我为什么会收到此错误吗?

import random

user_score = 0
computer_score = 0
tied = 0

def main():
print ("Let's play the game of Rock, Paper, Scissors. ")

while True:
print ("Your current record is", user_score, "wins,", computer_score, "losses and", tied, "ties")

computer_choice = random.randint(1,3)
if computer_choice == 1:
computer_rock()
elif computer_choice == 2:
computer_paper()
else:
computer_scissors()

def computer_rock():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("Draw! You both chose Rock.")
tied += 1
try_again()
elif user_choice == "2":
print ("You Win! The computer chose Rock, while you picked Paper.")
user_score += 1
try_again()
elif user_choice == "3":
print ("You Lose! You chose scissors, while the computer picked Rock.")
computer_score += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_rock()

def computer_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("You Lose! You chose rock, while the computer picked Paper.")
computer_score += 1
try_again()
elif user_choice == "2":
print ("Draw! You both picked Paper.")
tied += 1
try_again()
elif user_choice == "3":
print ("You Win! The computer chose Paper, while you picked Scissors.")
user_score += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_paper()

def computer_scissors():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("You Win! You chose rock, while the computer picked Scissors.")
user_score += 1
try_again()
elif user_choice == "2":
print ("You Lose! The computer chose Scissors, while you picked Paper.")
computer_score += 1
try_again()
elif user_choice == "3":
print ("Draw! You both picked Scissors.")
tied += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_scissors()

def try_again():
choice = input("Play again? Yes or no. ")
if choice == "y" or choice == "Y" or choice == "yes" or choice == "Yes":
main()
elif choice == "n" or choice == "N" or choice == "no" or choice == "No":
print ("Thanks for playing. ")
else:
print ("Try again")
try_again()

main()

最佳答案

将以下代码添加为三个 computer_() 函数中每个函数的第一行应该可以解决您的问题。

global tied, user_score, computer_score

有更好的方法来完成您正在做的事情,但这应该可以帮助您克服困难:)

关于python - 石头、剪刀、布 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com