我正在使用pygame在python中创建一个完全可定制的enigma机器。我决定尽早实施的一件事是帮助功能。当我对此进行测试时,控制台上不会显示任何内容。这是图片点击的代码(不是全部代码)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
if img.get_rect().collidepoint(x, y):
print('test')
我如何进行这项工作?所有帮助都会有用。
答案 0 :(得分:1)
调用img.get_rect()
时,会创建一个pygame.Rect
,其图像大小/表面大小和默认topleft
坐标(0,0),即您的矩形位于顶部屏幕的左上角。我建议在程序开始时为img创建一个rect实例,并将其用作blit位置并用于碰撞检测。您可以将topleft
,center
,x, y
等作为参数直接传递给get_rect
:rect = img.get_rect(topleft=(200, 300))
。
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
img = pg.Surface((100, 50))
img.fill((0, 100, 200))
# Create a pygame.Rect with the size of the surface and
# the `topleft` coordinates (200, 300).
rect = img.get_rect(topleft=(200, 300))
# You could also set the coords afterwards.
# rect.topleft = (200, 300)
# rect.center = (250, 325)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
if rect.collidepoint(event.pos):
print('test')
screen.fill(BG_COLOR)
# Blit the image/surface at the rect.topleft coords.
screen.blit(img, rect)
pg.display.flip()
clock.tick(60)
pg.quit()