Search code examples
pythonrandompygameterrainpygame2

Problem with generating random terrain pygame


I want to make simple game with randomly generated terrain but, when I move the terrain, instead of generating terrain randomly, it generates terrain at maximum height, which is 8.

I am beginner in PyGame and this bug is irritating me.

Code:

    import pygame
from random import randint
pygame.init()

# Set up the drawing window
screen = pygame.display.set_mode([1000, 500])

kolory = ["deepskyblue2","chocolate4"]

w = 6

def wysokosc_spr():
    global w
    if w == 8:
        w -= 1
        return w
    elif w <= 3:
        w += 1
        return w
    else:
        w = randint(w-1,w+1)
        return w

swiat = [[kolory[1] for j in range(wysokosc_spr())] for i in range(20)]

def wyswietl_swiat(tablica_2D,x,y = 500):
    for i in tablica_2D:
        for j in i:
            pygame.draw.rect(screen,kolory[1],pygame.Rect(x,y,50,50))
            y -= 50
        y = 500
        x += 50

# Run until the user asks to quit
running = True
while running:

    screen.fill((255, 255, 255))
    wyswietl_swiat(swiat,0,500)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                swiat += [kolory[1] for i in range(wysokosc_spr())]
                swiat.pop(0)

    pygame.display.flip()


# Done! Time to quit.
pygame.quit()

Solution

  • Actually you add w columns. You have to append a new column with w items:

    swiat += [kolory[1] for i in range(wysokosc_spr())]

    swiat.append([kolory[1] for i in range(wysokosc_spr())])