Я бы заменил метод create
на метод __init__
, в котором создаются фоновая поверхность, текстовая поверхность и соответствующие им рамки.Это позволяет вам передавать все необходимые параметры во время создания экземпляра:
start_button = Button(10, 10, 300, 100, "Clicky Button!", BLUE)
Используйте параметры для размещения прямоугольника self.button
в нужных координатах:
self.button = pygame.Rect(x, y, w, h)
Вы также можете использоватьget_rect
метод поверхности кнопки для создания прямоугольника (см. создание text_rect
).
Единственная цель метода view
состоит в том, чтобы блицевать поверхности на ихт.
import sys
import pygame
pygame.init()
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 50, 130, 255)
screen_surf = pygame.display.set_mode((500,500), 0, 24)
screen_surf.fill((100,0,0))
clock = pygame.time.Clock()
# No need to recreate the font object all the time.
SYS_FONT = pygame.font.SysFont(None, 25)
class Button():
def __init__(self, x, y, w, h, text, colour):
self.button_surf = pygame.Surface((w,h), 0, 24)
self.button_surf.fill(colour)
self.button = pygame.Rect(x, y, w, h)
self.text_surf = SYS_FONT.render(text, False, (255,255,255))
# Pass the center coords of the button rect to the newly
# created text_rect for the purpose of centering the text.
self.text_rect = self.text_surf.get_rect(center=self.button.center)
def view(self, screen_surf):
screen_surf.blit(self.button_surf, self.button)
screen_surf.blit(self.text_surf, self.text_rect)
# Button() calls the __init__ method.
start_button = Button(10, 10, 300, 100, "Clicky Button!", BLUE)
start_button.view(screen_surf) # Call `view` in a separate line.
exit_button = Button(10, 200, 300, 50, "Exit!", GREEN)
exit_button.view(screen_surf)
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
if start_button.button.collidepoint(event.pos):
print("You opened a chest!")
elif exit_button.button.collidepoint(event.pos):
pygame.quit()
sys.exit()
elif event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
clock.tick(60) # Limit the frame rate to 60 FPS.