我认为我有两个问题:
在chooseTheme()
中,返回语句或按键代码都不起作用。
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文件打印一个随机单词。你知道吗
您应该避免多次调用
pygame.event.get()
,因为每次调用都会从队列中删除所有事件,因此后续调用不会“看到”刚刚删除的事件。你知道吗另外,一旦你按下一个键,你就会在
randomWord
函数中呈现随机词,但它会在下一帧中立即被透支。您必须跟踪游戏的状态(例如,在下面的代码中,认为您的游戏处于ChooseTheme状态或Word状态)。你知道吗下面是使用sprite的方法(你不必这么做,但它们很有用)。注意代码中的注释。你知道吗
相关问题 更多 >
编程相关推荐