Henry
Henry

Reputation: 88

Pygame: Snap-to-grid/board in chess

Is there a way in pygame for sprites, when dragged, to snap to an invisible (or visible) grid? Kinda like drag 'n drop? If so, how? I've been trying to do some sprite overlap, but it's too tedious to make an if-statement for each of the grid-lines. So how can I make a snap-to-grid drag-n-drop sprite? This is for a chess program. I'll appreciate your help.

Upvotes: 1

Views: 1561

Answers (2)

Tom Rosewell
Tom Rosewell

Reputation: 21

So this can be done quite simply by using the round function in python.

sprite.rect.x = ((round(sprite.rect.x/gridSquareSize))*gridSquareSize)
sprite.rect.y = ((round(sprite.rect.y/gridSquareSize))*gridSquareSize)

This manipulates the round function, by rounding your sprite's coordinates to the nearest grid square.

Upvotes: 2

bcdan
bcdan

Reputation: 1428

Make an array of corners of the chess board using for loops.

corners = []
for x in range(edgeRight, edgeLeft, interval):
  for y in range(edgeTop, edgeBottom, interval):
    corners.append((x,y))

Then, make an event listener. When the piece is being dragged around, insert this code into whatever while statement you have:

px, py = Piece.Rect.topleft //using tuples to assign multiple vars
for cx, cy in corners:
  if math.hypot(cx-px, cy-py) < distToSnap:
    Piece.setPos((cx,cy))
    break

I have no idea what your actual code is, but this should give you an idea. Again, pygame has no snap-to-grid functionality.

Upvotes: 2

Related Questions