我正在创建python的游戏问题
python 538
原文标题 :problem with game that I am creating python
我正在创建这个游戏,它只是刽子手游戏,程序从列表中随机选择一个单词,用户从随机选择的单词中猜测一个字母,如果单词不正确,生命计数会减少,直到它耗尽。
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 !')
我的问题是为什么即使选择的字母是真的,它也会继续打印阶段列表?
回复
我来回复-
furas 评论
该回答已被采纳!
你的问题是
if guess not in letter:
。您签入guess
错误的元素。必须
if guess not in chosen_word:
就这样。
或者你应该在找到匹配
letter
时退出(break
)循环 – 但你运行循环到最后 – 所以你为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 !')
2年前