Python中Hangman游戏中的无限循环

时间:2016-07-04 15:10:36

标签: python infinite-loop

我正在尝试构建一个简单的Hangman游戏,但是当用户输入的字母不是要猜测的单词(它无限期地打印"*")时,以下程序会创建一个无限循环。这里缺少什么?任何建议将不胜感激。

import re
import random

folder = open("datas.txt","r")
data = folder.read()

word_list = re.sub("[^\w]"," ", data).split()
chosen_word = random.choice(word_list)

letter_player = input('enter a letter pls:\n')

continue_game = False

masked_word = []
for letter in chosen_word:
masked_word.append("*")

found_letters = []

def guess_letter():
for letter in range(0,len(chosen_word)):
    if letter_player == chosen_word[letter]:
        found_letters.append(letter_player)
        masked_word[letter] = letter_player

    else:
        masked_word[letter] = '*'
        print(masked_word[letter])

return found_letters

str_found_letters = ''.join(found_letters)
print(str_found_letters)

if(str_found_letters != chosen_word):
    continue_game = True

while continue_game:
   guess_letter()

2 个答案:

答案 0 :(得分:1)

当有其他人回答时,为什么不再发出另一个尝试,OP可以继续?所以这里另一个版本修复了后续迭代中先前找到的字母的覆盖错误。另外,在列表中找到的字母的附加可能是人们想要的,或者可能不是o foo将被附加两次。

#Python 3/2,导入和文字:

from __future__ import print_function
import re
import random

MASK_CHAR = '*'

#从文件中读取单词并随机选择:

def read_game_data(source="datas.txt"):
    """Randomly select a word from source data."""

    with open(source, "r") as f_data:
        return random.choice(re.sub("[^\w]", " ", f_data.read()).split())

#构建构成单词的字母序列(此处列出)或"掩码"

def build_word_seq(a_word, a_mask=None):
    return [letter if not a_mask else a_mask for letter in a_word]

#核心评估函数(以前称为guess_letter)

def evaluate_letter(chosen_word, masked_word, letter_player, found=None):
    if found is None:
        found = set()
    for pos in range(len(chosen_word)):
        if letter_player == chosen_word[pos]:
            found.add(letter_player)
            masked_word[pos] = letter_player
    return masked_word, found

#替换continue_game变量的函数:

def not_ready(chosen_word, masked_word):
    """Evaluate."""
    return True if masked_word != chosen_word else False

#将业务放在main函数中,最小化全局:

def main():
    """Do the game."""
    chosen_word = build_word_seq(read_game_data())
    mask = build_word_seq(chosen_word, a_mask=MASK_CHAR)
    found_letters = set()
    while not_ready(chosen_word, mask):
        letter_player = input('enter a letter pls:\n')
        mask, found_letters = evaluate_letter(
            chosen_word, mask, letter_player, found_letters)
        print(''.join(mask))
        if found_letters:
            print("LettersFound: %s" % (sorted(found_letters),))


if __name__ == '__main__':
    main()

基于datas.txt文件的典型运行:

foo bar baz
yes
no

产生例如:

$ python3 hangman_again_inf_loop.py 
enter a letter pls:
f
***
enter a letter pls:
y
***
enter a letter pls:
b
b**
LettersFound: ['b']
enter a letter pls:
a
ba*
LettersFound: ['a', 'b']
enter a letter pls:
r
bar
LettersFound: ['a', 'b', 'r']

循环可能是无限的(如果你猜对不对; - )

对于一个刽子手游戏,应该有一些等效的计数逻辑,其中猜测与逐行绘制的刽子手竞争......

当使用python v2时,上面的代码仍然需要通过raw_input()替换input()...但是OP使用了print()而没有将来导入,因此它是合理的,Python v3解决方案是很好的nuff。 / p>

快乐的黑客攻击!

答案 1 :(得分:0)

因此,最大的问题是continue_game变量的范围。因为它是在函数之外声明的。 “while continue_game”总是评估相同的内容。

要解决此问题,请在方法定义中添加global continue_game

下面是将突破循环的代码。为了测试我用一个单词和当前逻辑创建了一个datas.txt文件,你必须按照那个顺序输入单词str_found_letters != chosen_word才能达到其他条件

import re
import random

folder = open("datas.txt","r")
data = folder.read()

word_list = re.sub("[^\w]"," ", data).split()
chosen_word = random.choice(word_list)

found_letters = []
continue_game = True

masked_word = []
for letter in chosen_word:
    masked_word.append("*")

def guess_letter():

    global continue_game, chosen_word, found_letters, masked_word

    letter_player = raw_input('enter a letter pls: ')

    for letter in range(0,len(chosen_word)):
        if letter_player == chosen_word[letter]:
            found_letters.append(letter_player)
            masked_word[letter] = letter_player
        else:
            masked_word[letter] = '*'
            print(masked_word[letter])

    str_found_letters = ''.join(found_letters)
    print(str_found_letters)

    if(str_found_letters != chosen_word):
        continue_game = True
    else:
        continue_game = False

while continue_game:
   guess_letter()