I am creating a 2D minecraft clone in Pygame and everything is going well so far. I am stuck on how to switch the block's picture so that it places a different block. The variable in which the PNG is stored in is "block". I want to be able to switch between 8 other images by using the left/right arrow keys. I have thought about listing these images in the "block"" variable but I am stuck on how to actually implement this. Here's what the game looks like
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()
Here is the new code that includes objects. It does the same thing as before in terms of block selection, the only difference now is that it appends an object to the list that stores a position and image instead of just a position. This object is defined in a new file (called 'block.py') that you will have to create, which is referenced by calling 'block.[what you are calling here]' in the same way you must type pygame before any pygame methods.
Main file:
And in your block.py file, you want to have this
Hopefully this helps!