【问题标题】:Pygame: Snap-to-grid/board in chessPygame:国际象棋中的对齐网格/棋盘
【发布时间】:2015-06-21 15:31:47
【问题描述】:

在 pygame 中有没有办法让精灵在拖动时捕捉到不可见(或可见)的网格?有点像拖放?如果是这样,怎么做?我一直在尝试做一些精灵重叠,但是为每条网格线制作一个 if 语句太乏味了。那么如何制作一个对齐网格的拖放精灵呢?这是一个国际象棋程序。感谢您的帮助。

【问题讨论】:

  • 不要为每一行做一个 if 语句,使用数学和循环。行是均匀分布的,它们都是一个空格的倍数。

标签: python drag-and-drop pygame


【解决方案1】:

使用 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 没有对齐网格功能。

【讨论】:

  • 请澄清edgeRightedgeLeftedgeTopedgeBottom
  • 对不起。这些是以像素为单位的棋盘区域的边缘。所以edgeTop 是第 8 行顶部开始的像素行(如 30),edgeLeft 是 a 文件(40)等等。
【解决方案2】:

所以这可以通过在 python 中使用 round 函数来完成。

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

这通过将精灵的坐标四舍五入到最近的方格来操纵圆形功能。

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 2013-05-24
    • 2014-03-02
    • 1970-01-01
    相关资源
    最近更新 更多