我正在創建這個游戲,它只是劊子手游戲,程式從串列中隨機選擇一個單詞,用戶從隨機選擇的單詞中猜測一個字母,如果單詞不正確,生命計數會減少,直到它耗盡。
import random as rn
words = ['peter','apple','dentist']
stages = ['''
---
| |
O |
/|\ |
/ \ |
|
=========
''', '''
---
| |
O |
/|\ |
/ |
|
=========
''', '''
---
| |
O |
/|\ |
|
|
=========
''', '''
---
| |
O |
/| |
|
|
=========''', '''
---
| |
O |
| |
|
|
=========
''', '''
---
| |
O |
|
|
|
=========
''', '''
---
| |
|
|
|
|
=========
''']
chosen_word = rn.choice(words)
print(chosen_word)
blanks = []
lives = 6
state = False
for j in range(0 , len(chosen_word)):
blanks = '_'
while not state :
guess = input('Enter a letter : ')
guess.lower()
for position in range(len(chosen_word)) :
letter = chosen_word[position]
if letter == guess :
blanks[position] = letter
print(blanks)
if '_' not in blanks :
state = True
print('Youy Won !')
if guess not in letter :
lives -= 1
print(stages[lives])
if lives == 0 :
state = True
print('You Lose !')
我的問題是為什么即使選擇的字母是真的,它也會繼續列印階段串列?
uj5u.com熱心網友回復:
你的問題是if guess not in letter:。您簽入guess了錯誤的元素。
它一定要是if guess not in chosen_word:
就這樣。
break或者,當您發現匹配時,您應該退出 ( ) 回圈letter- 但您將回圈運行到最后 - 因此您將新值分配給letter,最后它的最后一個字母chosen_word與guess.
但這只會取代第一個letter匹配guess并跳過其他 - 即。apple如果您選擇p它只會匹配第一個p并跳過第二個-p所以第一個版本更好。
for position, letter in enumerate(chosen_word):
if letter == guess :
blanks[position] = letter
break # <--- exit loop when found letter
如果您使用print()查看變數中的內容,那么您應該看到錯誤。
你也有錯誤的縮進。
帶有一些小改動的完整作業代碼。
import random
stages = ['''
---
| |
O |
/|\ |
/ \ |
|
=========
''', '''
---
| |
O |
/|\ |
/ |
|
=========
''', '''
---
| |
O |
/|\ |
|
|
=========
''', '''
---
| |
O |
/| |
|
|
=========''', '''
---
| |
O |
| |
|
|
=========
''', '''
---
| |
O |
|
|
|
=========
''', '''
---
| |
|
|
|
|
=========
''']
words = ['peter','apple','dentist']
chosen_word = random.choice(words)
print(chosen_word)
blanks = ['_'] * len(chosen_word)
lives = 6
state = False
while not state :
guess = input('Enter a letter : ')
guess = guess.lower()
for position, letter in enumerate(chosen_word):
if letter == guess :
blanks[position] = letter
print(blanks)
if '_' not in blanks:
state = True
print('Youy Won !')
if guess not in chosen_word:
lives -= 1
print(stages[lives])
if lives == 0:
state = True
print('You Lose !')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/444665.html
