[Tutor] Improving My Simple Game Code for Speed, Memory and Learning

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Jan 12 22:47:11 CET 2015


On 12/01/2015 19:35, WolfRage wrote:
> So I was write as I suspected; the grid is not actually being built like
> I thought it was. Sure the ID's print fine but when the grid positions
> are procedurally accessed the program fails with IndexError.
>
> python3 test1.py
> | 19 |  5 |  5 |  5 |
> | 11 |  6 | 19 | 11 |
> |  6 |  6 | 11 | 19 |
> | 11 | 20 |  6 |  5 |
> | 11 |  5 | 20 |  5 |
> | 20 | 20 | 11 | 11 |
> | 19 | 19 |  5 |  5 |
> | 11 | 19 | 19 |  5 |
> After Eliminations
> |  0 |  0 |  0 |  5 |
> | 11 |  0 | 19 | 11 |
> |  0 |  0 | 11 |  0 |
> |  0 | 20 |  6 |  0 |
> |  0 |  5 | 20 |  0 |
> |  0 |  0 |  0 |  0 |
> | 19 |  0 |  0 |  0 |
> |  0 |  0 |  0 |  0 |
> broke 0 5
> 0 6
> broke 1 6
> 1 7
> broke 2 6
> 2 7
> broke 3 6
> 3 7
> After Drops
> |  0 |  0 |  0 |  5 |
> |  0 |  0 | 19 |  0 |
> |  0 |  0 | 11 |  0 |
> |  0 | 20 |  6 |  0 |
> |  0 |  0 |  0 |  0 |
> |  0 |  0 |  0 |  0 |
> | 11 |  0 |  0 |  0 |
> | 19 |  5 | 20 | 11 |
> Normal
> | 0,0 | 1,0 | 2,0 | 3,0 |
> | 0,1 | 1,1 | 2,1 | 3,1 |
> | 0,2 | 1,2 | 2,2 | 3,2 |
> | 0,3 | 1,3 | 2,3 | 3,3 |
> | 0,4 | 1,4 | 2,4 | 3,4 |
> | 0,5 | 1,5 | 2,5 | 3,5 |
> | 0,6 | 1,6 | 2,6 | 3,6 |
> | 0,7 | 1,7 | 2,7 | 3,7 |
> Procedurally
> # The first printed pair is the id, the second pair in parentheses is
> # the procedurally accessed id, which should be all ordered as (column,
> # row)
> | 0,0 (0,0) | 1,0 (0,1) | 2,0 (0,2) | 3,0 (0,3) | Traceback (most recent
> call last):
>    File "test1.py", line 186, in <module>
>      grid.draw_by_id_proc()
>    File "test1.py", line 75, in draw_by_id_proc
>      print(self.grid[col_num][row_num].id, '(' + str(col_num) + ',' +
> str(row_num) + ')', end=' | ')
> IndexError: list index out of range
>

I haven't looked carefully at your code but there's always a smell in 
Python when you see structure[x][y].  Can you change the grid so you 
always write something like:-

for row in grid:
     for cell in row:
         process(cell)

I say this as I'm all for short term pain, long term gain, especially 
when it's guaranteed to eliminate "list index out of range" errors.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list