• Welcome to Valhalla Legends Archive.
 

[Python] Tetris

Started by Noodlez, July 01, 2004, 09:52 AM

Previous topic - Next topic

Noodlez

I'm trying to write a Tetris game in Python. I decided I'd use a matrix to represent the board 10x12 board. If theres a 1 draw a square, otherwise ignore it. I find this to be the most optimal way to detect when lines have been connected as well.

Anyway, the problem is python programmers got lazy.

The following code should generate a matrix:

   def __init__( self, shape ):
       if (p_shapes[shape]==1): #The middle finger piece
           self.shapematrix = [[1]*3]*2]
           self.rotate=0


At first glance, it worked fine. Then I tried to make it my middle finger piece.


           self.shapematrix[0][0] = 0
           self.shapematrix[0][1] = 0


The result? (This isn't from the exact same instance, but it demonstrates the problem.)


>>> test[0][0] = 0
>>> test[0][2] = 0
>>> test
[[0, 1, 0], [0, 1, 0]]


As you can obviously deduce, the Python programmers decided that when someone wants to make a list *2, it's obviously gonna be the exact same list, so hey, why not make it a pointer?

I found a workaround, using a for loop to generate the matrix. This, however, is CPU hogging in the long run and I don't like it. If anyone out there can help, I'd appreciate it. Thanks.
           

Banana fanna fo fanna

It's not a bug...__mul__ is defined to make a shallow copy of the list. You'll want to do something like this:


import copy

class CopyList(list):
   def __init__(self, *args):
       list.__init__(self, list(args))
   def __pow__(self, n):
       newlist = CopyList()
       for i in range(0, n):
           newlist.extend(copy.deepcopy(self))
       return newlist

#shapematrix = [[1]*3]*2]            
shapematrix = CopyList(CopyList(1) ** 3) ** 2
print shapematrix
shapematrix[0][0] = 0
print shapematrix


I wrote it to use the pow (**) operator instead of *, so it wouldn't break compatibility. You can pass varargs to the constructor to create a list. I just realize I didn't create a constructor that takes a list, so you might want to do that.

Look into the Psyco VM.