主菜单帮助(pygame)



我已经创建了鼠标点击功能,当我点击这些按钮时,可以打印(开始、选项等等(。我只是不知道点击这些按钮后如何进入下一阶段,真正打开一个新页面。我试着在点击按钮时进行了一次屏幕填充,但它只会持续几秒钟,按钮就会出现在它的前面。

我对pygame相当陌生。这是我到目前为止的代码,

import pygame
from pygame import *

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
HOVER_COLOR = (50, 70, 90)
#Background Music
pygame.mixer.music.load('game.ogg')
pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
pygame.mixer.music.play()
pygame.display.update()
clock.tick(15)
#Background
bg = pygame.image.load("greybackground.png")

#Fonts
FONT = pygame.font.SysFont ("Times New Norman", 60)

text1 = FONT.render("START", True, WHITE)
text2 = FONT.render("OPTIONS", True, WHITE)
text3 = FONT.render("ABOUT", True, WHITE)
#Buttons
rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)
rect3 = pygame.Rect(300,500,205,80)
buttons = [
[text1, rect1, BLACK],
[text2, rect2, BLACK],
[text3, rect3, BLACK],
]
running = False
def game_intro():
while not running: 
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.MOUSEMOTION:
for button in buttons:
if button[1].collidepoint(event.pos):
button[2] = HOVER_COLOR
else:
button[2] = BLACK
screen.blit(bg, (0, 0))
for text, rect, color in buttons:
pygame.draw.rect(screen, color, rect)
screen.blit(text, rect)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if rect1.collidepoint(event.pos):
screen.fill((0, 0, 0))
elif rect2.collidepoint(event.pos):
print ('options')
elif rect3.collidepoint(event.pos):
print ('about')
if event.type == KEYDOWN:
if (event.key == K_UP):
print ("UP was pressed")
elif (event.key == K_DOWN):
print ("DOWN was pressed")
elif (event.key == K_w):
print ("W was pressed")
elif (event.key == K_s):
print ("S was pressed")
else:
print ("error")


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

game_intro()
pygame.quit()

实际上我自己也做过类似的事情。这是你会放在底部的:

while running:
event = pygame.event.wait()
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
x,y = pygame.mouse.get_pos()
if 300 <= x <= 505 and 300 <= y <= 380:
#change stuff here
running = False
#insert code here / for the next screen

这可以普遍用于每个按钮。如果你需要更多的按钮,只需复制并粘贴第三个If语句,并根据需要进行更改。

不要忘记执行"pygame.display.update(("来刷新屏幕;否则,你将看不到任何变化(这就是发生在我身上的事情(。

我希望这能有所帮助!

最新更新