我正在尝试创建一个pygame程序,以查看用户是否单击了一个矩形,如果是,则更改该矩形的颜色。
这是我绘制屏幕的初始代码:
import pygame
import sys
pygame.init()
size_x = 650
size_y = 550
bkg_colour = 0, 0, 0
white = 255, 255, 255
colour = 0, 130, 90
position_x, position_y = 70, 100
screen = pygame.display.set_mode((size_x, size_y))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(bkg_colour)
for x in range(-50, 500, position_x + 20):
for y in range(-50, 400, position_y + 20):
pygame.draw.rect(screen, colour, (position_x + x, position_y + y, position_x, position_y), 0)
pygame.display.flip()
我尝试做的是像这样使用pygame.Rect和collisionpoint:
for x in range(-50, 500, position_x + 20):
for y in range(-50, 400, position_y + 20):
rect_size = pygame.Rect(position_x + x, position_y + y, position_x, position_y)
pygame.draw.rect(screen, colour, rect_size, 0)
if event.type == pygame.MOUSEBUTTONDOWN:
click = rect_size.collidepoint(pygame.mouse.get_pos())
if click == 1:
print("Clicked")
pygame.draw.rect(screen, white, rect_size, 0)
pygame.display.flip()
但它的作用只适用于屏幕上最后绘制的矩形。 如何使其适用于屏幕上的每个矩形?
答案 0 :(得分:0)
rect_size
一次保存一个值,并一次又一次地覆盖它,直到它保存最后一个矩形。
你想要保存一个矩形列表并检查所有矩形的碰撞。
而不是
rect_size = pygame.Rect(position_x + x, position_y + y, position_x, position_y)
你想做点什么:
rect_sizes.append(pygame.Rect(position_x + x, position_y + y, position_x, position_y))
然后迭代rect_sizes
并检查每个碰撞。
rect_sizes = []
for x in range(-50, 500, position_x + 20):
for y in range(-50, 400, position_y + 20):
rect_size = pygame.Rect(position_x + x, position_y + y, position_x, position_y)
pygame.draw.rect(screen, colour, rect_size, 0)
rect_sizes.append(rect_size)
if event.type == pygame.MOUSEBUTTONDOWN:
for rect_size in rect_sizes:
click = rect_size.collidepoint(pygame.mouse.get_pos())
if click == 1:
print("Clicked")
pygame.draw.rect(screen, white, rect_size, 0)