刽子手游戏代码

问题描述 投票:0回答:4

我想得到一些关于刽子手游戏的帮助。我已经创建了这段代码并花了很多时间来尝试改进它但我仍然无法获得正确的输出。真的很感谢你的帮助!

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而不是特定的字母。

此外,我猜的字母中确实出现的字母没有存储。即在猜测1中,代码返回单词(例如)'d____',但在猜测2中,在猜测'e'时,代码返回单词'e_'而不是'd_e__'。是因为变量的分配?局部变量和全局变量?对此我很困惑。

真的很感激帮助!非常感谢! :)

python variables
4个回答
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()

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!'

你仍然可以通过检查剩余的猜测次数是否小于要填写的字母来做得更好,并决定是否让播放器失败或允许它继续播放。


0
投票

class Hangman():def init(self):print“欢迎来到'Hangman',你准备好死吗?”打印“(1)是的,因为我已经死了。\ n(2)不,让我离开这里!” user_choice_1 = raw_input(“ - >”)

    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)

game = Hangman()


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(
        '''
        ☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
        ☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺☻☺
        '''
    )
© www.soinside.com 2019 - 2024. All rights reserved.