python - 我如何跟踪用户在棋盘上的点击?

标签 python pygame pycharm python-3.7

我正在使用Python 3.7.4。我使用 Pycharm 2020 Community 作为我的 IDE。我使用 Pygame 1.9.6 作为我的游戏解释器。

我想知道如何跟踪玩家在棋盘上的点击。我想它应该在我的 main() 运行操作中,但是在哪里呢? 所以在棋盘上它是一个 8x8 的棋盘,所以有 64 个方格。就像说,他们单击一次方 block 来选择上面有棋子的方 block ,然后单击另一个方 block ,如果该方 block 是空的,则将所述棋子移动到另一个方 block 。我的棋盘上的一个空方格是:“01”。就像我需要某种方式来获取板的尺寸(例如行或列)吗? 我有电路板的尺寸。

WIDTH = HEIGHT = 512  # 400 is another option
DIMENSION = 8  # dimensions of a chess board are 8x8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 15  # for animations later on
IMAGES = {}

def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    loadImages()  # only do this once, before the while loop
    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()

我以前从未点击过鼠标,所以我想知道如何才能做到这一点?

最佳答案

点击字段的索引可以通过//(下限除法)运算符来计算。获取 MOUSEBUTTONDOWN 事件(请参阅 pygame.event )并将鼠标位置坐标除以 SQ_SIZE:

def main():
    # [...]

    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

            if e.type == p.MOUSEBUTTONDOWN:
                mousePos = e.pos
                column, row = mousePos[0] // SQ_SIZE, mousePos[1] // SQ_SIZE
                columnName, rowName  = chr(ord('a') + column), str(row+1)
                print("clicked at " + columnName + rowName)

关于python - 我如何跟踪用户在棋盘上的点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63584252/

相关文章:

python - 当需要不同的参数时,如何在类中使用 if/elif?

python - 在 PyCharm 3.4.X 控制台中运行脚本时,msvcrt getch() 没有任何反应

python - 在 Pycharm : How to turn off interactive mode? 中调试时使用 Matplotlib

javascript - Django 响应将 json 设置为 cookie

Python:使用 "dot notation"访问 YAML 值

python - 在 tkinter 中运行 matplotlib

python - 调试对 Python 脚本的 ajax 调用

python - "TypeError: argument 1 must be pygame.Surface, not method"Python 错误

python - Pygame 窗口卡住并停止响应,我该如何解决这个问题?

python - 当在另一个函数(self)中声明函数(self)时,“self”丢失了一些东西