可以通过以下步骤实现:
import pygame
from pygame.locals import *
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Interactive Polygons")
class Button:
def __init__(self, vertices, color, action):
self.vertices = vertices
self.color = color
self.action = action
def draw(self):
pygame.draw.polygon(screen, self.color, self.vertices)
def check_collision(self, mouse_pos):
if pygame.mouse.get_pressed()[0]:
if pygame.draw.polygon(screen, self.color, self.vertices).collidepoint(mouse_pos):
self.action()
def button1_action():
print("Button 1 clicked!")
def button2_action():
print("Button 2 clicked!")
button1 = Button([(100, 100), (200, 100), (200, 200), (100, 200)], (255, 0, 0), button1_action)
button2 = Button([(300, 100), (400, 100), (400, 200), (300, 200)], (0, 255, 0), button2_action)
running = True
while running:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == QUIT:
running = False
mouse_pos = pygame.mouse.get_pos()
button1.check_collision(mouse_pos)
button2.check_collision(mouse_pos)
button1.draw()
button2.draw()
pygame.display.update()
pygame.quit()
这样,你就可以在Pygame中创建多个交互式多边形按钮了。每个按钮都有自己的形状、颜色和动作函数。当鼠标点击按钮时,相应的动作函数将被调用。你可以根据需要自定义按钮的形状、颜色和动作函数。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云