import pygame
from color import Color
from random import randint
···
class Button:
def init(self, x, y, width, height, text='', background_color=Color.red, text_color=Color.white):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.background_color = background_color
self.text_color = text_color
self.font_size = 30
def show(self, window):
pygame.draw.rect(window, self.background_color, (self.x, self.y, self.width, self.height))
font = pygame.font.SysFont('Times', self.font_size)
text = font.render(self.text, True, self.text_color)
w, h = text.get_size()
x = self.width / 2 - w / 2 + self.x
y = self.height / 2 - h / 2 + self.y
window.blit(text, (x, y))
def is_cliecked(self, pos):
x, y = pos
return (self.x <= x <= self.x + self.width) and (self.y <= y <= self.y + self.height)
def main():
pygame.init()
window = pygame.display.set_mode((400, 600))
pygame.display.set_caption('事件')
window.fill(Color.white)
# add_btn(window)
add_btn = Button(100, 100, 100, 50, 'del')
add_btn.show(window)
btn2 = Button(100, 250, 100, 60, 'Score', background_color=Color.yellow, text_color=Color.black)
btn2.show(window)
pygame.display.flip()
is_move = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mx, my = event.pos
if add_btn.is_cliecked(event.pos):
print('删除!')
continue
if btn2.is_cliecked(event.pos):
# print('hello')
btn2.text = str(randint(0, 100))
btn2.show(window)
pygame.display.update()
continue
···