简体   繁体   English

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

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

I'm lost on this programming assignment.我迷失在这个编程任务上。 I'm supposed to make a hangman game that randomly generates a word taken from a text file (using FileIO) and prompts the user to guess one letter at a time with each letter in the word is displayed as an asterisk.我应该制作一个刽子手游戏,从文本文件中随机生成一个单词(使用 FileIO),并提示用户一次猜测一个字母,单词中的每个字母都显示为星号。 When the user makes a correct guess, the actual letter is then displayed.当用户做出正确的猜测时,就会显示实际的字母。 Then when the user finishes a word, it will display the number of misses and ask the user whether to continue to play with another word.然后当用户完成一个单词时,它会显示未命中的数量,并询问用户是否继续玩另一个单词。

This is what I have so far.这就是我到目前为止所拥有的。 I don't know what to do next.我不知道下一步该做什么。 Please help!请帮忙!

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"))

Here's a skeleton of something that might work.这是可能有用的东西的骨架。

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)

You could write this a little more imperatively as:你可以把它写得更迫切:

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)

This is less performant and harder to read for an experienced Python programmer, though.不过,对于有经验的 Python 程序员来说,这性能较差且难以阅读。


You could also improve your pick_word function by not reading the whole file into memory each time.您还可以通过不每次将整个文件读入 memory 来改进您的pick_word function。 Either read it through once and hold it in memory for the run of your application (this costs more memory) or never hold it in memory at all and read the file twice -- once to get the length, and again to pick the file you want (this costs more time)要么通读一遍并将其保存在 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)

Once you've selected a random word (which you seem to have a handle on), you should have the gameplay done in a separate function that returns the number of failed attempts after the user found the word.一旦你选择了一个随机词(你似乎有一个句柄),你应该在一个单独的 function 中完成游戏,它返回用户找到该词后的失败尝试次数。 It will then be easier to make a while loop that calls the function, prints the result and asks to continue with a other word:然后创建一个调用 function 的 while 循环会更容易,打印结果并要求用另一个词继续:

Example gameplay function:示例游戏 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))

Example main loop:主循环示例:

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

Sample run:样品运行:

********
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