在我的代码中,我很难用正确的字母替换单词长度显示的下划线。我该如何解决这个问题?。
下面是我正在运行的代码的示例。
print("Welcome to Python Hangman")
print()
import random # Needed to make a random choice
from turtle import * #Needed to draw line
WORDS= ("variable", "python", "turtle", "string", "loop")
word= random.choice(WORDS)#chooses randomly from the choice of words
print ("The word is", len(word), "letters long.")# used to show how many letters are in the random word
space = len(word)
underscore = ("_ " * space)
print(underscore)
for i in range(1, 9):#gives the amount of guesses allocated
letter = input("Guess a letter ")
if letter in word:
print ("Correct", letter)#if guesses letter is correct print correct
else:
print ("Incorrect", " ",letter)
#if its wrong print incorecct
我会使用dict来跟踪正确猜测的字母并在此基础上打印,您还需要了解用户何时获胜:
WORDS= ("variable", "python", "turtle", "string", "loop")
word = random.choice(WORDS)#chooses randomly from the choice of words
print ("The word is", len(word), "letters long.")# used to show how many letters are in the random word
ln = len(word)
guessed = dict.fromkeys(word, 0)
print("_ "*ln)
correct = 0
for i in range(1, 9):#gives the amount of guesses allocated
letter = input("Guess a letter ")
if letter in word:
print ("Correct! {} is in the word".format(letter))#if guesses letter is correct print correct
guessed[letter] = 1
correct += 1
if correct == ln:
print("Congratulations! you win.n The word was {}".format(word))
break
else:
print ("Incorrect! {} is not in the word".format(letter))
#if its wrong print incorecct
print(" ".join([ch if guessed[ch] else "_" for ch in word]))
else:
print("You lose!nThe word was {}".format(word))
遗憾的是,在将下划线打印到控制台窗口后,无法替换下划线。您的选择是:
- 实现GUI,该GUI允许您在文本显示后更改文本
- 打印大量空行以使旧版本的输出文本消失(这给人的印象是输出已经更改)
- 每次需要更改输出文本时打印更新版本(这是我建议的)。请参阅下面我对此选项的描述
对于选项3,您的输出可能如下所示:
欢迎来到Python Hangman这个单词有6个字母长。__ _ _ _猜一个字母t更正tt猜一个字母u更正ut u _ t _ _猜一个字母e更正et u _ t _ e猜一封信
为了实现这一点,你应该有一个这样的列表:
output = ['_'] * len(word)
现在,每当用户找到正确的字母时,您可以通过以下操作替换此列表中的空格:
for i,x in enumerate(word):
if x is letter:
output[i] = letter
并使用以下功能打印更新后的列表:
def print_output():
print ''.join([str(x)+" " for x in output])
这将为您提供所需的输出。
完整解决方案:
print "Welcome to Python Hangman"
print
import random # Needed to make a random choice
WORDS = ("variable", "python", "turtle", "string", "loop")
word = random.choice(WORDS)#chooses randomly from the choice of words
print "The word is", len(word), "letters long." # used to show how many letters are in the random word
output = ['_'] * len(word)
# function to print the output list
def print_output():
print
print ''.join([x+" " for x in output])
for i in range(1, 9):#gives the amount of guesses allocated
print_output()
letter = raw_input("Guess a letter ")
if letter in word:
print "Correct", letter #if guesses letter is correct print correct
# now replace the underscores in the output-list with the correctly
# guessed letters - on the same position the letter is in the
# secret word of course
for i,x in enumerate(word):
if x is letter:
output[i] = letter
else:
print "Incorrect", " ", letter
#if its wrong print incorecct
这里有一个Python 3版本,它也检查是否获胜:
print('Welcome to Python Hangman')
import random
WORDS = ("variable", "python", "turtle", "string", "loop")
word = random.choice(WORDS)#chooses randomly from the choice of words
print('The word is", len(word), "letters long.')
output = ['_'] * len(word)
def print_output():
print()
print(''.join([x+' ' for x in output]))
for w in range(1, 9):
print_output()
letter = input('Guess a letter n')
if letter == word:
print('You win!')
break
elif letter in word:
print('Correct', letter)
for i, x in enumerate(word):
if x is letter:
output[i] = letter
if '_' not in output:
print('You win!')
break
else:
print('Incorrect', ' ', letter)
这里有一个多人游戏版本,允许第一个人选择自己的单词:
print('Welcome to Python Hangman')
word = input('Your word. DON'T TELL THIS TO ANYONE!n')
print('nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'
'nnnnnThe word is', len(word), 'letters long.')
output = ['_'] * len(word)
def print_output():
print()
print(''.join([x+' ' for x in output]))
for w in range(1, 9):
print_output()
letter = input('Guess a letter n')
if letter == word:
print('You win!')
break
elif letter in word:
print('Correct', letter)
for i, x in enumerate(word):
if x is letter:
output[i] = letter
if '_' not in output:
print('You win!')
break
else:
print('Incorrect', ' ', letter)
使用列表并替换您想要的任何内容,如:
ml = ["tom","tim"]
fw = (ml[0])
fwl = list(fw)
no = 0
for i in range(0,len(fwl)):
a = (fwl[no])
if a == "o":
fwl[0] = "i"
no = no+1
o = ""
p = o.join(fwl)
print(p)
短期使用:
your list[index for replacement to be done] = replacement
在实际打印之前打印空行会给人一种重写下划线的错觉。我用os找到tty/terminal的高度并打印了那么多空行。
"\b"不能用于此实例,因为使用了输入所需的换行符。
import os
import random # Needed to make a random choice
WORDS= ("variable", "python", "turtle", "string", "loop")
word= random.choice(WORDS)#chooses randomly from the choice of words
print ("The word is", len(word), "letters long.")# used to show how many letters are in the random word
def guess_word(word, max_attempt, attempt, guessed_chars=[]):
prompt_string="Guess a letter "
rows, columns = os.popen('stty size', 'r').read().split()
print "n"*int(columns)
print("Welcome to Python Hangman")
complete = 1
for char in word:
if char in guessed_chars:
print char,
else:
print '_',
complete = 0
if complete == 1:
print "nYou won!"
return
print "Attempts left = "+ str(max_attempt - attempt + 1)
letter = raw_input(prompt_string)
if letter in word:
guessed_chars.append(letter)
else:
print ' '
if (attempt<max_attempt and len(guessed_chars) <= len(word)):
guess_word(word, max_attempt, attempt+1, guessed_chars)
else:
print "You lose :(. Word is "+word
guess_word(word, len(word), 0)