在我的代码中,我无法用正确的字母替换单词长度显示的下划线。我该如何解决这个问题?。
以下是我的代码运行示例。
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
答案 0 :(得分:0)
可悲的是,在将下划线打印到控制台窗口后,无法更换下划线。您的选择是:
对于选项3,您的输出可能如下所示:
Welcome to Python Hangman The word is 6 letters long. _ _ _ _ _ _ Guess a letter t Correct t t _ _ t _ _ Guess a letter u Correct u t u _ t _ _ Guess a letter e Correct e t u _ t _ e Guess a letter
要实现这一目标,您应该有一个这样的列表:
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
答案 1 :(得分:0)
我会使用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))
答案 2 :(得分:0)
以下是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('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'
'\n\n\n\n\nThe 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)
答案 3 :(得分:0)
使用列表并替换您想要的内容,例如:
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
答案 4 :(得分:-1)
在实际打印之前使用打印空行会给人一种幻觉,即你正在编写下划线。 我使用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)