我在pygame中被分配了一个作业问题,以制作两个矩形,一个红色,一个绿色,当单击时,出现显示按钮颜色名称的文本,我已经成功创建了形状,但是我没有不知道如何在单击按钮时使文本显示。感谢您的帮助
我已经使用pygame.draw.rect()函数成功绘制了两个矩形,并且调用了pos = pygame.mouse.get_pos()以便为用户的鼠标获取x和y值。
pos = pygame.mouse.get_pos()
x = pos[0]
y = pos[1]
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, [100, 300, 200, 200])
pygame.draw.rect(screen, RED, [400, 300, 200, 200])
pygame.display.flip()
clock.tick(60)
结果是在屏幕中央有两个矩形,一个绿色,一个红色。
答案 0 :(得分:1)
要验证oyu是否按下了鼠标按钮,可以使用pygame.mouse.get_pressed()
:
leftClicked = pygame.mouse.get_pressed()[0]
对于文本渲染,您可以使用pygame.font
或pygame.pygame.freetype
。 e。 g:
import pygame.freetype
font = pygame.freetype.SysFont('Times New Roman', 30)
为每个按钮定义pygame.Rect
:
rect_green = pygame.Rect(100, 300, 200, 200)
rect_red = pygame.Rect(400, 300, 200, 200)
通过.collidepoint()
来验证是否按下了鼠标按钮,并且鼠标光标位于按钮上。例如:
pygame.draw.rect(screen, GREEN, rectGreen)
if leftClicked and rectGreen.collidepoint(pos):
text_surf, text_rect = font.render("GREEN", WHITE, size=30)
text_rect.center = rectGreen.center
screen.blit(text_surf, text_rect)
请参见简短示例:
import pygame
import pygame.freetype
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
pygame.init()
size = (800,600)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
font = pygame.freetype.SysFont('Times New Roman', 30)
rect_green = pygame.Rect(100, 300, 200, 200)
rect_red = pygame.Rect(400, 300, 200, 200)
def DrawButton(surf, cursor_pos, pressed, rect, color, text_color, text):
pygame.draw.rect(surf, color, rect)
if pressed and rect.collidepoint(cursor_pos):
text_surf, text_rect = font.render(text, text_color, size=30)
text_rect.center = rect.center
screen.blit(text_surf, text_rect)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pos = pygame.mouse.get_pos()
x = pos[0]
y = pos[1]
leftClicked = pygame.mouse.get_pressed()[0]
screen.fill(WHITE)
DrawButton(screen, pos, leftClicked, rect_green, GREEN, BLACK, "GREEN")
DrawButton(screen, pos, leftClicked, rect_red, RED, BLACK, "RED")
pygame.display.flip()
clock.tick(60)
pygame.quit()