0

我必须编写一个代码,我需要创建一个让用户猜测方程式的游戏。每次猜测结束后,我必须显示用户猜到了多少方程式。例如,如果等式是 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

在调用函数时以任何方式更改此代码,我要么得到错误,要么不使用之前的猜测。我不知道该怎么做。

4

1 回答 1

0

我知道这不会直接解决您的问题,但我会回到那个问题上。

我强烈建议写出完成目标所需的逻辑。在纸上做这件事,并随意在相关内容、实现目标所需的标准以及程序的整个想法之间做出箭头。

这样做将有助于阐明您想要解决的实际问题是什么,以及如何去做。

所以你的第一个问题是,你想做什么?

看来您想创建一个类似刽子手的游戏,但使用论坛而不是信件。

第二件事,您要跟踪用户的进度——无论是在成就方面,还是在失败方面。

输赢取决于第二部分,所以这告诉我们一些事情。

有几种方法可以做到这一点,但一种简单的方法是使用 while 循环。

为什么是一个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 #游戏失败等

对于您的实际问题,您似乎想知道闭包。使用闭包可能对您有益,因此请随时阅读它们并决定情况是否需要它们。

最后,我强烈建议您尝试找出您遇到的问题。从这里,您可以大大节省时间和精力来找出解决问题的正确方法。

于 2014-11-30T05:13:28.827 回答