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

Re: [pygame] vector type: mutable or immutable




Hi



Brian Fisher pointed out two advantages of immutable vector types:
1) they prevent bugs in programs like the following (adopted from Brian):
> class Angel(object)
>     def __init__(self, offset):
>         self.offset = offset
>
> t = Angel()
> halo_pos = t.offset
> halo_pos.y -= 5  # BUG: this changes the offset in t


If you have a certain number of objects that you want to move simultaneous you could share the self.pos vector and by only changing it at one place all objects would change place too. For example a sprite that should always follow:

class Entity:

 def __init__(self):
   self.pos = Vec2(x,y)
   self.sprite.pos = self.pos

e = Entity()

by updating e.pos.x = 10 the sprite would follow automatically

To avoid the bug that Brian had I used this:

   def _set_values(self, other):
       self.x = other.x
       self.y = other.y
   values = property(None, _set_values, doc='set only,value assignemt')

This is basically the same as writing:

v.x = w.x
v.y = w.y

but more elegant:

v.values = w

So it can be used like this:

class Angel(object)
   def __init__(self, offset):
       self.offset = offset

t  = Angel()
halo_pos.values = t.offset # <- set the values rather change the reference
halo_pos.y -= 5  # does not change t anymore

I'm for mutable vectors so far.

~DR0ID