如何向“按钮”添加动作?
How to add action to `Button`?
我在我的游戏中添加了类 'Button',但我不知道如何实现它们。我应该怎么做才能让我的程序正常运行而不出错?
class Button2(pygame.sprite.Sprite):
def __init__(self, width, height):
#[...]
def draw(self, x, y, message, action = None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x < mouse[0] < x + self.width and y < mouse[1] < y + self.height:
pygame.draw.rect(screen, self.active_color, (x, y, self.width, self.height))
if click[0] == 1:
if action is not None:
action()
else:
pygame.draw.rect(screen, self.inactive_color, (x, y, self.width, self.height))
print_text_5(message, x + 10, y + 10)
def game():
Game = True
while Game:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
player.jump()
elif event.key == K_p:
pause()
elif event_key == K_k:
Game = False
Begining = True
while Begining:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
Begining = False
mini_button = Button2(180, 120)
screen.blit(important_phone_jpg, important_phone_rect)
print_text_5('Welcome to my game!', 300, 50)
mini_button.draw(570, 200, 'PLAY')
mini_button.draw(570, 420, 'QUIT')
pygame.display.update()
你应该在 clock.tick(FPS)
之后留出空格
Game = True
while Game:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
player.jump()
elif event.key == K_p:
pause()
elif event_key == K_k:
Game = False
我在我的游戏中添加了类 'Button',但我不知道如何实现它们。我应该怎么做才能让我的程序正常运行而不出错?
class Button2(pygame.sprite.Sprite):
def __init__(self, width, height):
#[...]
def draw(self, x, y, message, action = None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x < mouse[0] < x + self.width and y < mouse[1] < y + self.height:
pygame.draw.rect(screen, self.active_color, (x, y, self.width, self.height))
if click[0] == 1:
if action is not None:
action()
else:
pygame.draw.rect(screen, self.inactive_color, (x, y, self.width, self.height))
print_text_5(message, x + 10, y + 10)
def game():
Game = True
while Game:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
player.jump()
elif event.key == K_p:
pause()
elif event_key == K_k:
Game = False
Begining = True
while Begining:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
Begining = False
mini_button = Button2(180, 120)
screen.blit(important_phone_jpg, important_phone_rect)
print_text_5('Welcome to my game!', 300, 50)
mini_button.draw(570, 200, 'PLAY')
mini_button.draw(570, 420, 'QUIT')
pygame.display.update()
你应该在 clock.tick(FPS)
之后留出空格 Game = True
while Game:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
player.jump()
elif event.key == K_p:
pause()
elif event_key == K_k:
Game = False