gpt4 book ai didi

python - Python 中的 Hangman 游戏 : how to replace blanks with guessed letters

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:24:14 26 4
gpt4 key购买 nike

我正在为一个学校项目创建一个简单的 Hangman 实现,目前我的任务是让一个字母在猜对时在单词中显示出来。我已经有了根据单词中字母的数量生成空格的代码,以及我需要的游戏的几乎所有其他组件,但我不知道如何用正确的字母替换空格。

如果您能保持简单和解释,我将不胜感激,因为我在编程方面还很陌生。如果可能的话,这样我就不必过多地更改我的代码。

这是我的代码:

import random

name = str(input("What's your name?"))
print("Hello,", name + "!")
failures = 0
allowed = 1
guessed = str()
wordlist = ['hangman', 'dinner', 'computer', 'america', 'olympics', 'football', 'minecraft', 'jacket', 'cabbage', 'electricity', 'dog',
'pasta', 'japan', 'water', 'programming', 'anaconda', 'onehunga', 'name', 'windows', 'curtains', 'bieber', 'kirito',
'montenegro', 'wheel', 'civilization', 'physics', 'bluebird' 'table', 'ACDC', 'guardian yam' 'mario', 'parachute', 'agario', 'obama',
'youtube', 'putin', 'dairy', 'christianity', 'club penguin', 'oskahlavistah', 'coins', 'agitating', 'jumping', 'eating',
'your mom', 'executive', 'car', 'jade', 'abraham', 'sand', 'silver', 'uranium', 'oscar is gay', 'bioshock', 'fizzle', 'moonman', 'watermelon',
'WAHAHAHAHAHA', 'steve jobs', 'extreme', 'weeaboo jones', 'hot damn', name]

def correct(guess):
if guess in word:
if guess not in guessed:
print("Correct")
return(True)
else:
if guess not in word and len(guess) == 1 and guess in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
if guess not in guessed:
print("Incorrect!")
return(False)

print("Guess this word!")
print("You can input any letter from A to Z and the space key.")
wordnumber = random.randint(0, len(wordlist))
word = (wordlist[wordnumber])
print("_ "*len(word))
while failures < allowed:
guess = str(input("Guess a letter!"))
if len(guess) != 1 or guess not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ':
print("That is not a letter, try again.")
if guess in guessed:
print("You have already guessed that letter, try again.")
iscorrect = correct(guess)
guessed = guessed, guess
if iscorrect == True:
print("Word display still in development")
if iscorrect == False:
print("You suck")
failures = failures+1
print("You have", allowed , "guesses left.")
if failures == allowed:
replay = str(input("Press 1 to play again, press 2 to exit."))
if replay == 1:
break
else:
quit()

#Now all I have to do is find a way to display positions of correct letters.

最佳答案

要查找字母在字符串中的位置,请使用 word.index(guess)。然后替换“空白”字中的字母。为此,请保存 b_word = "_ "*len(word),并在正确的位置替换“_”:

s = list(b_word)
s[word.index(guess)] = guess

之后打印新的 b_word。

关于python - Python 中的 Hangman 游戏 : how to replace blanks with guessed letters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32222025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com