Tôi đang cố gắng tạo trò chơi đoán từ. Mọi thứ hoạt động ngoại trừ phần câu lệnh if cuối cùng. Nếu người dùng đoán tên chính xác, nó sẽ không in "Won!". Tuy nhiên, nếu không, câu lệnh khác sẽ thi hành và nó sẽ in "Lost!". Tại sao vậy? Tôi đã kiểm tra nó nhiều lần, nhưng tôi không tìm thấy bất kỳ lỗi nào.Tại sao điều này không xảy ra nếu câu lệnh được thực thi?
Lưu ý: Tôi sử dụng Python 3,6
import random
def get_random_word():
words = ["Ronnie", "Deskty", "Lorrie"]
word = words[random.randint(0, len(words)-1)]
return word
def show_word(word):
for character in word:
print(character, " ", end="")
print("")
def get_guess():
print("Enter a letter: ")
return input()
def process_letter(letter, secret_word, blanked_word):
result = False
for i in range(0, len(secret_word)):
if secret_word[i] == letter:
result = True
blanked_word[i] = letter
return result
def print_strikes(number_of_strikes):
for i in range(0, number_of_strikes):
print("X ", end="")
print("")
def play_word_game():
strikes = 0
max_strikes = 3
playing = True
word = get_random_word()
blanked_word = list("_" * len(word))
while playing:
show_word(blanked_word)
letter = get_guess()
found = process_letter(letter, word, blanked_word)
if not found:
strikes += 1
print_strikes(strikes)
if strikes >= max_strikes:
playing = False
if not "_" in blanked_word:
playıng = False
if strikes >= max_strikes:
print("Lost")
else:
print("Won")
print("Game started")
play_word_game()
print("Game over")
Vâng, in giá trị của 'cảnh cáo' trước' if' ... –
Lưu ý: bạn có thể sử dụng ['random.choice (words)'] (https://docs.python.org/3/library /random.html#random.choice) trên 'từ [random.randint (0, len (words) -1)]' để nhận giá trị ngẫu nhiên từ danh sách – cat