0

所以基本上这就是我所拥有的;

print "***Welcome to Code Breaker***"

print "\n"

rounds = raw_input("How many rounds do you want to play (has to be a positive integer)? ")

while rounds.isdigit() == False or int(rounds) < 1:    
    rounds = raw_input("ERROR:How many turns do you want to play (has to be a positve integer)? ")

print "\n"

i = 0

while i < int(rounds):
    i = i + 1
    for i2 in range(2):
        if i2 == 0:
            player = 1
            breaker = 2
        else:
            player = 2
            breaker = 1

    print "Round" + str(i) + ":***Player " + str(player) + "'s turn to setup the game.***"

    print "Player " + str(breaker) + " look away PLEASE!"

    secret = raw_input("Type in the secret word, QUICKLY? ")

    while secret.isalpha() == False:
        secret = raw_input("ERROR: Type in the secret word (has to be letters): ")

    secret = secret.lower()
    print "\n"*100


    numberOfGuess = raw_input("How many guesses will you allow?(has to be a positive integer) ")

    while numberOfGuess.isdigit() == False or int(numberOfGuess) < 1:
        numberOfGuess = raw_input("ERROR:How many guesses will you allow? (has to be a positive integer) ")

    def maskWord(state, word, guess):
        state = list(state)
        for i in range(len(word)):
            if word[i] == guess:
                state[i] = guess
        return "".join(state)


    word = secret
    state = "*" * len(word)
    tries = 0
    print "Secret Word = " + state
    play = True

    while play:
        if tries == int(numberOfGuess): 
            print "Fail...";
            break
            play = False
        guess = raw_input("Guess a letter (a-z)? ")

        while guess.isalpha() == False or len(guess)!= 1:
            guess = raw_input("ERROR: Guess a letter (a-z)? ")

        guess = guess.lower()
        tries +=1
        state = maskWord(state, word, guess)
        print state
        if maskWord(state, word, guess) == word:  
            print "WIN, WIN!!"; 
            play = False


    print "\n" * 100

问题:在代码的猜测部分,我想设置它,因为用户不能两次猜测同一个字母。我知道你必须使用一个空列表并使用 .append 函数来存储数据。但是我已经尝试过了,并且以许多不同的方式它似乎不起作用。我不知道我在哪里做错了,如果有人能回答这个问题,那就太好了。我需要知道它会是什么样子,以及我应该将它放在我的代码中的什么位置。谢谢!

4

2 回答 2

1

我没有阅读所有代码,但查看您的问题,我认为您正在寻找类似的东西:

l = []

#build list

char = 'a'

if char in l:
    print('error')
else:
    l.append(char)
于 2013-07-12T03:10:01.483 回答
0

通常使用一组来跟踪此类事情。

used_letters = set()  # a new empty set
# ...
if guess in used_letters:  # test presence
  print "This letter has been used already!"
else:
  used_letters.add(guess) # remember as used

您可以使用list()and.append(guess)代替。使用列表,它的效率较低,但在您的情况下,效率低下是完全无法检测到的。

使用 a 的set目的是传达不应该存在重复字母的想法。(您知道,程序的阅读频率远高于编写频率。)

于 2013-07-12T03:12:36.577 回答