我正在 Pygame 中创建 2D Minecraft 克隆,到目前为止一切进展顺利。我被困在如何切换块的图片以便它放置不同的块上。存储PNG的变量是“block”。我希望能够使用左/右箭头键在其他 8 个图像之间切换。我曾考虑过在“block”变量中列出这些图像,但我不知道如何实际实现它。
import pygame
pygame.init()
win = pygame.display.set_mode((480,320))
pygame.display.set_caption(("PyCraft"))
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
if event.type == pygame.MOUSEBUTTONDOWN:
px, py = event.pos
pxr = rtm(px, 32)
pyr = rtm(py, 32)
positions.append((pxr, pyr))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
positions = []
mx, my = pygame.mouse.get_pos()
mxr = rtm(mx, 32)
myr = rtm(my, 32)
if mxr > 448:
mxr = 448
if myr > 288:
myr = 288
win.fill("white")
for pos in positions:
win.blit(block, pos)
win.blit(block, (mxr, myr))
pygame.display.update()
假设您不想为每个块创建一个精灵,最简单的方法(imo)是保留您想要的所有精灵的列表,并使用全局变量循环遍历它们。下面的代码可以容纳模块化数量的图像 - 我无法测试它,但这应该可以工作,如果有任何问题请告诉我,我会相应地更新它。
import pygame
pygame.init()
win = pygame.display.set_mode((480,320))
pygame.display.set_caption(("PyCraft"))
BLOCK_LIST = [pygame.image.load('path here'),...] #load all block images into this list
ACTIVE_BLOCK = BLOCK_LIST[0]
COUNT = 0 #which block is currently selected
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
if event.type == pygame.MOUSEBUTTONDOWN:
px, py = event.pos
pxr = rtm(px, 32)
pyr = rtm(py, 32)
positions.append((pxr, pyr))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
positions = []
#deal with arrow keys
if event.key == pygame.K_LEFT:
#move count left, keep it within the bounds of the list and update active block img
if COUNT == 0: #count is below 0, so loop to the end of the list instead
COUNT = len(BLOCK_LIST)
COUNT = (COUNT - 1) % len(BLOCK_LIST)
ACTIVE_BLOCK = BLOCK_LIST[count]
if event.key == pygame.K_RIGHT:
#do the same thing but add one instead of removing one from count
COUNT = (COUNT + 1) % len(BLOCK_LIST)
ACTIVE_BLOCK = BLOCK_LIST[count]
mx, my = pygame.mouse.get_pos()
mxr = rtm(mx, 32)
myr = rtm(my, 32)
if mxr > 448:
mxr = 448
if myr > 288:
myr = 288
win.fill("white")
for pos in positions:
win.blit(ACTIVE_BLOCK, pos) #always blit whatever the active block is
win.blit(ACTIVE_BLOCK, (mxr, myr))
pygame.display.update()
希望这有帮助!