Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm currently working on a map editor for a game in pygame, using tile maps. The level is built up out of blocks in the following structure (though much larger):

level1 = ( 

(1,1,1,1,1,1) 

(1,0,0,0,0,1) 

(1,0,0,0,0,1) 

(1,0,0,0,0,1) 

(1,0,0,0,0,1) 

(1,1,1,1,1,1))

where "1" is a block that's a wall and "0" is a block that's empty air.

The following code is basically the one handling the change of block type:

clicked = pygame.mouse.get_pressed() 

if clicked[0] == 1: 

currLevel[((mousey+cameraY)/60)][((mousex+cameraX)/60)] = 1

But since the level is stored in a tuple, I'm unable to change the values of the different blocks. How do I go about changing the different values in the level in an easy manner?

2 Answers

0 votes
by (106k points)

Convert tuple to list:

>>> t = ('my', 'name', 'is', 'mr', 'tuple') 

>>> prit(t)

 ('my', 'name', 'is', 'mr', 'tuple') 

>>> list(t) 

['my', 'name', 'is', 'mr', 'tuple']

Convert list to tuple:

>>> l = ['my', 'name', 'is', 'mr', 'list'] 

>>> print(l) 

['my', 'name', 'is', 'mr', 'list'] 

>>> tuple(l) 

('my', 'name', 'is', 'mr', 'list')

0 votes
by (20.3k points)

You have a tuple of tuples. To convert every tuple to a list:

[list(i) for i in level] # list of lists

Or, you can try this:

map(list, level)

And after you are done editing, then just convert them back:

tuple(tuple(i) for i in edited) # tuple of tuples

tuple(itertools.imap(tuple, edited))

You can also try using a numpy array like this:

>>> a = numpy.array(level1)

>>> a

array([[1, 1, 1, 1, 1, 1],

       [1, 0, 0, 0, 0, 1],

       [1, 0, 0, 0, 0, 1],

       [1, 0, 0, 0, 0, 1],

       [1, 0, 0, 0, 0, 1],

       [1, 1, 1, 1, 1, 1]])

For manipulating try this:

if clicked[0] == 1:

    x = (mousey + cameraY) // 60 # For readability

    y = (mousex + cameraX) // 60 # For readability

    a[x][y] = 1

Related questions

0 votes
1 answer
asked Jul 4, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 3, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer

Browse Categories

...