[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Calculating x/y pos for a 2D grid



On 23/01/07, Farai Aschwanden <fash@xxxxxxxxxx> wrote:
Hi all

No question, except maybe someone already used it (experience?).

I found a easy way how to calculate the x and y pos out of 2D grid.
Watch this 4*4 grid. Every number represents the grid number:

  0      1      2      3
  4      5      6      7
  8      9    10    11
11   12    13   14

The numbers can be in a simple list or dictionary.

Now the big question: How you  get f.e. the coordinates for position
number 9? The solution is the function divmod().  Divide the wanted
position number by the amount of vertical grid size. In this case its
4. The calculation looks like this then:

ypos, xpos = divmod (9, 4)

=> xpos : 1
=> ypos:  2

Based on the fact that Python starts counting at 0, you get the
correct coordinates for position 9.

I had no time to test it yet but should work - theroetically.

Just my 2 cents.

Farai

Did a quick test:

 >>> l = [[0 ,1 ,2 ,3 ],
...      [4 ,5 ,6 ,7 ],
...      [8 , 9,10,11],
...      [12,13,14,15]]
>>>
>>> ypos,xpos = divmod(9,4)
>>> print l[ypos][xpos]
9
>>> ypos,xpos = divmod(15,4)
>>> print l[ypos][xpos]
15
>>> ypos,xpos = divmod(0,4)
>>> print l[ypos][xpos]
0
>>>

as you can see, it seems to work, nice one Farai.