麻烦与True和if语句。

时间:2013-11-17 12:13:44

标签: python python-2.7

我在试图摆脱循环时遇到了麻烦。以下是代码的一部分:

def save():
    newFileName = raw_input("Please enter a name for your save file")
    saveFile = open(newFileName+".txt" , "w")
    saveFile.write(str(guessesRemaining) + "\n" + str(npegs) + "\n" + str(numberColours) + "\n" + str(coloursUsed) + "\n" + str(code))
    print "Game saved."


def validateInput():

    inputGuess = raw_input("Please enter your guess as letters: ")

    while True:
        if inputGuess == "save":
            save()
            validateInput()


        elif len(inputGuess) != npegs:
            inputGuess = raw_input("Please enter the same number of letters as pegs you chose to play with: ")
        else:

            wordList = list(inputGuess.upper())

            invalidLetters = False
            for letter in wordList:
                if letter not in coloursUsed:
                    invalidLetters = True

            if invalidLetters == True:
                print "Possible colours are", coloursUsed

            else:
                return wordList

基本上它是一个策划游戏,可以通过在文本文件中存储一些数据来保存。要保存,只需输入“save”即可运行保存功能。问题是,一旦我选择了文件名并保存,我希望能够继续玩游戏。但是,一旦保存它就会运行:

inputGuess = raw_input("Please enter your guess as letters" 

因为我被提示输入字母,但无论我输入什么,它只是要求我选择保存文件的名称然后再次保存。我怎样才能解决这个问题,以便继续比赛。

谢谢!

1 个答案:

答案 0 :(得分:1)

你在游戏中基于无限递归。你的验证也是错误的。对于这样一个混乱的代码,最好的办法是尝试对它进行分区,如下所示:

def takeAGuess(inputGuess):
    wordList = list(inputGuess.upper())

    invalidLetters = False
    for letter in wordList:
        if letter not in coloursUsed:
            invalidLetters = True

    if invalidLetters == True:
        print "Possible colours are", coloursUsed
        return None
    else:
        return wordList

def validateInput():
    inputGuess = raw_input("Please enter your guess as letters: ")

    if inputGuess == "save":
        save()
        return None
    elif len(inputGuess) != npegs:
        inputGuess = raw_input("Please enter the same number of letters as pegs you chose to play with: ")
        return takeAGuess(inputGuess)
    else:
        return takeAGuess(inputGuess)

while True:
    result = validateInput()
    # result is either None to continue playing, or a wordList
    # not sure what do you want to do with it