如何在Pygame中单击并转到另一个页面



所以我写这段代码是为了学校作业,我应该使用pygame并显示一些文本。我把这些文本放在不同的页面上,如果单击屏幕,它将显示下一个屏幕。

以下是我目前所拥有的:

import pygame
pygame.init()
pygame.font.init()
# defining the screen
SIZE = (1000, 700)
screen = pygame.display.set_mode(SIZE)
# define time
clock = pygame.time.Clock()
#define button
button = 0
# define font
fontIntro = pygame.font.SysFont("Times New Roman",30)
# define draw scene
def drawIntro(screen):
#start
if button > 0:
screen.fill((0, 0, 0))
text = fontIntro.render("Sigle click to start", 1, (255,255,255))
screen.blit(text, (300, 300, 500, 500))
pygame.display.flip() 
#page1
if button == 1:
screen.fill((0, 0, 0))
text = fontIntro.render("page 1", True, (255, 255, 255))
pygame.display.flip()
#page2
if button == 1:
screen.fill((0, 0, 0))
text = fontIntro.render("page 2", True, (255, 255, 255))
screen.blit(text, (300,220,500,200))
pygame.display.flip()
#page3
if button == 1:
screen.fill((0, 0, 0))
text = fontIntro.render("page3", True, (255, 255, 255))
screen.blit(text, (200,190,500,200))
pygame.display.flip()

running = True
while running:
for evnt in pygame.event.get():
if evnt.type == pygame.QUIT:
running = False
if evnt.type == pygame.MOUSEMOTION:
mx,my = evnt.pos
print(evnt.pos)
drawIntro(screen)
pygame.quit()

虽然它不起作用,但有人能帮忙吗?!谢谢

您在一开始就定义了button = 0,但在主循环中永远不会更改其值。在drawIntro函数中,您可以选中if button > 0if button == 1很明显,你从来没有执行过任何一个if语句。

您需要通过调用pygame.mouse.get_pressed()来抓住鼠标按钮,并了解如何正确切换到下一页。

顺便说一句,您还有三次if button == 1,我想这不是您想要的,因为if语句在编写时会立即执行,所以您的第3页会立即显示。您需要一些计数器来跟踪下次按下鼠标按钮时需要显示的页面。

当用户按下鼠标按钮时,需要增加button计数器。

drawIntro函数不应在每个pygame.MOUSEMOTION事件的事件循环中调用一次,而应在主while循环中调用。此外,将MOUSEMOTION更改为MOUSEBUTTONDOWN,以使每次单击的button增加一次。

drawIntro函数中的条件语句不正确。

import pygame

pygame.init()
SIZE = (1000, 700)
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
button = 0
fontIntro = pygame.font.SysFont("Times New Roman",30)

def drawIntro(screen):
#start
if button == 0:  # == 0
screen.fill((0, 0, 0))
text = fontIntro.render("Sigle click to start", 1, (255,255,255))
screen.blit(text, (300, 300, 500, 500))
elif button == 1:  #page1
screen.fill((0, 0, 0))
text = fontIntro.render("page 1", True, (255, 255, 255))
screen.blit(text, (300,220,500,200))
elif button == 2:  #page2
screen.fill((0, 0, 0))
text = fontIntro.render("page 2", True, (255, 255, 255))
screen.blit(text, (300,220,500,200))
elif button == 3:  #page3
screen.fill((0, 0, 0))
text = fontIntro.render("page3", True, (255, 255, 255))
screen.blit(text, (200,190,500,200))

running = True
while running:
for evnt in pygame.event.get():
if evnt.type == pygame.QUIT:
running = False
if evnt.type == pygame.MOUSEBUTTONDOWN:  # Once per click.
button += 1
drawIntro(screen)
pygame.display.flip()
pygame.quit()

相关内容

最新更新