0

I'm trying to create a random map, with lists inside the main list representing the lines. The "createBlankMap" function works perfectly fine, for creating a placeholder map, and the "displayMap" function also works fine, for printing the map and changing the 0s or 1s to "." or "#". But when i try to update the blank map, using the "generateMap" function, all the nested lists get the same random generated value, instead of all of them generating random generated values.

# -*- coding: utf-8 -*-
import random

def displayMap(canvas):
    for i in range(len(canvas)): #LINE
        for j in range(len(canvas[i])):
            if canvas[i][j] == 0:
                print(".", end='')
            elif canvas[i][j] == 1:
                print("#", end='')
            else:
                break
        print()

def createBlankMap(x,y):
    MAP = []
    LINE = []
    for j in range(y): #COLUMN
        LINE.append(0)
    for i in range(x): #LINE
        MAP.append(LINE)
    return MAP

def generateMap(canvas):
    for i in range(len(canvas)): #LINE
        for j in range(len(canvas[i])): #COLUMN
            choice = random.uniform(0,1)
            if choice < 0.5:
                canvas[i][j] = 1
            else:
                canvas[i][j] = 0
    return canvas

displayMap(generateMap(createBlankMap(5, 10)))

The output is always like this: (remembering those values are randomly generated, so they're different every time i run the program).

###.##.#.#
###.##.#.#
###.##.#.#
###.##.#.#
###.##.#.#

So basically, i want all the lines to have random generated values, instead of them repeating the first one.

  • 2
    It's not your random number generation that's failing, it's your creation of the map. There is only one `LINE`, each element of the map is a reference to that single list. Making copies of that list (`MAP.append(LINE[:])`) would be one solution. – jasonharper Mar 17 '20 at 19:33
  • Thank you, i didn't realize i was simply editing that single list. Solved. – Vitor Silvestri Mar 17 '20 at 19:38

0 Answers0