You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame开发2D Minecraft克隆:方块无法对齐32倍数网格位置

问题解决:2D Minecraft克隆游戏方块无法对齐网格

你的问题核心原因是点击事件中直接存储了原始鼠标位置event.pos,没有做网格对齐处理,而跟随鼠标的占位方块用的是经过rtm函数修正后的坐标,两者处理逻辑不一致导致错位。

解决步骤

  • 在鼠标点击事件里,不要直接把event.pos加入positions列表,先对点击的x、y坐标做网格对齐计算
  • 复用你已经写好的rtm函数,同时加上边界限制,避免方块超出窗口范围

修改后的完整代码

import pygame

pygame.init()
win = pygame.display.set_mode((480,320))
pygame.display.set_caption(("2D Craft"))
block = pygame.image.load("Grass.png")
running = True

positions = []

def rtm(n, m):
    return round(n / m) * m

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            # 对点击坐标做网格对齐+边界限制
            click_x, click_y = event.pos
            aligned_x = rtm(click_x, 32)
            aligned_y = rtm(click_y, 32)
            if aligned_x > 448:
                aligned_x = 448
            if aligned_y > 288:
                aligned_y = 288
            positions.append((aligned_x, aligned_y))

    mx, my = pygame.mouse.get_pos()

    #snap to grid (multiple should be width and height of cube)
    mxr = rtm(mx, 32)
    myr = rtm(my, 32)

    #boundries
    if mxr > 448:
        mxr = 448
    if myr > 288:
        myr = 288

    win.fill("aqua")
    for pos in positions:
        win.blit(block, pos)
    win.blit(block, (mxr, myr))
    pygame.display.update()

说明

修改后,点击时的坐标会和预览方块走完全相同的处理流程:先对齐到32的倍数,再做边界限制,最后存入列表。这样放置的方块位置就会和预览的占位方块完全一致,解决对齐问题。

内容的提问来源于stack exchange,提问作者Pythonista

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:32:47