【发布时间】:2021-06-24 17:06:08
【问题描述】:
构建一个简单的 Pygame,在你点击开始按钮后进入关卡 1;一扇门出现,通过点击门它调用包含游戏第二级代码的函数。但是当点击门按钮时,该函数会被快速调用,然后它会返回到第 1 级。我该如何解决这个问题?仅包含相关代码:(游戏循环、关卡功能和按钮类。
main_menu = True
class Button():
def __init__(self,x,y,image):
self.image = image
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.clicked = False
def draw(self):
action = False
#get mouse position
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
action = True
self.clicked = True
if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
#draw Button
screen.blit(self.image, self.rect)
return action
#create buttons
start_button = Button(screen_width // 2 -350, screen_height // 2, start_img)
cancel_button = Button(screen_width // 2 + 150, screen_height // 2, cancel_img)
closed_door_button = Button(370,0,closedDoor)
def level1():
draw_bg()
player.draw()
draw_oMG()
if player.rect.x >= 440 and player.rect.x <= 460 and player.rect.y >= 30 and player.rect.y <=80:
draw_oMGM1()
def level2():
draw_house()
player.draw()
running = True
while running:
if main_menu == True:
if start_button.draw():
main_menu = False
if cancel_button.draw():
running = False
else:
level1()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player.rect.x>5:
player.face = "left"
player.facing()
player.rect.x -= 5
if keys[pygame.K_RIGHT] and player.rect.x<790:
player.face = "right"
player.facing()
player.rect.x += 5
if keys[pygame.K_UP] and player.rect.y>10:
player.face = "up"
player.facing()
player.rect.y -= 5
if keys[pygame.K_DOWN]and player.rect.y<395:
player.face = "down"
player.facing()
player.rect.y += 5
if closed_door_button.draw():
level2()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
pygame.quit()
【问题讨论】:
-
如果我发布的答案有帮助,您可以考虑accepting。否则,发表评论,我会改变我的答案。
标签: python button pygame pygame-surface