Python 简单的蟒蛇刽子手游戏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19760186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple python hangman game
提问by user2951107
I am having a little bit of trouble with my python hangman game. I think I have the mechanisms down for the most part (not 100% confident) but I am having a bit of issues when it comes to printing out the board whenever the user enters in a letter. It is supposed to find the index where that is stored and then go to that index and replace it with the guessed letter. At the moment it doesn't replace the letter and when it reprints out the board after a guessed letter it just keeps adding more stars to the end. For example if the word is 6 letters long it prints out 6 stars. When you guess a letter it reprints the board with 12 stars and so on. How can I make it replace the letter when it is in the word and print that same board out with that letter filled in. Also when the game is over how do I prompt them to enter in if they want to keep playing and loop the whole game over again? The code is below:
我的 python 刽子手游戏有点问题。我想我在很大程度上已经关闭了机制(不是 100% 有信心),但是当用户输入一封信时,在打印板时我遇到了一些问题。它应该找到存储的索引,然后转到该索引并将其替换为猜测的字母。目前它不会替换字母,当它在猜出一个字母后重新打印出电路板时,它只会在末尾添加更多的星星。例如,如果单词长度为 6 个字母,则它会打印出 6 颗星。当你猜出一个字母时,它会用 12 颗星等重新打印板。当它在单词中时,我怎样才能让它替换字母并打印出填充该字母的同一个板。另外,当游戏结束时,如果他们想继续玩并重新循环整个游戏,我该如何提示他们进入?代码如下:
import random
listOfWords = ("hangman", "chairs", "backpack", "bodywash", "clothing", "computer", "python", "program", "glasses", "sweatshirt", "sweatpants", "mattress", "friends", "clocks", "biology", "algebra", "suitcase", "knives", "ninjas", "shampoo")
randomNumber = random.randint(0, len(listOfWords) - 1)
guessWord = listOfWords[randomNumber]
theBoard = []
wrong = []
guessedLetter = int(0)
#Will create the board using a new list and replace them with stars
def makeBoard(word):
for x in word: #will go through the number of letters in the word that is chosen and for each letter will append a star into theBoard list
theBoard.append('*')
return ''.join(theBoard) #Will print the list without having the [] and the commas
def guessing(letter): #This is for guessing the letters
win = int(0) #Will be used to see if the user wins
count = int(0) #Will be used to replace the star with a letter
if letter.lower() in guessWord: # converts to lowercase and goes through the word
guessedLetter = guessWord.index(letter) #create a variable called guessedLetter that will take the index of the letter guessed by the user
while (count != guessedLetter): #while loop to look for the index of the guessed letter
count += 1
if (count == guessedLetter): # will go into the board and replace the desired index with the letter if it matches
theBoard[count] = letter
for x in theBoard: # loop to go through theBoard to see if any '*' are there. If none are found it will say you win
if (x != '*'):
win += 1
if (win == len(theBoard)):
print("You win!")
def main():
print(guessWord)
level = input("Enter a difficulty level: ")
print("The word is: " + makeBoard(guessWord))
if (level == '1'):
print("You have selected the easy difficulty.")
while (len(wrong) != 9):
userGuess = input("Enter in the letter you want to guess: ")
guessing(userGuess)
if userGuess not in guessWord:
wrong.append(userGuess)
print("You have " + str(len(wrong)) + " guesses. Guessed letters: " + str(wrong))
if (len(wrong) == 9):
level = input("You have lost. If you would like to play again then enter in the difficulty level, or 4 to exit")
if (level != 4):
randomNewNumber = random.randint(0, len(listOfWords) - 1)
guessNewWord = listOfWords[randomNewNumber]
if (level == 4):
sys.exit(0)
if (level == '2'):
print("You have selected the medium difficulty.")
print("The word is: " + makeBoard(guessWord))
while (len(wrong) != 7):
userGuess = input("Enter in the letter you want to guess: ")
guessing(userGuess)
if userGuess not in guessWord:
wrong.append(userGuess)
print("You have " + str(len(wrong)) + " guesses. Guessed letters: " + str(wrong))
if (level == '3'):
print("You have selected the hard difficulty.")
print("The word is: " + makeBoard(guessWord))
while (len(wrong) != 5):
userGuess = input("Enter in the letter you want to guess: ")
guessing(userGuess)
if userGuess not in guessWord:
wrong.append(userGuess)
print("You have " + str(len(wrong)) + " guesses. Guessed letters: " + str(wrong))
main()
EDIT: I have fixed the problem about it redisplaying with the proper letter except for the first one. Example if the word is python it comes up as *ython even if you guess the p it doesn't display. Here is the code that does the replacing:
编辑:我已经解决了关于它以正确的字母重新显示的问题,除了第一个。例如,如果单词是 python,它会显示为 *ython,即使您猜测它不显示 p。这是进行替换的代码:
def guessing(letter): #This is for guessing the letters
win = int(0) #Will be used to see if the user wins
count = int(0) #Will be used to replace the star with a letter
guessedLetter = guessWord.index(letter) #create a variable called guessedLetter that will take the index of the letter guessed by the user
if letter.lower() in guessWord: # converts to lowercase and goes through the word
while (count != guessedLetter): #while loop to look for the index of the guessed letter
count = count + 1
if (count == guessedLetter): # will go into the board and replace the desired index with the letter if it matches
theBoard[count] = letter
print("The word is: " + ''.join(theBoard))
for x in theBoard: # loop to go through theBoard to see if any '*' are there. If none are found it will say you win
if (x != '*'):
win += 1
if (win == len(theBoard)):
print("You win!")
回答by Saelyth
I suggest you to save "progress" in a string variable (board) and replace it each time someone guess a good answer. I'll made up a code that might work and give you a hint.
我建议您将“进度”保存在字符串变量(板)中,并在每次有人猜出一个好的答案时替换它。我会编写一个可能有效的代码并给你一个提示。
import random
#global vars when starting the game
listOfWords = ["example", "says", "python", "rocks"]
guessWord = random.choice(listOfWords)
board = [" * " for char in guessWord]
alreadySaid = ""
#ready to rock and roll in a single loop
class Hangman():
def Playing():
global guessWord, board, alreadySaid
whatplayersaid = input("Guess a letter: ")
if whatplayersaid in guessWord:
board = [char if char == whatplayersaid or char in alreadySaid else " * " for char in guessWord]
board = "".join(board)
print(board)
else:
print("Nope")
alreadySaid = alreadySaid + whatplayersaid
Hangman.Playing()
Hangman.Playing()
:D Is that what you wanted to accomplish? (sorry about my poor english)
:D 这就是你想要完成的吗?(抱歉我的英语不好)
EDITTEDYou can save this in a new .py file, run it and try to say guesses, i hope you can adapt this to your code.
编辑您可以将其保存在一个新的 .py 文件中,运行它并尝试猜测,我希望您可以将其调整为您的代码。
EDITTED x2Now with a loop itself to see if is working fine
编辑 x2现在有一个循环本身,看看是否工作正常
回答by furas
Modified and tested Saelyth example - so now it is working game :)
修改和测试 Saelyth 示例 - 所以现在它正在运行游戏:)
#!/usr/bin/python3
import random
class Hangman():
def Playing(self):
listOfWords = ["example", "says", "python", "rocks"]
again = True
while again:
guessWord = random.choice(listOfWords)
board = "*" * len(guessWord)
alreadySaid = set()
mistakes = 7
print(" ".join(board))
guessed = False
while not guessed and mistakes > 0:
whatplayersaid = input("Guess a letter: ")
if whatplayersaid in guessWord:
alreadySaid.add(whatplayersaid)
board = "".join([char if char in alreadySaid else "*" for char in guessWord])
if board == guessWord:
guessed = True
else:
mistakes -= 1
print("Nope.", mistakes, "mistakes left.")
print(" ".join(board))
again = (input("Again [y/n]: ").lower() == 'y')
#----------------------------------------------------------------------
Hangman().Playing()
回答by hashmat
you didnt need some of the code you included changed it slightly
你不需要你包含的一些代码稍微改变了它
Hangman Program
刽子手计划
import random
def Playing():
listOfWords = ["example", "says", "python", "rocks","test", "hangman"]`
again = True #variable created
while again: #created a loop
guessWord = random.choice(listOfWords) #choses a randomly out of the words in the variable listofWords
board = "-" * len(guessWord) #prints how many letters theirn are in the randomly chosen word in - format
alreadySaid = set()
mistakes = 7 # the msitakes start at 7
print(" ".join(board)) # joining other letters/ replace - wirh the actual letteers
guessed = False
while not guessed and mistakes > 0:
guess = input("Guess a letter: ") #tells you to guess a letter and input it
if guess in guessWord: #if the leter you guessed is in the randomly selected word
alreadySaid.add(guess) #add it to whats already been said
board = "".join([char if char in alreadySaid else "-" for char in guessWord]) # join them
if board == guessWord:
guessed = True
else:
mistakes -= 1 # minuses 1 from the value of mistakes (7) if you get the guess wrong
print("Nope.", mistakes, "mistakes left.") # if what you guessed is wrong then print nope and how many mistakes are remaining
print(" ".join(board))
print('well done')
again = (input("Would you like to go again [y/n]: ").lower() == 'y') # asks if you want to go again -- changes it to lower cap
Playing() # displays Playing() whithout you typing in Playing() for it to appear
回答by Corrie Stewart
I LOVE MPM's version. I just tweaked the print out to tell the winner if they lost or won. In the previous version it printed "well done." whether they won or lost.
我喜欢 MPM 的版本。我只是调整了打印出来告诉赢家他们是输了还是赢了。在以前的版本中,它打印了“做得好”。不管他们赢了还是输了。
import random
def Playing():
listOfWords = ["example", "says", "python", "rocks","test", "hangman"]
again = True #variable created
while again: #created a loop
guessWord = random.choice(listOfWords) #choses a randomly out of the words in the variable listofWords
board = "*" * len(guessWord) #prints how many letters theirn are in the randomly chosen word in - format
alreadySaid = set()
mistakes = 7 # the msitakes start at 7
print(" ".join(board)) # joining other letters/ replace - wirh the actual letteers
guessed = False
while not guessed and mistakes > 0:
guess = input("Guess a letter: ") #tells you to guess a letter and input it
if guess in guessWord: #if the leter you guessed is in the randomly selected word
alreadySaid.add(guess) #add it to whats already been said
board = "".join([char if char in alreadySaid else "*" for char in guessWord]) # join them
if board == guessWord:
guessed = True
else:
mistakes -= 1 # minuses 1 from the value of mistakes (7) if you get the guess wrong
print("Nope.", mistakes, "mistakes left.") # if what you guessed is wrong then print nope and how many mistakes are remaining
print(" ".join(board))
if mistakes == 0:
print("Sorry! Game over.")
else:
print('Nice! You win.')
again = (input("Would you like to go again [y/n]: ").lower() == 'y') # asks if you want to go again -- changes it to lower cap
Playing() # displays Playing() whithout you typing in Playing() for it to appear
回答by Chris Oliver
When finding whether the letter is in the guessWord
move the line count = count + 1
to the end of your while
loop as shown below:
当找到字母是否在guessWord
移动线count = count + 1
到你的while
循环结束时,如下所示:
def guessing(letter): #This is for guessing the letters
win = int(0) #Will be used to see if the user wins
count = int(0) #Will be used to replace the star with a letter
guessedLetter = guessWord.index(letter) #create a variable called guessedLetter that will take the index of the letter guessed by the user
if letter.lower() in guessWord: # converts to lowercase and goes through the word
while (count != guessedLetter): #while loop to look for the index of the guessed letter
if (count == guessedLetter): # will go into the board and replace the desired index with the letter if it matches
theBoard[count] = letter
print("The word is: " + ''.join(theBoard))
##Just Here!
count = count + 1
for x in theBoard: # loop to go through theBoard to see if any '*' are there. If none are found it will say you win
if (x != '*'):
win += 1
if (win == len(theBoard)):
print("You win!")