pygame - Snap Mouse to Grid
<p>I'm making a little platformer game using pygame, and decided that making a level editor for each level would be easier than typing each blocks' coordinate and size.</p>

<hr>

<p>I'm using a set of lines, horizontally and vertically to make a grid to make plotting points easier.</p>

<p>Here's the code for my grid:</p>

<pre><code>def makeGrid(surface, width, height, spacing):
    for x in range(0, width, spacing):
        pygame.draw.line(surface, BLACK, (x,0), (x, height))
    for y in range(0, height, spacing):
        pygame.draw.line(surface, BLACK, (0,y), (width, y))
</code></pre>

<hr>

<p>I want the user's mouse to move at 10px intervals, to move to only the points of intersection. Here's what I tried to force the mouse to snap to the grid.</p>

<pre><code>def snapToGrid(mousePos):
    if 0 &lt; mousePos[0] &lt; DISPLAYWIDTH and 0 &lt; mousePos[1] &lt; 700:
        pygame.mouse.set_pos(roundCoords(mousePos[0],mousePos[1]))
</code></pre>

<p>(BTW, roundCoords() returns the coordinates rounded to the nearest ten unit.)</p>

<p>(Also BTW, snapToGrid() is called inside the main game loop (while not done))</p>

<p>...but <a href="https://youtu.be/Y_cfBKgNHgQ" rel="nofollow">this</a> happens, the mouse doesn't want to move anywhere else.</p>

<hr>

<p>Any suggestions on how to fix this? If I need to, I can change the grid code too.
Thanks a bunch.</p>

<p><strong>P.S. This is using the latest version of PyGame on 64 bit Python 2.7</strong></p>

<p>First of all I think you're not far off.</p>

<p>I think the problem is that the code runs quite fast through each game loop, so your mouse doesn't have time to move far before being set to the position return by your function. </p>

<p>What I would have a look into is rather than to <code>pygame.mouse.set_pos()</code> just return the snapped coordinates to a variable and use this to blit a marker to the screen highlighting the intersection of interest (here I use a circle, but you could just blit the image of a mouse ;) ). And hide your actual mouse using <code>pygame.mouse.set_visible(False)</code>:</p>

<pre><code>def snapToGrid(mousePos):
    if 0 &lt; mousePos[0] &lt; DISPLAYWIDTH and 0 &lt; mousePos[1] &lt; 700:
        return roundCoords(mousePos[0],mousePos[1])

snap_coord = snapToGrid(mousePos)# save snapped coordinates to variable

pygame.draw.circle(Surface, color, snap_coord, radius, 0)# define the remaining arguments, Surface, color, radius as you need

pygame.mouse.set_visible(False)# hide the actual mouse pointer
</code></pre>

<p>I hope that works for you !</p>

python python-2.7 pygame grid-layout