#The induvidual squares
class Square():
def __init__(self,x,y):
self.x = x
self.y = y
#The grid as a whole
class Grid():
def __init__(self,width,height):
self.squares = []
self.objects = []
self.width = width
self.height = height
def populate(self):
for i in range(1,self.height + 1):
for j in range(1,self.width + 1):
self.squares.append(Square(j,i))
grid = Grid(10,10)
grid.populate()
for i in grid.squares:
grid.objects.append(pygame.Rect((i.x -1) * 50,(i.y - 1) * 50,50,50))
While True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN :
print("HELLO") #Testing to see if it worked
(x,y) = pygame.mouse.get_pos()
for i in grid.objects:
if i.x*50 <= (x) < (i.x+1)*50:
if i.y*50 <= (y) < (i.y+1)*50:
print("hi") #Testing to see if it worked
I have been experimenting with creating grids and using them to make games. I was looking at being able to click on a certain square of my grid and that would cause a change in that square.
This is where I was attempting to get it to register whether I had clicked any squares however it has not been registering whether I have clicked at all. I've looked at other discussions on the topic and none have worked.
The .x
and .y
component of the pygame.Rect
object contain the actual top left position of the rectangle. The multiplication by 50 is wrong:
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN :
print("HELLO") #Testing to see if it worked
x, y = pygame.mouse.get_pos()
for obj_rect in grid.objects:
if obj_rect.x <= x < obj_rect.x+50:
if obj_rect.y <= y < obj_rect.y+50:
print("hi") #Testing to see if it worked
Anyway I recommend to simplify the code and to use collidepoint
x, y = pygame.mouse.get_pos()
for obj_rect in grid.objects:
if obj_rect.collidepoint((x, y)):
print("hi") #Testing to see if it worked
See also How to detect collisions between two rectangular objects or images in the pygame
I've found a fix which is related to me having another
for event in pygame.event.get()
in the same while loop. This event check was used to detect whether I had tried to exit the window. It seems that pygame has an issue with having two event checks in the same loop, possibly related to them using the same variable name , either way, I moved my check into the same for loop and it now works
while True:
for event in pygame.event.get():
print(event)
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN :
print("HELLO")
x, y = pygame.mouse.get_pos()
for obj_rect in grid.objects:
if obj_rect.collidepoint((x, y)):
print("hi") #Testing to see if it worked
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.