如何在Pygame中通过一系列函数在屏幕上显示单词

2024-10-05 11:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为我有两个问题:

  1. chooseTheme()中,返回语句或按键代码都不起作用。

  2. randWord()函数在while not done主函数中不会停止,它会保持单词列表的随机性。

打印chooseTheme()中的消息。你知道吗

我分别运行了22-27行,它打印出一个单词,这就是我想要的。你知道吗

当尝试randWord("Nations")而不是randWord(chooseTheme())时,文本会显示出来,但它会遍历所有单词,而不是只选择一个。你知道吗

import random
import pygame


pygame.init()

display_width = 1102
display_height = 625

moccasin = (255, 228, 181)
BLACK = (0, 0, 0)

screen = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Hangman")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 25)
background = pygame.image.load("world_map.jpg")


def randomWord(theme):
    if theme == "Nations":
        with open("countries_europe.txt") as f:
            word_list = ""
            for word in f:
                word_list = word_list + word
            f.close()
            x = random.choice(word_list.split())
            screen_word = font.render(x, True, BLACK)
            screen.blit(screen_word, [display_width/2, display_height/2])
    elif theme == "Capitals":
        with open("capitals_europe.txt") as f:
            word_list = ""
            for word in f:
                word_list = word_list + word
            f.close()
            x = random.choice(word_list.split())
            screen_word = font.render(x, True, BLACK)
            screen.blit(screen_word, [display_width/2, display_height/2])


def chooseTheme():
    category_text = font.render("Choose a theme:  NATIONS [N] CAPITALS [C]", True, BLACK)
    screen.blit(category_text, (200, display_height/2))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_n:
                return "Nations"
            elif event.key == pygame.K_c:
                return "Capitals"


done = False

while not done:
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    randomWord(chooseTheme())

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

当按下N或C键时,“选择主题:”问题将消失,屏幕上将从其中一个.txt文件打印一个随机单词。你知道吗


Tags: eventtruedisplaywidththeme单词screenpygame
1条回答
网友
1楼 · 发布于 2024-10-05 11:43:22

您应该避免多次调用pygame.event.get(),因为每次调用都会从队列中删除所有事件,因此后续调用不会“看到”刚刚删除的事件。你知道吗

另外,一旦你按下一个键,你就会在randomWord函数中呈现随机词,但它会在下一帧中立即被透支。您必须跟踪游戏的状态(例如,在下面的代码中,认为您的游戏处于ChooseTheme状态或Word状态)。你知道吗

下面是使用sprite的方法(你不必这么做,但它们很有用)。注意代码中的注释。你知道吗

import random
import pygame
import pygame.freetype

pygame.init()

MOCASSIN = (255, 228, 181)
BLACK = (0, 0, 0)

screen = pygame.display.set_mode((1102, 625))
pygame.display.set_caption("Hangman")
clock = pygame.time.Clock()

# let's use freetype instead of font 
# because freetype is just better in every way
FONT = pygame.freetype.SysFont(None, 25)

# let's use a solid Surface instead of a picture
# so we can run the code without the image
# background = pygame.image.load("world_map.jpg")
background = pygame.Surface(screen.get_rect().size)
background.fill((30, 30, 30))

# we define a dict of the dicts we want to use
# this allows us to easily add new dicts
# also we seperated data from code
THEMES = {
    'Nations': 'countries_europe.txt',
    'Capitals': 'capitals_europe.txt'
}

# let's cache the words so we don't have to read the files over and over again
cached_themes = {}
def get_theme(theme):
    if not theme in cached_themes:
        with open(THEMES[theme]) as f:
            cached_themes[theme] = [data.strip() for data in f.readlines()]
    return cached_themes[theme]


# we use a Sprite so pygame handles the drawing automatically for us
# this sprite handles the theme choosing
class ChooseTheme(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        # we create the message dynamically, so new themes are automatically avaiable
        theme_str = ' '.join(t.upper() + ' [' + t[0].upper() + ']' for t in THEMES)
        self.image =  pygame.Surface(screen.get_rect().size)
        FONT.render_to(self.image, (50, 50), 'Choose a theme: ' + theme_str, MOCASSIN)
        self.rect = self.image.get_rect()

    def update(self, events):
        for event in events:
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                for theme in THEMES:
                    if theme[0].upper() == event.unicode.upper():
                        # create a new  Word-sprite
                        # self.groups()[0] is the sprites-group created below
                        self.groups()[0].add(Word(theme))
                        # remove this sprite from the game
                        self.kill()

# this sprite handles the displaying of a random word
class Word(pygame.sprite.Sprite):
    def __init__(self, theme):
        super().__init__()
        self.word = random.choice(get_theme(theme))
        self.image = pygame.Surface(screen.get_rect().size)
        FONT.render_to(self.image, (50, 50), self.word, MOCASSIN)
        self.rect = self.image.get_rect()


def main():
    # we use a sprite group to handle updating and drawing
    # since we put all the game logic into the sprites,
    # we probably don't have to touch the main loop again
    sprites = pygame.sprite.Group(ChooseTheme())
    while True:
        # handle events
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                return

        # update gamestate
        sprites.update(events)

        # draw everything
        screen.blit(background, (0, 0))
        sprites.draw(screen)
        pygame.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()
    pygame.quit()

相关问题 更多 >

    热门问题