[英]Triggering a win function in Hangman
我對編碼很陌生,我已開始為學校項目編寫一個劊子手游戲。 目前我遇到了觸發勝利的問題。 我還有另一個問題,即用戶輸入后沒有打印。 任何幫助是極大的贊賞。
print ("WELCOME, YOU ARE PLAYING HANGMAN!")
import random
def guess():
word = (random.choice(open("Level1py.txt").readline().split()))
guesses = 8
#If letterguessed == current letter in word, add that letter else add a _
#guess function
guessword = []
word = (random.choice(open("Level1py.txt").readline().split()))
guesses = 8
def checkLetter(letter, word, guess_word):
for c in word:
if c == letter:
guess_word[word.index(c)] = c
word_list = list(word)
word_list[word.index(c)] = "*"
word = ''.join(word_list)
print(guess_word)
guess_word = ['_' for x in word]
while '_' in guess_word:
guess = input('Letter: ')
print(checkLetter(guess, word, guess_word))
while guesses > -1 and not guess_word == word:
guess = input("Guess:")
if guess in word:
print("correct letter")
print(guess_word)
else:
print("incorrect")
guesses -= 1
if guesses < 0:
print ("""
_______
|/ |
| (_)
| /|\
| |
| / \
|
|___
HANGMAN""""You guessed wrong. The correct word was: " + str(word))
else:
print("congrats, you won")
您確實需要檢查縮進並簡化代碼。 永遠不會觸發win的原因是從未達到else語句(由於while循環中沒有guess_word == word
條件)。 你需要在游戲循環中結束游戲。 您還可以在幾個地方不必要地打印guess_word
。
這是一個工作版本。 你可以在這里測試一下: https : //repl.it/@glhr/hangman 。 我對該單詞進行了硬編碼,而不是從文件中取出,因為該部分與您的問題無關。
print ("WELCOME, YOU ARE PLAYING HANGMAN!")
guessword = []
word = "test"
guesses = 8
guess_word = ['_' for x in word]
def checkLetter(letter, word, guess_word):
for c in word:
if c == letter:
guess_word[word.index(c)] = c
print(guess_word)
while '_' in guess_word and guesses > -1:
guess = input('Letter: ')
if guess in word:
print("correct letter")
else:
print("incorrect")
guesses -= 1
print (guesses," guesses left")
checkLetter(guess, word, guess_word)
if guesses < 0:
print ("""
|/ |
| (_)
| /|\
| |
| / \
|
|___
HANGMAN"""" You guessed wrong. The correct word was: " + str(word))
else:
print("congrats, you won")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.