Kivy Pong Official Tutorial - Using Vector (kivy.vector)

I follow the official Kivy PongApp tutorial ( link - all program code at the bottom of the site), and I ran into a problem I can not understand.

I defined a move function to change the position of the ball by the velocity vector on each frame. The code:

def move(self): self.pos = Vector(*self.velocity) + self.pos 

However, when I wrote the code as follows:

 def move(self): self.pos = self.pos + Vector(*self.velocity) 

This results in an error: ValueError: the length of the PongBall.pos value is unchanged

Why shouldn't it be the same?

+5
source share
2 answers

I think this is only due to the fact that the Vector type overrides the complement for adding vectors, and in the first case, its __add__ is called, which automatically treats self.pos (list) as another vector.

In the second case, __add__ self.pos is called, which does not know about the Vector type and instead tries to perform the usual addition of a list that extends the length of the list. This is not with the error you see, since pos must be a fixed-length list.

Thus, in general (if I'm right) the problem is that + performs different actions depending on the types of its arguments. This is usually not important, but here it is of great importance.

+4
source

self.pos is kivy.properties.ObservableReferenceList .

When trying to set this property, it checks that the new value is the same length as the old value.

From kivy.properties.ReferenceProperty :

 cdef check(self, EventDispatcher obj, value): cdef PropertyStorage ps = obj.__storage[self._name] if len(value) != len(ps.properties): raise ValueError('%s.%s value length is immutable' % ( obj.__class__.__name__, self.name)) 

In addition, kivy.properties.ObservableList subclasses list .

Unfortunately, the same is kivy.vector.Vector , and as anyone with experience in Python can tell you, list.__add__ combines its arguments.

This means that the vector is added to self.pos , expanding it, rather than adding it separately, and then causes self.pos complain because its length changes.

This works differently because Vector overloads __add__ to make type additions.

Since python stands for __add__ over __radd__ , all of this fails.

+6
source

Source: https://habr.com/ru/post/1200545/


All Articles