点击矩形按钮(pygame主菜单)



我目前是pygame的新手,想知道如何编写矩形的位置,以便打印"开始">

到目前为止,我的循环是

def game_intro():
while True:
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:
mx, my = pygame.mouse.get_pos()

我对矩形的定位和大小是

rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)
rect3 = pygame.Rect(300,500,205,80)

由于已将rects定义为单独的变量,因此可以通过调用事件循环中的pygame.Rect.collidepoint方法来检查特定rects是否与鼠标位置冲突:

def game_intro():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:  # 1 = left button, 2 = middle, 3 = right.
# `event.pos` is the mouse position.
if rect1.collidepoint(event.pos):
print('Start')

如果列表中只有rects(按钮(,而按钮没有单独的变量,则必须为每个按钮分配一个回调函数,使用for循环迭代按钮,检查是否发生冲突,然后调用回调函数(请参阅本答案的附录1和附录2(。

您应该为按钮创建一个单独的函数:

def button(x, y, w, h, inactive, active, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
gameDisplay.blit(active, (x, y))      #Images are a bit easier to use
if click[0] == 1 and action is not None:
print("start")
else:
gameDisplay.blit(inactive, (x, y))

完成后,你可以这样称呼它:

#For Example
button(100, 350, 195, 80, startBtn, startBtn_hover, game_loop)

以下是每个参数的含义:

  • x:x按钮坐标
  • y: 按钮的y坐标
  • w: 按钮宽度
  • h: 按钮高度
  • 活动:鼠标悬停在按钮上时按钮的图片
  • inactive:按钮空闲时的图片

最新更新