如果我点击第一个菜单上的播放按钮,它应该打开一个菜单供用户选择级别。在我写的代码中,单击播放按钮,计算机也假设我也点击了与水平屏幕中的播放按钮放在同一位置的简易按钮。它直接进入游戏循环。
答案 0 :(得分:1)
当您按住按钮时,可能会使用mouse.get_pressed()
给出True
- 这会产生问题。使用事件MOUSEBUTTONDOWN
时,只有当按钮从"not-pressed"
更改为"pressed"
时才会显示“真”,但是当您按住按钮时则不会。
但大多数情况下,按钮需要进行大量更改,尤其是在一个功能中有按钮时。
使用班级Button
import pygame
# --- constants ---
WIDTH = 320
HEIGHT = 110
FPS = 5
# --- class ---
class Button(object):
def __init__(self, position, size, color, text):
self.image = pygame.Surface(size)
self.image.fill(color)
self.rect = pygame.Rect((0,0), size)
font = pygame.font.SysFont(None, 32)
text = font.render(text, True, (0,0,0))
text_rect = text.get_rect()
text_rect.center = self.rect.center
self.image.blit(text, text_rect)
# set after centering text
self.rect.topleft = position
def draw(self, screen):
screen.blit(self.image, self.rect)
def is_clicked(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
return self.rect.collidepoint(event.pos)
def stage1(screen):
button1 = Button((5, 5), (100, 100), (0,255,0), "GO 1")
button2 = Button((215, 5), (100, 100), (0,255,0), "EXIT")
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
if button1.is_clicked(event):
# go to stage2
stage2(screen)
if button2.is_clicked(event):
# exit
pygame.quit()
exit()
# - draws -
screen.fill((255,0,0))
button1.draw(screen)
button2.draw(screen)
pygame.display.flip()
# - FPS -
clock.tick(FPS)
def stage2(screen):
button1 = Button((5, 5), (100, 100), (255,0,0), "GO 2")
button2 = Button((215, 5), (100, 100), (255,0,0), "BACK")
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
if button1.is_clicked(event):
stage3(screen)
if button2.is_clicked(event):
return
# - draws -
screen.fill((0,255,0))
button1.draw(screen)
button2.draw(screen)
pygame.display.flip()
# - FPS -
clock.tick(FPS)
def stage3(screen):
button2 = Button((215, 5), (100, 100), (0,0,255), "BACK")
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
if button2.is_clicked(event):
return
# - draws -
screen.fill((128,128,128))
button2.draw(screen)
pygame.display.flip()
# - FPS -
clock.tick(FPS)
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# - start -
stage1(screen)
# - end -
pygame.quit()