1

我需要用 python 程序制作一个刽子手程序,但我不知道如何继续。在程序中,我有 6 次机会(也称为“生命线”)来猜测单词中的字母。每一次错误的猜测都会缩短“生命线”。当你猜对了单词或者你用完了你所有的“生命线”时,游戏就会结束。这是示例输出:

['_', '_', '_', '_']

***Life Line***
-+-+-+-+-+-+
$|$|$|$|$|$|
-+-+-+-+-+-+

Enter your guess: a
['_', '_', '_', '_']

***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+

Incorrect Guess: ['a']
...................................
Enter your guess: b
['b', '_', '_', '_']

***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+

Incorrect Guess: ['a']
...................................
Enter your guess: l
['b', 'l', '_', '_']

***Life Line***
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+

Incorrect Guess: ['a']
...................................
Enter your guess: o
['b', 'l', '_', '_']

***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+

Incorrect Guess: ['a', 'o']
...................................
Enter your guess: u
['b', 'l', 'u', '_']

***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+

Incorrect Guess: ['a', 'o']
...................................
Enter your guess: e
['b', 'l', 'u', 'e']

***Life Line***
-+-+-+-+
$|$|$|$|
-+-+-+-+

Incorrect Guess: ['a', 'o']
...................................
You Got it Right! Well Done!

我已经输入了前几个代码但卡住了。

import random
wordList = ["Mary","Tian Pei","Pong"]
randname = random.choice ( wordList)
print randname

resultList = [ ] 

for i in range(len(randname)):
    resultList.append("_")
print resultList
4

3 回答 3

2

Create the blank list:

>>> name = "Mary"
>>> blanks = ["_" for letter in name]
>>> blanks
['_', '_', '_', '_']

Create a list of incorrect guesses:

>>> incorrect_guesses = # you figure this one out

Set up your life-lines:

>>> life_lines = # you figure this one out

Prompt for a guess:

>>> guess = raw_input("Guess: ")
Guess: a
>>> guess
'a'

Save a variable which says whether or not the guess was incorrect:

>>> incorrect = # you figure this one out

Iterate over the name and replace the respective blank line in blanks with the letter if the respective letter in name is the same as the guess:

>>> for i in range(len(name)):
...     if name[i] == guess:
...         incorrect = # you figure this one out
...         blanks[i] = # you figure this one out
... 
>>> blanks
['_', 'a', '_', '_']

If incorrect is True, add the guess to the incorrect_guesses (in this case, since the guess was correct, it wouldn't update) and subtract a life-line:

>>> if incorrect:
...     incorrect_guesses.append( # you figure this one out )
...     life_lines -= # you figure this one out
...

To check for equivalence, join the letters in blanks to re-form the original word so that you can compare the two:

>>> final = ''.join(blanks)    # this connects each letter with an empty string
>>> final
'_a__'

The general control structure could be the following:

choose random word
create blanks list
set up life-lines
while life_lines is greater than 0 and word not completed:
    print blanks list
    print life_lines graphic
    if there are incorrect guesses:
        print incorrect guesses
    prompt for guess
    check if correct and fill in blanks
    if incorrect:
        add to incorrect guesses and subtract a life-line
if word completed:
    you win
else:
    you lose

It's up to you to fill in the blanks I wrote here (and to write your own routines for printing the life-line graphics and such).

于 2013-08-01T01:38:33.983 回答
0

你可以做这样的事情。有关逻辑的解释,请参见代码中的注释。

#!/usr/bin/env python
import random

wordList = ["Mary","Tian Pei","Pong"]
randname = random.choice ( wordList)

resultList = []

# When creating the resultList you will want the spaces already filled in
# You probably don't want the user to guess for spaces, only letters.
for letter in randname:
    if letter == ' ':
        resultList.append(' ')
    else:
        resultList.append("_")

# We are storing the number of lifeline 'chances' we have here
# and the letters that have already been guessed
lifeline = 6
guesses = []


# The game does not end until you win, on run out of guesses
while guesses != 0:

    # This prints the 'scoreboard'
    print resultList
    print '***Life Line***'
    print '-+' * lifeline
    print '$|' * lifeline
    print '-+' * lifeline
    print 'Incorrect Guess: %s' % guesses

    # If the win condition is met, then we break out of the while loop
    # I placed it here so that you see the scoreboard once more before 
    # the game ends
    if ''.join(resultList) == randname:
        print 'You win!'
        break

    # raw_input because I'm using 2.7
    g = raw_input("What letter do you want to guess?:")

    # If the user has already guessed the letter incorrectly,
    # we want to forgive them and skip this iteration
    if g in guesses:
        print 'You already guessed that!'
        continue

    # The lower port here is important, without it guesses are 
    # case sensitive, which seems wrong.
    if g.lower() in [letter.lower() for letter in randname]:
        # this goes over each letter in randname, then flips
        # the appropriate postions in resultList
        for pos, letter in enumerate(randname):
            if g.lower() == letter.lower():
                resultList[pos] = letter
    # If the letter is not in randname, we reduce lifeline
    # add the guess to guesses and move on
    else:
        lifeline -= 1
        guesses.append(g)

如果您需要任何澄清,请告诉我。

于 2013-08-01T01:58:14.917 回答
0
import random
"""
Uncomment this section to use these instead of life-lines
HANGMAN_PICS = ['''
  +---+
      |
      |
      |
     ===''', '''
  +---+
  O   |
      |
      |
     ===''', '''
  +---+
  O   |
  |   |
      |
     ===''', '''
  +---+
  O   |
 /|   |
      |
     ===''', '''
  +---+
  O   |
 /|\  |
      |
     ===''', '''
  +---+
  O   |
 /|\  |
 /    |
     ===''', '''
  +---+
  O   |
 /|\  |
 / \  |
      ===''']
"""

HANGMAN_PICS = ['''
-+-+-+-+-+-+
$|$|$|$|$|$|
-+-+-+-+-+-+ ''','''
-+-+-+-+-+
$|$|$|$|$|
-+-+-+-+-+ ''','''
-+-+-+-+
$|$|$|$|
-+-+-+-+ ''','''
-+-+-+
$|$|$|
-+-+-+ ''','''
-+-+
$|$|
-+-+ ''','''
-+
$|
-+ ''','''
-+
 |
-+''']

words = '''ant baboon badger bat bear beaver camel kangaroo chicken panda giraffe
 raccoon frog shark fish cat clam cobra crow deer dog donkey duck eagle ferret fox frog 
 goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot
 pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork
 swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'''.split()
# List of all the words

def getRandomWord(wordList):
    wordIndex = random.randint(0, len(wordList) - 1) # Random index
    # Indexes in python start from 0, therefore len(wordList) - 1
    return wordList[wordIndex] # Chooses a random word from the list which is a passed through the function
    # Returns the random word

def displayBoard(missedLetters, correctLetters, secretWord):
    print(HANGMAN_PICS[len(missedLetters)])
    print()

    print('Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
        # Displaying each letter of the string 'missedLetters'
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)):
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
            # Checking for characters that match and replacing the blank with the character

    for letter in blanks:
        print(letter, end=' ')
    print()
    # Printing the blanks and correct guesses

def getGuess(alreadyGuessed):

    while True:
        print('Guess a letter.')
        guess = input()
        guess = guess.lower()
        if len(guess) != 1: # more than 1 letters entered
            print('Please enter a single letter.')
        elif guess in alreadyGuessed: # letter already guessed
            print('You have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghijklmnopqrstuvwxyz': # not a letter
            print('Please enter a LETTER.')
        else:
            return guess
    # Taking a guess as input and checking if it's valid
    # The loop will keep reiterating till it reaches 'else'

def playAgain():

    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')
    # Returns a boolean value


print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words) # Calls the 'getRandomWord' function
gameIsDone = False

while True:

    displayBoard(missedLetters, correctLetters, secretWord)

    guess = getGuess(missedLetters + correctLetters)

    if guess in secretWord:
        correctLetters = correctLetters + guess

        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
                # if any letter of the 'secretWord' is not in 'correctLetters', 'foundAllLetters' is made False
            # If the program doesn't enter the if statement, it means all the letters of the 'secretWord' are in 'correctLetters'
        if foundAllLetters: # if foundAllLetters = True
            print('Yes! The secret word is "' + secretWord +
              '"! You have won!')
            # Printing the secret word
            gameIsDone = True
    else:
        missedLetters = missedLetters + guess

        if len(missedLetters) == len(HANGMAN_PICS) - 1:
            displayBoard(missedLetters, correctLetters, secretWord)
            print('You have run out of guesses!\nAfter ' +
              str(len(missedLetters)) + ' missed guesses and ' +
              str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
            # Prints the answer and the all guesses
            gameIsDone = True

    if gameIsDone:
        if playAgain():
            missedLetters = ''
            correctLetters = ''
            gameIsDone = False
            secretWord = getRandomWord(words)
            # Restarts Game
        else:
            break
            # Program finishes
于 2020-06-09T13:05:33.527 回答