猜字游戏代码

0 投票
4 回答
5747 浏览
提问于 2025-04-18 04:53

我想请教一下关于“刽子手”游戏的问题。我写了一段代码,花了很多时间在改进它,但还是无法得到正确的输出。非常感谢大家的帮助!

word = choose_word(wordlist)
letters = 'abcdefghijklmnopqrstuvwxyz'
numLetters = len(word)
print numLetters

import re


def hangman(word, numLetters):
    print 'Welcome to the game, Hangman!'
    print 'I am thinking of a word that is', numLetters, 'letters long'
    remainingGuesses = 8 
    print 'You have', remainingGuesses, 'guesses left.'
    letters = 'abcdefghijklmnopqrstuvwxyz'
    print 'Available letters:', letters
    guess = raw_input("Please guess a letter:")

    def filled_word(wordy, guessy):
        emptyWord = ['_']*numLetters
        if wordy.find(guessy) != -1:
            position = [m.start() for m in re.finditer(guessy, wordy)]
            for x in position:
                emptyWord[x] = guessy
            strWord = ''.join(emptyWord)
            print 'Good guess =', strWord


        else:
            strWord = ''.join(emptyWord)
            print 'Oops! That letter is not in my word:', strWord

    filled_word(word, guess)
    emptyWord =  ['_']*numLetters
    print 'emptyWord =', ['_']*numLetters

    while '_' in emptyWord and remainingGuesses>0:
        remainingGuesses -= 1
        print 'You have', remainingGuesses, 'guesses left'
        letters = 'abcdefghijklmnopqrstuvwxyz'

        def unused_letters(letters):
            letters = 'abcdefghijklmnopqrstuvwxyz'
            unusedLetters = str(list(letters).remove(guess))
            letters = unusedLetters
            return unusedLetters

        letters =  unused_letters(letters)
        print 'Available letters:', letters
        guess = raw_input("Please guess a letter:")

        if word.find(guess) != -1:
            position = [m.start() for m in re.finditer(guess, word)]
            for x in position:
                emptyWord[x] = guess
                strWord = ''.join(emptyWord)
                print 'Good guess ='+strWord
                emptyWord = list(strWord)

        else:
            strWord = ''.join(emptyWord)
            print 'Oops! That letter is not in my word:', strWord


print hangman(word, numLetters)
print '___________'
print 'Congratulations, you won!'

问题是,当我运行这段代码时,前面的猜测都没问题,但从第二次猜测开始,我看到的却是Available letters = None,而不是具体的字母。

而且我猜的字母如果在单词中出现了,也没有被记录下来。比如在第一次猜测时,代码返回的单词是'd____',但在第二次猜测'e'时,代码返回的是e_,而不是'd_e__'。这是不是和变量的赋值有关?比如局部变量和全局变量?我对此有点困惑。

非常感谢大家的帮助!谢谢! :)

4 个回答

0

你可以从我的程序中获取一些灵感。先运行一下它。

import random
# Starter code start
# The variable word is a random word from the text file 'words.txt'
words = list()
with open("words.txt") as f:
    for line in f:
        words.append(line.lower())

word = random.choice(words).strip().upper()
# This is the starter code that chooses a word
# Starter code end
letter = ''
# This is the input of letters the user will type in over and over
word_index = 0
# This is the index for the input correct word to be checked against the correct letters
correct_letters = ''
# This is the variable for the correct letters as a list, once the user types them in and they are deemed correct
correct_letters_index = 0
# This is the index to print the correct letters from, in a while statement below. This gets reset to 0 after every time the letters are printed
incorrect_letters = ''
# This is the variable to hold the incorrect letters in.
lives = 6  # ♥
#  is the variable to hold the 6 lives, printed as hearts in
win_user = 0
# This is the variable that determines if the user wins or not
guessed_letters = ''
# this variable checks for repeated letters (incorrect + correct ones)
while win_user != len(word) and lives != 0:  # 1 mean yes the user have win

    if lives == 6:
        print(
        '''
        |--------------------|
        |                    |
        |                  
        |                 
        |                
        |                
        |                  
        |                 
        |                  
        |                   
        |                    
        |                    
        |                  
        |                 
        |                
        |_________________________________________
        '''
        )
    elif lives == 5:
        print(
        '''
        |--------------------|
        |                    |
        |                  **|**
        |                 * ()() *
        |                **  ▼   **
        |                ** (---) **
        |                  *****
        |                 
        |                  
        |                   
        |                    
        |                    
        |                  
        |                 
        |                
        |_________________________________________

        '''
        )
    elif lives == 4:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                    |   
            |                    |  
            |                    |
            |                    
            |                    
            |                  
            |                 
            |                
            |_________________________________________

            '''
        )
    elif lives == 3:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                 \  |   
            |                  \ |  
            |                   \|
            |                    
            |                    
            |                  
            |                 
            |                
            |_________________________________________

            '''
        )
    elif lives == 2:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                 \  |  / 
            |                  \ | / 
            |                   \|/
            |                    
            |                    
            |                  
            |                 
            |                
            |_________________________________________

            '''
        )

    elif lives == 1:
        print(
            '''
            |--------------------|
            |                    |
            |                  **|**
            |                 * ()() *
            |                **  ▼   **
            |                ** (---) **
            |                  *****
            |                 \  |  / 
            |                  \ | / 
            |                   \|/
            |                    |
            |                    |
            |                   /
            |                 /
            |               /
            |_________________________________________

            '''
        )

    # This is the while loop that prints only if the player has remaining lives and has not won yet; It prints the ascii drawing for the hangman with the body parts
    print("Remaining lives:", end=' ')
    for left_lives in range(lives):
        print("♥", end=' ')  # This prints the remaining lives as hearts

    print()

    # labels all correct letters like: cake into _ _ _ _
    while word_index != (len(word)) and word_index <= (len(word) - 1):
        while correct_letters_index != (len(correct_letters)) and word_index <= (len(word) - 1):
            if word[word_index] != correct_letters[correct_letters_index]:
                correct_letters_index += 1
            elif word[word_index] == correct_letters[correct_letters_index]:
                print(word[word_index], end=' ')
                word_index += 1
                correct_letters_index = 0
        if word_index <= (len(word) - 1):
            print("__", end=' ')
            correct_letters_index = 0
            word_index += 1
    print()

    # This goes through the correct word, and prints out the correct letters that have been typed in, in order
    # It also types out the blank spaces for letters

    if win_user != len(word):
        # This asks the user for another letter, and sets the checking value on the correct word back to 0 for the next run through
        letter = str(input("Enter a letter: ")).upper()

        if letter in guessed_letters:
            print("The letter had already been guessed: " + str(letter))

        if letter not in guessed_letters:
            if letter not in word:
                incorrect_letters += letter
                guessed_letters += incorrect_letters
                lives -= 1
            elif letter in word:
                correct_letters += letter
                guessed_letters += correct_letters
                for user_word in word:
                    if letter in user_word:
                        win_user += 1
        # This takes in the letter if it has not previously been deemed in a variable, either correct or not.
        # It also checks if the letter is correct, or not, and adds it to the variable
        # If the letter has already been typed, it will also let the user know that

    word_index = 0

if lives == 0:
    print(
        '''
        |--------------------|
        |                    |
        |                  **|**
        |                 * ()() *
        |                **  ▼   **
        |                ** (---) **
        |                  *****
        |                 \  |  / 
        |                  \ | / 
        |                   \|/
        |                    |
        |                    |
        |                   /  \\
        |                 /     \\
        |               /        \\
        |_________________________________________

        '''
    )
    # This prints the full hangman, and that the user loses if their lives reach 0
    print("User Looses !!")
    print("Incorrect letters typed: " + str(incorrect_letters))
    print("The word is: " + str(word))

elif win_user == len(word):
    print("The word is: " + str(word))
    # This prints the user wins if all characters are printed out for the correct word
    print("Incorrect letters typed: " + str(incorrect_letters))
    print("User Wins !")
    print(
        '''
        ☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
        ☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
        '''
    )
0
    if user_choice_1 == '1':
        print "Loading nooses, murderers, rapists, thiefs, lunatics..."
        self.start_game()
    elif user_choice_1 == '2':
        print "Bye bye now..."
        exit()
    else:
        print "I'm sorry, I'm hard of hearing, could you repeat that?"
        self.__init__()

def start_game(self):
    print "A crowd begins to gather, they can't wait to see some real"
    print "justice. There's just one thing, you aren't a real criminal."
    print "No, no. You're the wrong time, wrong place type. You may think"
    print "you're dead, but it's not like that at all. Yes, yes. You've"
    print "got a chance to live. All you've gotta do is guess the right"
    print "words and you can live to see another day. But don't get so"
    print "happy yet. If you make 6 wrong guess, YOU'RE TOAST! VAMANOS!"
    self.core_game()

def core_game(self):
    guesses = 0
    letters_used = ""
    the_word = "pizza"
    progress = ["?", "?", "?", "?", "?"]

    while guesses < 6:
        guess = raw_input("Guess a letter ->")

        if guess in the_word and not in letters_used:
            print "As it turns out, your guess was RIGHT!"
            letters_used += "," + guess
            self.hangman_graphic(guesses)
            print "Progress: " + self.progress_updater(guess, the_word, progress)
            print "Letter used: " + letters_used
        elif guess not in the_word and not(in letters_used):
            guesses += 1
            print "Things aren't looking so good, that guess was WRONG!" 
            print "Oh man, that crowd is getting happy, I thought you"
            print "wanted to make them mad?"
            letters_used += "," + guess
            self.hangman_graphic(guesses)
            print "Progress: " + "".join(progress)
            print "Letter used: " + letters_used
        else:
            print "That's the wrong letter, you wanna be out here all day?"
            print "Try again!"



def hangman_graphic(self, guesses):
    if guesses == 0:
        print "________      "
        print "|      |      "
        print "|             "
        print "|             "
        print "|             "
        print "|             "
    elif guesses == 1:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|             "
        print "|             "
        print "|             "
    elif guesses == 2:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /       "
        print "|             "
        print "|             "
    elif guesses == 3:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|      "
        print "|             "
        print "|             "
    elif guesses == 4:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|\     "
        print "|             "
        print "|             "
    elif guesses == 5:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|\     "
        print "|     /       "
        print "|             "
    else:
        print "________      "
        print "|      |      "
        print "|      0      "
        print "|     /|\     "
        print "|     / \     "
        print "|             "
        print "The noose tightens around your neck, and you feel the"
        print "sudden urge to urinate."
        print "GAME OVER!"
        self.__init__()

def progress_updater(self, guess, the_word, progress):
    i = 0
    while i < len(the_word):
        if guess == the_word[i]:
            progress[i] = guess
            i += 1
        else:
            i += 1

    return "".join(progress)

这是一个叫做“Hangman”(猜单词游戏)的类。它的作用是创建一个游戏的基本框架。

在这个类里,有一个初始化的方法(也就是当你创建这个游戏的时候会自动运行的部分)。

当你开始这个游戏时,它会打印出欢迎信息:“欢迎来到‘Hangman’,你准备好接受挑战了吗?”

接着,它会给你两个选择:

(1) 是的,我已经准备好了。

(2) 不,我想离开这里!

然后,程序会等待你输入你的选择。

最后一行代码是创建这个游戏的实例,也就是开始游戏的意思。

这段代码的意思就是:当你运行这段代码时,会看到欢迎信息和选择,然后你可以根据提示输入你的选择。

0

代码里有好几个错误。下面是修正后的代码:

import re

def unused_letters( letters, guess ): # your main problem is corrected here.
    unusedLetters = list( letters )
    unusedLetters.remove( guess )

    letters = ''.join( unusedLetters )
    return letters

def filled_word( wordy, guessy ):
    if wordy.find( guessy ) != -1:
        position = [m.start() for m in re.finditer( guessy, wordy )]
        for x in position:
            filled_word.emptyWord[x] = guessy
        strWord = ''.join( filled_word.emptyWord )
        print 'Good guess.'
        print 'Current word: %s' % ''.join( filled_word.emptyWord )
    else:
        strWord = ''.join( filled_word.emptyWord )
        print 'Oops! That letter is not in my word:', strWord

def hangman( word, numLetters ):  # you dont need the previous check. Let all be done in the main loop
    print 'Welcome to the game, Hangman!'
    print 'I am thinking of a word that is', numLetters, 'letters long'
    remainingGuesses = 8
    letters = 'abcdefghijklmnopqrstuvwxyz'
    try:
        # # memoizing the current word. for more info, try to understand that functions are
        # # also objects and that we are assigning a new attribute the function object here.
        filled_word.emptyWord
    except:
        filled_word.emptyWord = ['_'] * numLetters
    while '_' in filled_word.emptyWord and remainingGuesses > 0:

        print 'You have', remainingGuesses, 'guesses left'

        print 'Available letters:', letters
        guess = raw_input( "Please guess a letter:" )
#         print 'guess: %s' % guess
        if guess in letters:
            filled_word( word, guess )
            letters = unused_letters( letters, guess )
        else:
            print 'You guessed: %s, which is not in Available letters: %s' % ( guess, ''.join( letters ) )
            print 'Current word: %s' % ''.join( filled_word.emptyWord )

        remainingGuesses -= 1

word = "godman"

print hangman( word, numLetters = len( word ) )
if '_' in filled_word.emptyWord:
    print 'Ahh ! you lost....The hangman is hung'
else:
    print 'Congratulations, you won!'

你还可以进一步改进,检查一下剩下的猜测次数是否少于需要填的字母数量,然后决定是让玩家失败还是继续游戏。

1

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这就像是把书从一个书架搬到另一个书架一样。

有些时候,我们会遇到一些问题,比如数据格式不对,或者数据不完整。这就像是你在搬书的时候,发现有些书缺页了,或者书的封面坏了。

为了避免这些问题,我们可以提前检查一下数据,确保它们都是完整的、格式正确的。这样在搬书的时候,就不会出现麻烦了。

总之,处理数据的时候,提前做好准备工作,可以让我们的程序运行得更顺利。

def choose_word():
    word = 'alphabeth'
    return {'word':word, 'length':len(word)}

def guess_letter(word_, hidden_word_, no_guesses_, letters_):
    print '---------------------------------------'
    print 'You have', no_guesses_, 'guesses left.'
    print 'Available letters:', letters_

    guess = raw_input("Please guess a letter:")
    guess = guess.lower()

    if guess in letters_:
        letters_ = letters_.replace(guess, '')

        if guess in word_:
            progress = list(hidden_word_)
            character_position = -1
            for character in word_:
                character_position += 1
                if guess == character:
                    progress[character_position] = guess
            hidden_word_ = ''.join(progress)
            print 'Good guess =', hidden_word_
        else:
            print 'Oops! That letter is not in my word:', hidden_word_
            no_guesses_ = no_guesses_ - 1
    else:
        print 'The letter "', guess, '" was already used!'
        no_guesses_ = no_guesses_ - 1

    if hidden_word_ == word_:
        print 'Congratulations, you won!'
        return True
    if no_guesses_ == 0 and hidden_word_ != word_:
        print 'Game over! Try again!'
        return False
    return guess_letter(word_, hidden_word_, no_guesses_, letters_)

def hangman():
    hangman_word = choose_word()
    print 'Welcome to the game, Hangman!'
    print 'I am thinking of a word that is', hangman_word['length'], 'letters long.'

    hidden_word = ''.join(['_'] * hangman_word['length'])
    no_guesses = 8
    letters = 'abcdefghijklmnopqrstuvwxyz'

    guess_letter(hangman_word['word'], hidden_word, no_guesses, letters)

hangman()

撰写回答