Reputation: 11
I'm trying to learn Python, (i have 2.5.4) by writing a snake game, but I'm stuck. Some integers change into floats and keep changing randomly, at least from my perspective :)
The problem is that Snake.spawnPoint
gets changed by Cam.move()
print Snake.spawnPoint # first time, this returns '[25, 20]' ,which is good.
Cam.Move()
print Snake.spawnPoint # after the method, the value is '[26.0, 21.0]', and that's bad
After that, they just drift around.
And this is the method: (it has nothing to do with the spawnPoint
def Move(self):
self.vel[0]+=(self.target[0]-self.cen[0])*self.k
self.vel[1]+=(self.target[1]-self.cen[1])*self.k
if self.vel[0] > self.friction: self.vel[0]-= self.friction
elif self.vel[0] < self.friction: self.vel[0]+= self.friction
else: self.vel[0] = 0
if self.vel[1] > self.friction: self.vel[1]-= self.friction
elif self.vel[1] < self.friction: self.vel[1]+= self.friction
else: self.vel[1]=0
self.cen[0]+=self.vel[0]
self.cen[1]+=self.vel[1]
The spawnPoint
is a constant that I append to the snake's body when he spawns. I like it to be a list because it have the snake's body made of lists, and the rendering method uses index()
to do stuff.
The code doesn't seem to fit here, so i zipped it. Can someone take a look at it? Thanks http://www.mediafire.com/?zdcx5s93q9hxz4o
Upvotes: 1
Views: 1797
Reputation: 26586
In Python (as in many other languages) any simple arithmetic operation (e.g. +,-,/,*) involving an integer and a float evaluates to an answer that is a float. Integers never change into floats, it is the result of the operation that is returned as a float.
Note that the result of operations involving only integers is returned as an integer (I'm using the word integer to refer to both int
and long
in Python).
Upvotes: 1
Reputation: 16775
Integers change to floats if you combine them in an expression, i.e. multiplication, addition, subtraction (not necessarily division). Most likely, some of your variables are floats, e.g. self.friction.
floats don't change back to integers by themselves, only through int(). If you observe anything else, you observe it wrong.
It appears your Move method modifies "spanwPoint" indirectly. I don't know if this is expected behavhiour, but it probably means you have two references pointing to the same list. E.g.
self.spawnPoint = [1, 0]
self.vel = self.spawnPoint # Does not make a copy!
self.vel[0] += 0.1
self.vel[1] += 0.2
will result in self.spawnPoint (also) being [1.1, 0.2]
Upvotes: 4