我正在创建一个等距的《我的世界》克隆,并且我的代码运行良好。我使用舍入函数来舍入玩家的位置,以便块捕捉到网格。该块的图像精确为 32x32 像素,并且图像中的所有内容都是对称的。
我目前将舍入函数设置为 X 轴上的 16 个像素和 Y 轴上的 8 个像素。问题出在 Y 轴上,因为如果您不按正确的顺序放置它们,这会导致一些块重叠。我不知道如何解决这个问题,因为我已经尝试过使用舍入函数。如有帮助,将不胜感激。这是代码:
import pygame
pygame.init()
win = pygame.display.set_mode((480,320))
pygame.display.set_caption(("Mini Minecraft"))
block = pygame.image.load("Stone.png")
pygame.display.set_icon(block)
background = pygame.image.load("Background.png")
running = True
positions = []
def roundToMultiple(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:
placeX, placeY = event.pos
placeXRound = roundToMultiple(placeX, 16)
placeYRound = roundToMultiple(placeY, 8)
positions.append((placeXRound, placeYRound))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
positions = []
mouseX, mouseY = pygame.mouse.get_pos()
mouseXRound = roundToMultiple(mouseX, 16)
mouseYRound = roundToMultiple(mouseY, 8)
if mouseXRound > 448:
mouseXRound = 448
if mouseYRound > 288:
mouseYRound = 288
win.blit(background, (0,0))
for pos in positions:
win.blit(block, pos)
win.blit(block, (mouseXRound, mouseYRound))
pygame.display.update()
您只需对点列表进行排序即可。根据 x 坐标和逆 y 坐标对列表进行排序:
if event.type == pygame.MOUSEBUTTONDOWN:
placeX, placeY = event.pos
placeXRound = roundToMultiple(placeX, 16)
placeYRound = roundToMultiple(placeY, 8)
positions.append((placeXRound, placeYRound))
temp = [(x, -y) for x, y in positions]
temp.sort()
positions = [(x, -y) for x, y in temp]