在可以使用任何字长的意义上,游戏与术语略有不同。如何让我的程序打印?当字母在单词中但不在正确的位置时?如果字母在正确的位置,如何打印实际字母呢?例如,这个词是“坦克”而用户进入“城镇”它应该打印“t--?”我把一切都搞定了,直到我必须使我的代码输出字符而不是“ - ” (这些词是荷兰语,但不应该有任何区别)
import random
wordlist = ["hond", "haas", "neus", "peer","fruit", "laptop","raam","computer", "python", "hakan", "akkas", "mohammed", "amine", "school","informatica"]
word = random.choice(wordlist)
print("Your secret word has ", len(word), "letters")
while True:
guessword = input("Guess the word:")
if len(Guessword) != len(word): print("type a word with", len(word),"letters")
elif guessword == word: break
elif guessword != word:
if guessword != word: print("-" * len(word))
print("Congratulations, you guessed the word correctly!")
我还必须让游戏告诉你你用了多少次来猜测这个词以及根据时间实现一个得分系统。
编辑:必须尽可能紧凑
答案 0 :(得分:0)
使用enumerate
:
import random
wordlist = ["hond", "haas", "neus", "peer","fruit", "laptop","raam","computer", "python", "hakan", "akkas", "mohammed", "amine", "school","informatica"]
# 'word' hardcoded for testing
word = "tank" #random.choice(wordlist)
print("Your secret word has ", len(word), "letters")
while True:
guessword = input("Guess the word:")
if len(guessword) != len(word): print("type a word with", len(word),"letters")
elif guessword == word: break
elif guessword != word:
for position, letter in enumerate(guessword):
if letter == word[position]:
print(letter, end="")
elif letter not in word:
print("-", end="")
else:
print("?", end="")
print("")
print("Congratulations, you guessed the word correctly!")
测试:
$ python3.5 word_game.py
Your secret word has 4 letters
Guess the word:town
t--?
Guess the word:tans
tan-
Guess the word:tank
Congratulations, you guessed the word correctly!