K
K
Konstantin2021-11-09 20:24:59
pygame
Konstantin, 2021-11-09 20:24:59

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:
618aaec7e2497335606533.png

How to implement such a grid using the Pygame library?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Chetchasov, 2022-02-28
@TalismanChet

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
#

If, in addition to all arguments, you pass a variable or a value that is NOT equal to 0 or False, then instead of the surface you will get the coordinates where to draw. This can be useful for optimization, if the game needs to be optimized, then use not the finished leveled surface, but coordinates, and after adding them to the main coordinates of the cell, draw.
3. implementation of finding a cell by coordinate
Everything is simple here.
x = mx // cw
y = my // ch
,
where mx, my are the click coordinates, and cw, ch are the width and height of the cell.
Good luck with development!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question