zzoop
zzoop

Reputation: 91

Unpacking a tuple in python and iterating over it

I'm trying to unpack a co-ord tuple then iterate over it to blit a sprite multiple times:

def updateMap(self, playerPosition):

  self.x_coord, self.y_coord = playerPosition 

  t = Tree(self.screen)
  for x in range(self.x_coord):
    for y in range(self.y_coord):
      self.screen.fill((0,104,0))
      t.drawTree((x, y))

However I get the following error:

File "unnamed.py", line 26, in updateMap
  for x, y in range(self.x_coord), range(self.y_coord):
ValueError: need more than 0 values to unpack

Grateful if someone can point me in the right direction on the correct way to do this. Thanks.

EDIT: I have edited my code to the above to iterate over every coord say if playerPostion is 0,5 so the iteration goes (0,1) (0,2) (0,3) (0,4) (0,5) -- but although I'm not getting any errors it seems the tree does not get drawn correctly. Thanks.. it seems to be the answer, except my coding is just wrong.

Upvotes: 0

Views: 159

Answers (4)

Iron Fist
Iron Fist

Reputation: 10961

I think this is what you want instead:

from itertools import product

self.x_coord, self.y_coord = playerPosition #playerPosition is a tuple

t = Tree(self.screen)
for x,y in product(range(self.x_coord+1), range(self.y_coord+1)):
    self.screen.fill((0,104,0))
    t.drawTree((x, y))

Upvotes: 1

Jolbas
Jolbas

Reputation: 752

Maybe if you change:

self.x_coord = 0 
self.y_coord = 0 
playerPosition = self.x_coord, self.y_coord

to:

self.x_coord, self.y_coord = playerPosition

then you get the player position x and y in to self.x_coord and self.y_coord

And to iterate over every combination of x and y you either need to put a loop over y range inside inside a loop over the x range

for x in range(self.x_coord):
    for y in range(self.y_coord):
        self.screen.fill((0,104,0))
        t.drawTree((x, y))

Upvotes: 0

Colin Schoen
Colin Schoen

Reputation: 2598

Use the built in Python zip function assuming both of the iterables are of the same length. If not then you will need to do a bit of sanitization before to ensure they are.

for x, y in zip(range(self.x_coord), range(self.y_coord))

Upvotes: 0

masnun
masnun

Reputation: 11916

I think the OP wants to iterate over the range of X co-ordinates and the range of Y co-ordinates to create a (x,y) for each case.

for x in range(self.x_coord):
    for y in range(self.y_coord):
        print(x, y)

Upvotes: 0

Related Questions