我一直在通过一个在线课程学习,我试图想出一些想法,我可以创造一些东西来“测试”我自己,所以我想出了一个石头剪刀游戏。它工作得很好,所以我决定尝试添加一种方法来跟踪你在电脑上的分数。进展不是很顺利。
这就是我所拥有的:
from random import randint
ai_score = 0
user_score = 0
def newgame():
print('New Game')
try:
while(1):
ai_guess = str(randint(1,3))
print('\n1) Rock \n2) Paper \n3) Scissors')
user_guess = input("Select An Option: ")
if(user_guess == '1'):
print('\nYou Selected Rock')
elif(user_guess == '2'):
print('\nYou Selected Paper')
elif(user_guess == '3'):
print('\nYou Selected Scissors')
else:
print('%s is not an option' % user_guess)
if(user_guess == ai_guess):
print('Draw - Please Try Again')
elif (user_guess == '1' and ai_guess == '2'):
print("AI Selected Paper")
print("Paper Beats Rock")
print("AI Wins!")
ai_score += 1
break
elif (user_guess == '1' and ai_guess == '3'):
print("AI Selected Scissors")
print("Rock Beats Scissors")
print("You Win!")
user_score += 1
break
elif (user_guess == '2' and ai_guess == '1'):
print("AI Selected Rock")
print("Paper Beats Rock")
print("You Win!")
user_score += 1
break
elif (user_guess == '2' and ai_guess == '3'):
print("AI Selected Scissors")
print("Scissors Beats Paper")
print("AI Wins!")
ai_score += 1
break
elif (user_guess == '3' and ai_guess == '1'):
print("AI Selected Rock")
print("Rock Beats Scissors")
print("AI Wins!")
ai_score += 1
break
elif (user_guess == '3' and ai_guess == '2'):
print("AI Selected Paper")
print("Scissors Beats Paper")
print("You Win!")
user_score += 1
break
else:
pass
break
except KeyboardInterrupt:
print("\nKeyboard Interrupt - Exiting...")
exit()
#1 = Rock, 2 = Paper, 3 = Scissors
def main():
while(1):
print("\n1) New Game \n2) View Score \n3) Exit")
try:
option = input("Select An Option: ")
if option == '1':
newgame()
if option == '2':
print("\nScores")
print("Your Score: " + str(user_score))
print("AI Score: " + str(ai_score))
elif option == '3':
print('\nExiting...')
break
else:
print('%s is not an option' % option)
except KeyboardInterrupt:
print("\nKeyboard Interrupt - Exiting...")
exit()
main()我在某处读到全局变量可以工作,但通常是不受欢迎的。不知道为什么,但是我不能说它们是=0,所以不能让它工作。将ai_score和user_score放入newgame()并不起作用,因为它会在您每次运行时将其设置为0。任何帮助都将不胜感激。
作为一个快速补充说明,第二个
else:
print('%s is not an option' % option)在main()中,似乎总是在执行,并且总是说"1不是一个选项“,我不知道为什么它会这样做。我假设与while循环有关,但我需要它们来保持它的运行,所以解释一下为什么和如何修复将是很好的。归根结底,我只是在这里学习更多。
发布于 2016-09-09 03:15:24
from random import randint
class newgame():
ai_score = 0
user_score = 0
def __init__(self):
self.ai_score = 0
self.user_score = 0
def playgame(self):
print('New Game')
try:
while(1):
ai_guess = str(randint(1,3))
print('\n1) Rock \n2) Paper \n3) Scissors')
user_guess = input("Select An Option: ")
if(user_guess == '1'):
print('\nYou Selected Rock')
elif(user_guess == '2'):
print('\nYou Selected Paper')
elif(user_guess == '3'):
print('\nYou Selected Scissors')
else:
print('%s is not an option' % user_guess)
if(user_guess == ai_guess):
print('Draw - Please Try Again')
elif (user_guess == '1' and ai_guess == '2'):
print("AI Selected Paper")
print("Paper Beats Rock")
print("AI Wins!")
self.ai_score += 1
break
elif (user_guess == '1' and ai_guess == '3'):
print("AI Selected Scissors")
print("Rock Beats Scissors")
print("You Win!")
self.user_score += 1
break
elif (user_guess == '2' and ai_guess == '1'):
print("AI Selected Rock")
print("Paper Beats Rock")
print("You Win!")
self.user_score += 1
break
elif (user_guess == '2' and ai_guess == '3'):
print("AI Selected Scissors")
print("Scissors Beats Paper")
print("AI Wins!")
self.ai_score += 1
break
elif (user_guess == '3' and ai_guess == '1'):
print("AI Selected Rock")
print("Rock Beats Scissors")
print("AI Wins!")
self.ai_score += 1
break
elif (user_guess == '3' and ai_guess == '2'):
print("AI Selected Paper")
print("Scissors Beats Paper")
print("You Win!")
self.user_score += 1
break
else:
pass
break
except KeyboardInterrupt:
print("\nKeyboard Interrupt - Exiting...")
exit()
#1 = Rock, 2 = Paper, 3 = Scissors
def main():
game_object = newgame()
while(1):
print("\n1) New Game \n2) View Score \n3) Exit")
try:
option = input("Select An Option: ")
if option == '1':
game_object.playgame()
elif option == '2':
print("\nScores")
print("Your Score: " + str(game_object.user_score))
print("AI Score: " + str(game_object.ai_score))
elif option == '3':
print('\nExiting...')
break
else:
print('%s is not an option' % option)
except KeyboardInterrupt:
print("\nKeyboard Interrupt - Exiting...")
exit()
main()课程很棒。__init__是该类的构造函数。它基本上使对象对类是即时的,并将变量设置为您想要的。game_object = newgame()生成类对象并将其存储到game_object中。为了获得game_object的类变量,我们使用game_object.ai_score。因为你创建了一个类对象,所以它的类变量仍然在你创建的对象的作用域中,即使它可能在你的函数之外。通常,如果我需要在函数外部使用变量,并且想要使用Global,我会改为创建一个类。有些情况下你不希望这样,但就我个人而言,我还没有遇到过这种情况。此外,您可能希望查看评论中有关使用字典作为选项的内容。还有其他问题吗?
编辑:
要回答你关于print('%s is not an option' % option)总是运行的新问题,是因为在你的代码中有if option == '1':,然后是if option == '2':,你希望选项2是elif。我在我的代码中修复了它。If语句在块中。因为您启动了一个新的if,所以else没有首先检查if,看看它是否是一个有效的选项。从某种意义上说,这超出了它的范围。既然你的代码基本上是说option等于1?它是否等于2或3或其他任何值?注意这是两个不同的问题?
发布于 2016-09-09 03:18:55
似乎变量option不是“1”,对吗?这是因为函数input返回的不是字符串,而是integer。您可以通过在此程序中添加一点跟踪来查看这一点。
print (option, type (option))在设置了变量选项的行后。
这将告诉您变量选项是什么类型,在这种情况下它是一个整数。因此,首先,您需要替换与字符串的比较(例如,将if option == '1':替换为与整数的比较,即:if option == 1:。
至于第二个问题:在函数内部声明或赋值的变量仅存在于该函数的作用域中。如果需要在具有外部作用域的函数内使用变量,则应该在函数内将其重新声明为global (即使它们“不受欢迎”--这是有充分理由的)。在def newgame():的开头,您需要再次声明全局变量:global ai_score, user_score。您还可以使用类来熟悉面向对象编程并编写更好的代码。这个程序中还有其他错误,但我相信您会发现的。
发布于 2016-09-09 03:08:33
至少有一个问题是这样的:你的main有if...if...elif...else。第二个if可能需要是一个elif。提示:当您遇到控制流问题时,将print语句放入每个控制分支中,打印出控制变量和其他可能相关的内容。这将告诉您哪个分支正在被采用--在本例中,哪个分支是复数。
你没有确切地说出记分的问题是什么,但我认为这是赋值前引用的变量的一个异常。如果是这样的话,你应该把“全局ai_score”放在函数的顶部。发生了什么,Python可以,但不喜欢,识别函数外部的变量,这些变量正在函数内部使用。你得稍微用力一点。考虑一下:
>>> bleem = 0
>>> def incrbleem():
... bleem += 1
...
>>> incrbleem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in incrbleem
UnboundLocalError: local variable 'bleem' referenced before assignment
>>> def incrbleem():
... global bleem
... bleem += 1
...
>>> bleem
0
>>> incrbleem()
>>> bleem
1顺便说一句,对于一个新手来说,你的代码一点也不差。我见过更多更糟的!无论如何,我不认为全局变量对于像这样一个小的、一次性的程序是不好的。一旦你有两个程序员,或者两个线程,或者两个月的工作时间间隔,全局变量肯定会带来问题。
https://stackoverflow.com/questions/39398378
复制相似问题