如何在每次单击子画面时将变量增加1,然后打印变量

zpjtge22  于 2022-10-22  发布在  Python
关注(0)|答案(1)|浏览(207)

我试图在每次点击红色精灵时将变量“clicks”设置为1。然后我需要更新变量,以便打印出更新后的点击次数。
我所尝试的:

import pygame

pygame.init()

WIDTH = 600
HEIGHT = 600

window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Printing")
window.fill((0, 0, 0))
rectangle = pygame.draw.rect(window, [255, 0, 0], [50, 50, 90, 90], 0)
pygame.display.flip()

allsprites = pygame.sprite.Group()
allsprites.add(rectangle)

clicks = 0

for event in pygame.event.get():
    if event.type == pygame.BUTTON_LEFT:
        pos = pygame.mouse.get_pos()
        clicked_sprites = [rectangle for rectangle in allsprites if rectangle.rect.collidepoint(pos)]
        clicks += 1
print(clicks)

# loop

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

pygame.quit()

问题:

allsprites.add(rectangle)

TypeError:无法处理的类型:“pygame.Rect”

wvt8vs2t

wvt8vs2t1#

请参阅如何将对象添加到“pygame.sprite.Group()”?。不能将矩形添加到pygame.sprite.Group()。必须将pygame.sprite.Sprite对象装箱。

class RectSprite(pygame.sprite.Sprite):
    def __init__(self, rect):
        super().__init__() 
        self.rect = pygame.Rect(rect)
        self.image = pygame.Surface(self.rect.size)
        self.image.fill((255, 0, 0))

请参见Pygame鼠标点击检测。您必须检查事件key是否为pygame.MOUSEBUTTONDOWNbuttonBUTTON_LEFT。使用pos属性获取鼠标光标的位置。仅当发现冲突时,才递增clicks

if event.type == pygame.MOUSEBUTTONDOWN:
    if event.button == pygame.BUTTON_LEFT:
        clicked_sprites = [rectangle for rectangle in allsprites if rectangle.rect.collidepoint(event.pos)]
        if clicked_sprites:
            clicks += 1

您必须在应用程序循环中完成所有这些操作。完整示例:

import pygame

pygame.init()

WIDTH = 600
HEIGHT = 600

window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Printing")

class RectSprite(pygame.sprite.Sprite):
    def __init__(self, rect):
        super().__init__() 
        self.rect = pygame.Rect(rect)
        self.image = pygame.Surface(self.rect.size)
        self.image.fill((255, 0, 0))

allsprites = pygame.sprite.Group()
rectangle = RectSprite((50, 50, 90, 90))
allsprites.add(rectangle)

clicks = 0

# loop

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == pygame.BUTTON_LEFT:
                clicked_sprites = [rectangle for rectangle in allsprites if rectangle.rect.collidepoint(event.pos)]
                if clicked_sprites:
                    clicks += 1
                    print(clicks)

    window.fill((0, 0, 0))
    allsprites.draw(window)
    pygame.display.flip()

pygame.quit()

相关问题