Reputation: 53
I am working on a game for a school project using pygame and was struggling to make a world generation algorithm I was wondering if anyone could help me. for anyone wondering the game is a rip off version of the game Terreira if that helps.
Upvotes: 1
Views: 1176
Reputation:
One way of making a map in pygame is to do it using tiles, but I find that it to be massive effort, since you first have to learn how to use it. Another more common way to do it is to create a 2-D list representing your x
and y
for every point in your map, depending on how you scale the map.First lets talk about the map creation:
# lets say 0 represents empty space
# 1 represents a block image u might have for example dirt image or a wall
layout = [ [1, 0, 2],
[0, 1, 1] ]
Then, to actually draw the map you can loop over this list, first every layer in the list, then every element in that layer, like this:
y = 0
for layer in layout:
x = 0
for element in layer:
if element == 1:
D.blit(your image, (x * block_length, y * block_height))
if element == 2:
D.blit(your image, (x * other_block_length, y * other_block_height))
else: # else do nothing, which leaves the area empty
pass
x += 1 # add 1 to x every inner loop
y += 1 # add 1 to y value every outer loop
Here is an example from one of my games
class Game_map:
def __init__(self):
self.land = pygame.image.load(r"C:\Users\pro-gramar\OneDrive\Documents\A level python codes\final game\land.png").convert()
self.height = 200
self.width = 200
self.land = pygame.transform.scale(self.land, (170 , 200))
self.land.set_colorkey((0, 0, 0))
self.map_width = 6000
self.map_height = 2000
# 0 = emepty
# 1 = land
self.layout = [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0 ,0 ,0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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