您好,我在我的python课堂上学习了2周,我做了一个简单的hangman型游戏,代码是
secret = "computers"
my_string = ""
guesses = 10
welcome = input("Welcome to hangman, whats your name? ")
print("Hi " + welcome + " lets get started.")
secret = "computers"
my_string = ""
guesses = 10
welcome = input("Welcome to hangman, whats your name? ")
print("Hi " + welcome + " lets get started.")
while guesses >= 0:
guess = input("Guess a letter: ")
if guess in secret:
print("Correct")
my_string = my_string + guess
print(my_string)
elif guess not in secret:
print("incorrect")
guesses = guesses - 1
print("You have " + str(guesses) + " left.")
if my_string == "computer":
print("Congrats you won!")
break
if guesses == -1:
print("You lost.")
break
问题在于,一旦我输入字母,它就不会以正确的顺序打印。例如,如果我先键入“ o”,然后以正确的顺序猜测其余字符,那么如果有人可以帮助我,它将打印“占用者”。
答案 0 :(得分:0)
您可以通过以下方式构建输出字符串:
my_string = my_string + guess
因此,您只需将正确猜出的字母按照猜出字母的顺序一个接一个地放置,而不必考虑秘密单词中的字母顺序。
答案 1 :(得分:0)
您的冲突线就是这些
if guess in secret:
print("Correct")
my_string = my_string + guess
如果仔细观察,当您第一次添加字母时,假设o
,my_string
为空,然后向其添加guess
变量。
>>> print(my_string)
"o"
,然后添加c
>>> print(my_string)
"oc"
我建议您使用其他方法来检查您是否输入了秘密字符的字符。
答案 2 :(得分:0)
由于您是新手,所以我想为您提供更好版本的hangman。下面的代码是您的子手的切碎和更改版本。这是代码:
def choose_word():
word = 'computers'
return {'word':word, 'length':len(word)}
def guess_letter(word_, hidden_word_, no_guesses_, letters_):
print('---------------------------------------')
print('You have', no_guesses_, 'guesses left.')
print('Available letters:', letters_)
guess = input("Please guess a letter:")
guess = guess.lower()
if guess in letters_:
letters_ = letters_.replace(guess, '')
if guess in word_:
progress = list(hidden_word_)
character_position = -1
for character in word_:
character_position += 1
if guess == character:
progress[character_position] = guess
hidden_word_ = ''.join(progress)
print('Good guess =', hidden_word_)
else:
print('Oops! That letter is not in my word:', hidden_word_)
no_guesses_ = no_guesses_ - 1
else:
print('The letter "', guess, '" was already used!')
no_guesses_ = no_guesses_ - 1
if hidden_word_ == word_:
print('Congratulations, you won!')
return True
if no_guesses_ == 0 and hidden_word_ != word_:
print('Game over! Try again!')
return False
return guess_letter(word_, hidden_word_, no_guesses_, letters_)
def hangman():
hangman_word = choose_word()
print('Welcome to the game, Hangman!')
print('I am thinking of a word that is', hangman_word['length'], 'letters long.')
hidden_word = ''.join(['_'] * hangman_word['length'])
no_guesses = 8
letters = 'abcdefghijklmnopqrstuvwxyz'
guess_letter(hangman_word['word'], hidden_word, no_guesses, letters)
hangman()