所以在我的代码中,我遇到了无法摆脱空间的问题,这是我的代码:
import random,time
def main():
welcome = ['Welcome to Hangman !This is the game of guessing',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts. Good luck!',
'Now player one please type in the letter without letting player two see it.']
for line in welcome:
print(line, sep='\n')
play_again = True
while play_again:
time.sleep(0)
words = input("Player one please enter the letter in: ")
chosen_word = words.lower()
player_guess = None
guessed_letters = []
word_guessed = []
for letter in chosen_word:
word_guessed.append("-")
joined_word = None
HANGMAN = (
"""
-----
| |
|
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| -+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| |
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| |
| |
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| | |
| |
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| | |
| | |
|
--------
""")
print(HANGMAN[0])
attempts = len(HANGMAN) - 1
while (attempts != 0 and "-" in word_guessed):
print(("\nYou have {} attempts remaining").format(attempts))
joined_word = "".join(word_guessed)
print(joined_word)
try:
player_guess = str(input("\nPlease select a letter between A-Z" + "\n> ")).lower()
except:
print("That is not valid input. Please try again.")
continue
else:
if len(player_guess) > 1:
print("That is more than one letter. Please try again.")
continue
elif player_guess in guessed_letters:
print("You have already guessed that letter. Please try again.")
continue
elif player_guess:
else:
pass
guessed_letters.append(player_guess)
for letter in range(len(chosen_word)):
if player_guess == chosen_word[letter]:
word_guessed[letter] = player_guess
if player_guess not in chosen_word:
attempts -= 1
print(HANGMAN[(len(HANGMAN) - 1) - attempts])
if "-" not in word_guessed:
print(("\nCongratulations! {} was the word").format(chosen_word))
else:
print(("\nUnlucky! The word was {}.").format(chosen_word))
print("\nWould you like to play again?")
response = input("> ").lower()
if response not in ("yes", "y"):
play_again = False
if __name__ == "__main__":
main()
因此,当我输入一个刺客信条的玩家时: 我希望我的代码是________ _____但是它显示______________我不会忽略这个空间请帮忙。
答案 0 :(得分:1)
您的问题是您创建列表word_guessed
的位置。您始终添加-
字符,但需要添加chosen_word
字符串中存在空格的空格。您可以使用基本列表理解:
chosen_word = 'chrisz is cool'
word_guessed = ['-' if i != ' ' else i for i in chosen_word]
print(''.join(word_guessed))
输出:
------ -- ----
答案 1 :(得分:0)
也许这样的事情可以帮到你。
for letter in chosen_word:
if letter =" ":
word_guessed.append(" ")
else:
word_guessed.append("-")
您正在循环遍历包含空格的字符串“chosen_word”中的每个字符串,检查将用新字符串中的空格替换“”(空格),将其他字符替换为“ - ”。
虽然这似乎也暗示数字和特殊字符可以包含在您可能要验证的单词中!