繁体   English   中英

如何使用星号创建 python 刽子手游戏

[英]How to create a python hangman game using asterisks

我迷失在这个编程任务上。 我应该制作一个刽子手游戏,从文本文件中随机生成一个单词(使用 FileIO),并提示用户一次猜测一个字母,单词中的每个字母都显示为星号。 当用户做出正确的猜测时,就会显示实际的字母。 然后当用户完成一个单词时,它会显示未命中的数量,并询问用户是否继续玩另一个单词。

这就是我到目前为止所拥有的。 我不知道下一步该做什么。 请帮忙!

import random 
hiddenWordList = []
words = []

def pick_word(infile):
    with open(infile) as f:
        contents_of_file = f.read()
    lines = contents_of_file.splitlines()
    line_number = random.randrange(0, len(lines))
    return lines[line_number]


def words():

    return(pick_word("vocab.txt"))

这是可能有用的东西的骨架。

def show_word(word, guessed_letters):
    guessed_letters = set(map(str.casefold, guessed_letters))
    # this is required for this minimal example, but will be a performance hit
    # better to do this when you insert the new guess into "guessed_letters"

    sanitized_word = ''.join([ch if ch.casefold() in guessed_letters else '*' for ch in word])
    print(sanitized_word)

你可以把它写得更迫切:

from typing import Set

def show_word_explained(word: str, guessed_letters: Set[str]):
    # assume for this example that we've already casefolded all the letters in
    # guessed_letters.

    result = ''
    for letter in word:
        if letter.casefold() in guessed_letters:
            result += letter
        else:
            result += '*'
    print(result)

不过,对于有经验的 Python 程序员来说,这性能较差且难以阅读。


您还可以通过不每次将整个文件读入 memory 来改进您的pick_word function。 要么通读一遍并将其保存在 memory 中以运行您的应用程序(这会花费更多内存),要么根本不将其保存在 memory 中并读取文件两次——一次获取长度,然后再次选择文件想要(这需要更多时间)

import random
from functools import lru_cache

@lru_cache(maxsize=1)
def word_list_store_in_memory(infile):
    """
    Reads a file into memory, storing it in an least recently used cache
    """
    with open(infile) as f:
        return [word.strip() for word in f.readlines()]

def get_single_word_from_memory(infile):
    word_list = word_list_store_in_memory(infile)
    return random.choice(word_list)

def get_single_word_from_disk(infile):
    with open(infile) as f:
        num_words = len(f)
    needle = random.randrange(num_words)
    with open(infile) as f:
        # skip the lines before the selected word
        for _ in range(needle):
            next(f)
        # return the next one
        return next(f)

一旦你选择了一个随机词(你似乎有一个句柄),你应该在一个单独的 function 中完成游戏,它返回用户找到该词后的失败尝试次数。 然后创建一个调用 function 的 while 循环会更容易,打印结果并要求用另一个词继续:

示例游戏 function:

def hang(word):
    tried = set()
    while not tried.issuperset(word):
        print("".join(f"*{c}"[c in tried] for c in word))
        c = input("Enter a letter : ")
        if c in tried or len(c)!=1 or c<"a" or c>"z":
            print("invalid letter")
            continue
        if c not in word: print(f"Letter '{c}' not in word")
        tried.add(c)
    return len(tried.difference(word))

主循环示例:

more = "y"
while more == "y":
    word = pickRandomWord()
    missCount = hang(word)
    print(f"{missCount} missed attempts")
    more = input("Try another word ? (y/n) ")

样品运行:

********
Enter a letter : e
e*e*****
Enter a letter : l
ele*****
Enter a letter : p
elep****
Enter a letter : r
Letter 'r' not in word
elep****
Enter a letter : m
Letter 'm' not in word
elep****
Enter a letter : n
elep**n*
Enter a letter : t
elep**nt
Enter a letter : a
elep*ant
Enter a letter : h
2 missed attempts
Try another word ? (y/n) n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM