📜  如何使用 PyGame 在游戏中创建按钮?

📅  最后修改于: 2022-05-13 01:54:27.200000             🧑  作者: Mango

如何使用 PyGame 在游戏中创建按钮?

Pygame是一个Python库,可专门用于设计和构建游戏。 Pygame 仅支持使用称为 sprite 的不同形状/图像构建的 2D 游戏。 Pygame 并不是特别适合设计游戏,因为它使用起来非常复杂,并且缺乏像统一游戏引擎这样的适当 GUI,但它确实为更大的项目构建了逻辑。

安装

在初始化 pygame 库之前,我们需要安装它。可以使用Python提供的用于其库安装的pip工具将该库安装到系统中。可以通过将这些行写入终端来安装 Pygame。

pip install pygame

使用 pygame 创建可交互按钮

游戏必须具有可交互的按钮,可以控制游戏中的不同事件,以使游戏更加可控,并在其中添加适当的 GUI。这些可以通过在屏幕上创建一个矩形然后在其上叠加指示文本来在 pygame 中创建。为此,我们将使用各种函数,如draw.rect()screen.blit()等。为了增加它的活力,我们可以在鼠标悬停在按钮上时更改按钮的颜色。

这可以通过使用更新鼠标指针的 x 和 y 位置并将其作为元组存储在变量中的函数来完成。然后我们可以将矩形的边界设置为相应的变量,并检查鼠标是否在这些边界中,如果是,块的颜色将更改为较浅的阴影,以指示按钮是可交互的。

下面是实现。

import pygame
import sys
  
  
# initializing the constructor
pygame.init()
  
# screen resolution
res = (720,720)
  
# opens up a window
screen = pygame.display.set_mode(res)
  
# white color
color = (255,255,255)
  
# light shade of the button
color_light = (170,170,170)
  
# dark shade of the button
color_dark = (100,100,100)
  
# stores the width of the
# screen into a variable
width = screen.get_width()
  
# stores the height of the
# screen into a variable
height = screen.get_height()
  
# defining a font
smallfont = pygame.font.SysFont('Corbel',35)
  
# rendering a text written in
# this font
text = smallfont.render('quit' , True , color)
  
while True:
      
    for ev in pygame.event.get():
          
        if ev.type == pygame.QUIT:
            pygame.quit()
              
        #checks if a mouse is clicked
        if ev.type == pygame.MOUSEBUTTONDOWN:
              
            #if the mouse is clicked on the
            # button the game is terminated
            if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
                pygame.quit()
                  
    # fills the screen with a color
    screen.fill((60,25,60))
      
    # stores the (x,y) coordinates into
    # the variable as a tuple
    mouse = pygame.mouse.get_pos()
      
    # if mouse is hovered on a button it
    # changes to lighter shade 
    if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
        pygame.draw.rect(screen,color_light,[width/2,height/2,140,40])
          
    else:
        pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40])
      
    # superimposing the text onto our button
    screen.blit(text , (width/2+50,height/2))
      
    # updates the frames of the game
    pygame.display.update()

输出:

创建按钮-pygame-python