0

我正在用 Python 为 GCSE 计算任务制作一个刽子手游戏,我所要做的就是确保当有人输入正确的字母时,它将把它放在单词中的正确位置。代码如下:

def guess_part(word):
    lives = 6
    LetterCount = 0
    LetterMask = ""
    for x in range(len(word)): #run for loop for the amount of the length of word
        LetterMask = LetterMask + "*"
    print LetterMask
    while lives != 0 and LetterMask.find("*")!=-1: #while lives are not 0 and the amount of asterisks are not -1
        LetterGuess = raw_input("Enter a letter to guess?")
        LetterCount = 0
        for char in word:
            LetterCount = LetterCount + 1
        if LetterGuess not in word:
            lives = lives - 1
        else:
            if LetterGuess in word and lives != 0:
                print "Good Guess."
                LetterMask = list(LetterMask)
                LetterMask[LetterCount-1] = LetterGuess
                LetterMask = "".join(LetterMask)
                print LetterMask
            else:
                print "Incorrect."
    if lives == 0:
        print "You have ran out of lives, your word was: ", word
    else:
        print "You have correctly guess the word! Score: ", lives
        print "Play again?"
        again = raw_input("")
        again.lower()
        if again == "y":
            menu()
        elif again == "n":
            exit()
        else:
            exit()


def rand_word():
    from random import randrange
    random_words = ['extraordinary','happy','computer','python','screen','cheese','cabaret','caravan','bee','wasp','insect','mitosis','electronegativity','jumper','trousers']
    word = random_words[randrange(0, 15)] #pick a random number, and use this number as an index for the list, "random_words".
    guess_part(word) #call the function, "guess_part" with the parameter "word"

def user_word():
    print "All words will be changed to lowercase."
    print "Enter the word you would like to guess."
    print ""
    validation_input = False
    while validation_input == False: #while the validation input is not False, do below.
        word = raw_input("")
        if word.isalpha(): #If word contains only strings, no numbers or symbols, do below.
            word = word.lower() #set the string of variable, "word", to all lowercase letters.
            guess_part(word) #call the function, "guess_part" with the parameter, "word".
            validation_input = True #Break the while loop
        else:
            print "Word either contained numbers or symbols."

def menu():
    print "Hangman Game"
    print ""
    print "Ashley Collinge"
    print ""
    print "You will have 6 lives. Everytime you incorrectly guess a word, you will lose a life."
    print "The score at the end of the game, is used to determine the winner."
    print ""
    print "Would you like to use a randomly generated word, or input your own?"
    print "Enter 'R' for randomly generated word, or 'I' for your own input."
    decision_bool = False
    decision_length = False
    while decision_bool == False: #While decision_bool equals "False", do below.
        while decision_length == False: #While decision_length equals "False", do below.
            decision = raw_input("")
            if len(decision) == 1: #If the length of decision eqausl 1, do below.
                decision_length = True
                decision = decision.capitalize() #Capitalize the string value of decision.
                if decision == "R": #if the value of decision, eqauls "R".
                    print "You chose randomly generated word."
                    print ""
                    print "Forwarding..."
                    decision_bool = True
                    print ""
                    rand_word() #Call the function, rand_word()
                elif decision =="I": #If decision equals "I", do below.
                    print "You chose to input your own word."
                    print ""
                    print "Forwarding..."
                    decision_bool = True
                    print ""
                    user_word() #Call the function, user_word()
                else:
                    print "You entered an incorrect value for the question. Try again."
            else:
                print "You entered an incorrect value for the question. Try again."

menu()
4

1 回答 1

0

下面的代码可能会回答您的问题:
“我所要做的就是确保当有人
输入正确的字母时,它将把它放在单词中的正确位置。”
它不验证输入。
提示:如果您验证,我建议您查看re模块
由于print声明,如果您使用 python 3+,此代码将不起作用:

from random import choice

def found(s , v):  
    # returns a list of indexes if v is in s
    # else it returns None
    return [i for i in range(len(s))if s[i] == v]

def guess_word(word, mask, lives):  

    # returns a 2 tuple : lettermask and the lives left
    # just like  'guess_part' but with 2 more para's  
    # to increase flexibility.
    # Beware !!! this function does not check the para's

    lettermask=list(len(word)* mask)
    livesleft ='You have {} lives left .\n'
    guess='Plz type a char a-z.\n>:'
    print word # just for checking
    while mask in lettermask:   
        if lives < 1: break
        print 'lettermask= '+ ''.join(lettermask)
        p = livesleft.format(lives)
        letterguess= raw_input(p + guess)
        print 'letterguess= '+ letterguess
        result = found( word, letterguess)
        if result:  
            print 'Good guess :) '
            for i in result :
                lettermask[i]=word[i]
        else:   
            print 'Wrong guess :( '
            lives-=1
    return lettermask,lives

random_words = ['extraordinary','happy','computer',
'python','screen','cheese','cabaret',
'caravan','bee','wasp','insect','mitosis',
'electronegativity','jumper','trousers']


word=choice (random_words)
# or word= raw_intput('pls type a word')
mask='*'
lives= 6
resultS,lives = guess_word(word, mask, lives)
if mask in resultS:  
   print 'Your result: {}'.format("".join(resultS))
   print 'You have failed,the word was: {}'.format(word)
else:
   print 'Congrats !!! Your score is: {}'.format(lives)
于 2013-02-04T12:43:54.303 回答