我必须编写一个代码,在其中创建需要让用户猜测方程式的游戏。每次猜测结束后,我必须显示用户已经猜测了多少方程式。例如,如果方程式为1 + 2 * 3 + 4,并且用户猜测方程式为3,则程序会说您的猜测是正确的,到目前为止,您猜测的方程式是---- 3-(破折号代表如果用户猜出2个下一个方程,则我需要他们到目前为止已经猜到的方程是2-3个,但是我无法让它们累加。
我正在使用的功能是
def guessing1():
'''
the player is asked to make a guess and the result is printed
'''
wrongguesses=0
if (guess1 in randomFormula):
print "Your guess is correct!"
wrongguesses=0
else:
print "Your guess is wrong!"
wrongguesses +=1
if (wrongguesses== max_guesses):
print "Sorry, you've reached the maximum number of wrong guesses."
print "Better luck next time!"
playagain=raw_input("Do you want to play again? y-yes, n-no: ")
if (playagain== n):
print "The game is over."
def formSoFar1():
a=''
for i in range (len(randomFormula)):
if (randomFormula[i] == guess1):
a += randomFormula[i]
else:
a+= "-"
print "The formula you have guessed so far is: ",a
我在调用函数时更改此代码的任何方式,都会得到一个错误或者它没有使用之前的猜测。我不确定该怎么做。
我知道这不会直接解决您的问题,但是我会回头再说。
我强烈建议写出完成目标所需的逻辑。在纸上进行此操作,可以随时使箭头指向相关内容,实现目标所需的标准以及程序的整体思想之间的实质。
这样做将有助于您弄清您要解决的实际问题以及如何去做。
因此,您的第一个问题是,您想做什么?
看来您想创建一个类似游戏的子手,但要使用论坛而不是字母。
第二件事,您想跟踪用户的进度-成就和失败。
输赢取决于第二部分,所以这告诉了我们一些东西。
有几种方法可以执行此操作,但是一种简单的方法是使用while循环。
为什么要循环一会儿?它使您可以在多次执行任务时检查条件。
您要检查用户尚未赢得或失去的条件。所以这样的事情
user_strikes = 0
formula = "1+2*3+4"
user_progress = "" # this will be updated
while game_over is False and user_strikes < STRIKES_ALLOWED:
# output "make a guess" or something
if guess in answer:
# update user_progress
# perhaps check if user_progress is equal to the formula, then set game_over to True if it is.
else:
# update user_strikes. Check here if it's equal to STRIKES_ALLOWED and output a message, since the while loop will end after that iteration.
# here you can check if game_over is True (user won), if strikes is equal to STRIKES_ALLOWED, and do logic based on that
# there are quite a few ways to do this.
要记住的其他事项:记录用户已经猜到的数字,符号等。如果他们一遍又一遍地猜出2,则可以打印出“已经猜中”或类似的内容。不必检查涉及游戏状态的多个变量,您可以仅使用一个设置为数字的变量。检查该数字的值,然后根据该数字执行操作。所以game_state = 1#游戏获胜;game_state = 2#游戏失败,依此类推。
对于您的实际问题,似乎您想知道闭包。使用闭包可能对您有益,因此请随时阅读它们,并确定情况是否需要它们。
最后,我强烈建议您尝试找出您遇到的问题。从这里,您可以极大地节省时间和精力,以找出解决问题的正确方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句