我正在使用pygame在python中创建一个完全可定制的谜机。我很早就决定实现一个帮助函数。当我测试这个的时候,控制台上什么也不会出现。下面是图像单击的代码(不是所有代码)

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')

我该怎么做?所有的帮助都是有用的。

最佳答案

当您调用img.get_rect()时,您将创建一个具有图像/曲面大小和默认pygame.Rect坐标(0,0)的topleft,即您的矩形位于屏幕的左上角。我建议在程序开始时为img创建一个rect实例,并将其用作blit位置和碰撞检测。您可以直接将topleftcenterx, y等坐标作为参数传递给get_rectrect = 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()

关于python - 点击图片将不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51804863/

10-10 08:49