1

I am making a small game in Python using pythonista on my ipad. I made a vector class that contains the coordinates and several functions to add, get a length, set a length. I have another class called Game in which I have my game variables and functions. I can define a vector lets say

self.pos=vector(200,200)

But if I want to work out the length, I can't call the getlength function because I'm not in the right class.

Example (I've taken out most of the code):

class vector(objet):
    def __init(self,x,y):
        self.x=x
        self.y=y

   def getlength(self):
       return sqrt(self.x**2+self.y**2)

  def addvec(self,a,b):
   return vector(a.x+b.x,a.y,b.y)


class Game(object):
    def __init__(self):
        self.pos=vector(200,200)
        self.pos=vector(200,200)

    def loop(self):
        ## here i want something like d= length of self.pos !!

class MyScene(Scene):
    def setup(self):
        self.game=Game()

    def draw(self):
        self.game.loop()  

run(MyScene())

Thanks, Nicolas

EDIT : the call

sum=addvec(self.pos,self.pos2)

obviously doesn't work because self is a Game class. How can I do it?

7
  • 2
    self.pos.getlength? You neither want nor need it to be a global function - it's a useful instance method. Commented May 23, 2014 at 17:24
  • Please use 4 spaces to set an indentation level. UPD: That's better. Commented May 23, 2014 at 17:24
  • What happens when you try to call the getlength method? Commented May 23, 2014 at 17:25
  • __init should be __init__ Commented May 23, 2014 at 17:25
  • objet should be object Commented May 23, 2014 at 17:25

1 Answer 1

4

Why do you use two arguments for the getLength function? The second one is a vector (I assume) so it would be better to use:

def getLength(self):
    return sqrt(self.x**2+self.y**2)

and then just call:

d = self.pos.getLength()

If you would want to add two vectors together you would do something like this:

def add(self,other_vector):
    return vector(self.x+other_vector.x,self.y+other_vector.y)

so you would call:

sum = self.pos.add(some_other_vector)

BTW: Classes should always be written in CamelCase. And maybe you should read something about object oriented programming in python: http://code.tutsplus.com/articles/python-from-scratch-object-oriented-programming--net-21476

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that works ! Sorry if I and not very good at this...if I want to add two vectors with a function in the vector class. 'code' def addvec(self,a,b): return vector(a.x+b.x,a.y,b.y) the call sum=addvec(self.pos,self.pos2) obviously doesn't work because self is a Game class. How can I do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.