Answer the question
In order to leave comments, you need to log in
How to make a grid for objects in pygame?
There is a game. I would like to implement some kind of grid so that when the left mouse button is pressed, the image position is in the center of the cell on which the mouse button was pressed.
Here's what it should look like:
How to implement such a grid using the Pygame library?
Answer the question
In order to leave comments, you need to log in
Most likely you mean "the image should be aligned" to the center of the cell.
1. implementation of the grid
To create a grid, you don't need much: it's enough to learn how to correctly represent the coordinates. To find the drawing position in the upper-left corner, it is enough to multiply the grid coordinates by the size of 1 cl.
2. implementation of cell center
rendering For cell center rendering, more needs to be done. I wrote a function that returns a surface that should be drawn from the top left of the cell. Perhaps you can figure out how it works. simple geometry)
import pygame
def align_center(cell_width, cell_height, surface_to_align, not_return_surface_but_coords=False):
cw, ch, sf = cell_width, cell_height, surface_to_align
cx, cy = cw//2, ch//2
dx, dy = sf.get_width()//2, sf.get_height()//2
tx, ty = cx-dx, cy-dy
ret = pygame.Surface((cw, ch), pygame.SRCALPHA)
ret.blit(sf, (tx, ty))
if not not_return_surface_but_coords:
return ret
else:
return [tx, ty]
return -1
#
x = mx // cw
y = my // ch
, Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question