title: Python: How to make drawn elements snap to grid in pygame
body: <p>I am experimenting with a Pathfinding project and got stuck while creating a working GUI. I'm using pygame and already created a grid and a feature, which draws cubes when you press (or keep pressing) the mouse-button. However, these cubes just go wherever you click, and do not snap to the grid. I thought about using modulo somehow but I cannot seem to get it to work. Please find the code attached below. The Cube class is what I use for the squares drawn on the screen. Moreover, the <code>drawgrid()</code> function is how I set up my grid. I'd love some help on this, as I've been stuck on this roadblock for three days now.</p>
  <pre class="lang-py prettyprint-override"><code>class Cube:
      def update(self):
          self.cx, self.cy = pygame.mouse.get_pos()
          self.square = pygame.Rect(self.cx, self.cy, 20, 20)
  
      def draw(self):
          click = pygame.mouse.get_pressed()
          if click[0]:  # evaluate left button
              pygame.draw.rect(screen, (255, 255, 255), self.square)
  </code></pre>
  <p>Other <code>drawgrid()</code> function:</p>
  <pre class="lang-py prettyprint-override"><code>def drawgrid(w, rows, surface):
      sizebtwn = w // rows  # Distance between Lines
      x = 0
      y = 0
      for i in range(rows):
          x = x + sizebtwn
          y = y + sizebtwn
          pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w))
          pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y))
  </code></pre>