gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:11 26 4
gpt4 key购买 nike

我认为我有两个问题:

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

  2. randWord() 函数在未完成 main 的同时不会停止,它会不断随机化单词列表。

打印 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 文件之一打印一个随机单词。

最佳答案

您应该避免多次调用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()

关于python - 如何在Pygame中通过一系列函数在屏幕上显示单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com