我需要用python程序制作一个hangman程序,但我不知道如何继续。 在该计划中 我有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
答案 0 :(得分:2)
创建空白列表:
>>> name = "Mary"
>>> blanks = ["_" for letter in name]
>>> blanks
['_', '_', '_', '_']
创建错误猜测列表:
>>> incorrect_guesses = # you figure this one out
设定你的生活线:
>>> life_lines = # you figure this one out
提示猜测:
>>> guess = raw_input("Guess: ")
Guess: a
>>> guess
'a'
保存一个变量,说明猜测是否不正确:
>>> incorrect = # you figure this one out
如果name
中的相应字母与blanks
相同,则name
将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', '_', '_']
:
incorrect
如果True
为guess
,请将incorrect_guesses
添加到>>> if incorrect:
... incorrect_guesses.append( # you figure this one out )
... life_lines -= # you figure this one out
...
(在这种情况下,因为猜测是正确的,它不会更新)并减去生命线:
blanks
要检查等效性,请加入>>> final = ''.join(blanks) # this connects each letter with an empty string
>>> final
'_a__'
中的字母以重新构成原始字词,以便您可以比较两者:
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
一般控制结构可能如下:
{{1}}
由你来填写我在这里写的空白(并编写自己的例程来打印生命线图形等)。
答案 1 :(得分: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)
如果您需要澄清任何内容,请告诉我。
答案 2 :(得分: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