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

Re: [pygame] Sprite Collision



Ethan Glasser-Camp wrote:
Ian Clark wrote:
On 4/30/07, Casey Duncan <casey@xxxxxxxxxxx> wrote:
passible_at = [[True] * 100] * 100 # Create a 2 dimensional list with
an element for each tile
This does not do what you think it would:

Someone more skilled than I can explain *why* the first one does what
it does. I just know one way to get around it (and I'm sure there's a
more elegant solution).

The expression

[True]*100

evaluates to a list that has 100 elements, each pointing to the same
thing (the True object).

Aha! I've seen a problem like this before. I called it the "stripey doom error," because when I did a tile-based game and changed one element, I'd see a whole stripe of tiles change instead of one. Python has other "sticky variable" problems sometimes if you don't think carefully about whether something is a reference to another variable. I would sometimes end up changing "constants" and having other problems.


>>> coords = [42,100]
>>> copy_of_coords = coords
>>> copy_of_coords[0] += 5000
>>> copy_of_coords
[5042, 100]
>>> coords
[5042, 100] ## Bad!

But:
>>> coords = [42,100]
>>> copy_of_coords = [coords[0],coords[1]]
>>> copy_of_coords[0] += 5000
>>> copy_of_coords
[5042, 100]
>>> coords
[42, 100] ## OK!

When all else fails, copy.deepcopy() seems to make Python understand, "I want this to have _the same value_ as X now has, not to be a _reference_ to X."

Kris