Pygame: Snap-to-grid/board 在国际象棋中
Pygame: Snap-to-grid/board in chess
pygame 中有没有一种方法可以让精灵在拖动时捕捉到不可见(或可见)的网格?有点像拖放?如果是这样,如何?我一直在尝试做一些精灵重叠,但是为每条网格线制作一个 if 语句太乏味了。那么我怎样才能制作一个对齐网格的拖放精灵呢?这是一个国际象棋程序。我会感谢你的帮助。
使用 for 循环制作棋盘角的数组。
corners = []
for x in range(edgeRight, edgeLeft, interval):
for y in range(edgeTop, edgeBottom, interval):
corners.append((x,y))
然后,制作一个事件侦听器。当这件作品被拖来拖去时,将这段代码插入到你拥有的任何 while
语句中:
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
我不知道您的实际代码是什么,但这应该能让您有所了解。同样,pygame
没有对齐网格功能。
所以这可以通过使用 python 中的 round 函数非常简单地完成。
sprite.rect.x = ((round(sprite.rect.x/gridSquareSize))*gridSquareSize)
sprite.rect.y = ((round(sprite.rect.y/gridSquareSize))*gridSquareSize)
这会通过将精灵的坐标四舍五入到最近的网格正方形来操纵 round 函数。
pygame 中有没有一种方法可以让精灵在拖动时捕捉到不可见(或可见)的网格?有点像拖放?如果是这样,如何?我一直在尝试做一些精灵重叠,但是为每条网格线制作一个 if 语句太乏味了。那么我怎样才能制作一个对齐网格的拖放精灵呢?这是一个国际象棋程序。我会感谢你的帮助。
使用 for 循环制作棋盘角的数组。
corners = []
for x in range(edgeRight, edgeLeft, interval):
for y in range(edgeTop, edgeBottom, interval):
corners.append((x,y))
然后,制作一个事件侦听器。当这件作品被拖来拖去时,将这段代码插入到你拥有的任何 while
语句中:
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
我不知道您的实际代码是什么,但这应该能让您有所了解。同样,pygame
没有对齐网格功能。
所以这可以通过使用 python 中的 round 函数非常简单地完成。
sprite.rect.x = ((round(sprite.rect.x/gridSquareSize))*gridSquareSize)
sprite.rect.y = ((round(sprite.rect.y/gridSquareSize))*gridSquareSize)
这会通过将精灵的坐标四舍五入到最近的网格正方形来操纵 round 函数。