Question re: objects and square grids

Dave Angel davea at davea.name
Wed May 15 13:55:34 EDT 2013


On 05/15/2013 12:56 PM, Andrew Bradley wrote:
> Hello everyone.
>
> I am having a good time programming with Python 3.3 and Pygame. Pygame
> seems like the perfect platform for the kind of simple games that I want to
> make.
>

Pygame indeed looks pretty good to me as well.  But I haven't done 
anything with it, so I can't give you specific Pygame advice.


>      <SNNIP>
>
> So far, I have done this:
>
> A1 = pygame.Rect(10, 12, 43, 43)
> A2
> A3
> A4
> B1
> B2
> etc.
>

This is a code smell in Python (or any reasonable language).  I'd 
suggest that instead of trying to have 200 separate global variables, 
you have one, maybe called grid, as follows:

maxrows = 10
maxcols = 20
grid = []
for row in range(maxrows):
     rowdata = []
     for column in range(maxcols):
         arg1 = ...
         arg2 = ...
         arg3 = ...
         arg4 = ...
         rowdata.append(pygame.Rect(arg1, arg2, arg3, arg4)
     grid.append(rowdata)


Now, this can be done shorter with list comprehensions, but I figured 
this would be clearer for you.  I also may have the 10 and 20 reversed, 
but you can work that out.

You'd need to make four formulae to get the four arguments to the Rect 
call, using row and column respectively.  Remember that row and column 
will be numbered from zero, not from one.

But now, you can either address a single rect by
    grid[4][8]

or you can do something to all of them, or to an entire row, or to an 
entire column, pretty easily.


While you're testing your formulae, you might want to replace the 
rowdata.append line with something like:

         rowdata.append( (arg1, arg2, arg3, arg4) )


And perhaps your maxrows, maxcols might be lower while you're testing.

And you can just print grid to see how those arguments are looking.

-- 
DaveA



More information about the Python-list mailing list