ahh!!

omg i have a large problem
i want to import player class from player.py into main.py but when i do player.player() nothing happens? wut do i do??
main.py

from pandac.PandaModules import * # Import the Panda Modules
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
from direct.actor import Actor
from direct.task.Task import Task
from direct.showbase.DirectObject import DirectObject
import random, sys, os, math

loadPrcFileData("", "win-title Test Game")
loadPrcFile("cfg/config.prc")

import direct.directbase.DirectStart
from source.missiondata import *
from source.Player import *
import source.Player

class Main(DirectObject):
    def __init__(self): 
        Player.Player()
    
w = Main()
run()   #Run script

player

# Player Script

class Player(DirectObject):
    def __init__(self):
        self.player = render.attachNewNode("camera_dummy_node") 
        #Position the camera dummy node. 
        self.player.setPos(-5, 50, 8)
        # Set angles
        self.player.setHpr(0, 0, 0)
        # Attach the camera to the dummy node. 
        camera.reparentTo(self.player)
        # Position the camera 
        camera.setPosHpr(Vec3(0,10,0),Vec3(0,10,0))
        self.prevtime = 0
        self.controls()
        #end
        
    def controls (self):
        self.sens = 100
        self.crouch = False
        self.moveforward = "w"
        self.moveforwardup = "w-up"
        #Key Library. all controls HAVE to go here
        self.keys = {"turnLeft" : 0, "turnRight": 0,"accel": 0, "fire": 0, "deaccel":0, "jump" : 0, "crouch" : 0}
        self.accept("escape", sys.exit)            #Escape quits
        #Other keys events set the appropriate value in our key dictionary
        self.accept("a",     self.setKey, ["turnLeft", 1])
        self.accept("a-up",  self.setKey, ["turnLeft", 0])
        self.accept("d",    self.setKey, ["turnRight", 1])
        self.accept("d-up", self.setKey, ["turnRight", 0])
        self.accept(self.moveforward,       self.setKey, ["accel", 1])
        self.accept(self.moveforwardup,    self.setKey, ["accel", 0])
        self.accept("s",       self.setKey, ["deaccel", 1])
        self.accept("s-up",    self.setKey, ["deaccel", 0])
        self.accept("space",    self.setKey, ["jump", 1])
        self.accept("space-up",    self.setKey, ["jump", 0])
        self.accept("control",     self.setKey, ["crouch", 1])
        self.accept("control-up",   self.setKey, ["crouch", 0])
        self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
        self.gameTask.last = 0 
        
    
    def setKey(self, key, val):
        self.keys[key] = val

    def gameLoop(self, task):
        self.elapsed = task.time - self.prevtime
        self.MouseTask()
        if self.keys["turnLeft"]:
            self.turn(-1)
        if self.keys["turnRight"]:
            self.turn(1)
        if self.keys["accel"]:
            self.walk()
        if self.keys["deaccel"]:
            self.back()
        if self.keys["jump"]:
            self.jump()

        self.prevtime = task.time
        
        return Task.cont
    
    def turn(self,dir):
        elapsed = self.elapsed
        strafe = self.c_node.getNetTransform().getMat().getRow3(0)
        strafe.setZ(0)
        strafe.normalize()
        self.c_node.setPos(self.c_node.getPos() + strafe*(elapsed*45*dir))
  
    def walk(self):
        elapsed = self.elapsed
        backward = self.c_node.getNetTransform().getMat().getRow3(1)
        backward.setZ(0)
        backward.normalize()
        self.c_node.setPos(self.c_node.getPos() + backward*(elapsed*46))
       
        
    def jump(self):
        backward = self.c_node.getNetTransform().getMat().getRow3(1)
        backward.normalize()
        self.c_node.setPos(self.c_node.getPos() + backward)

        
    def back(self):
        elapsed = self.elapsed
        backward = self.c_node.getNetTransform().getMat().getRow3(1)
        backward.setZ(0)
        backward.normalize()
        self.c_node.setPos(self.c_node.getPos() + backward*(elapsed*-45))

    def MouseTask(self):
        try:
            x = base.win.getPointer(0).getX()
            y = base.win.getPointer(0).getY()
            if base.win.movePointer(0, 100, 100):
                self.heading = self.heading - (x - 100)*0.2
                self.pitch = self.pitch - (y - 100)*0.2
            if (self.pitch < -self.sens): self.pitch = -self.sens
            if (self.pitch >  self.sens): self.pitch =  self.sens
            self.c_node.setHpr(self.heading,self.pitch,0)
        except: pass

What’s the problem? You don’t get a crash or traceback, so everything is fine.

Look at your code:

(1) You import the class Player in two way. Only one is needed. So kick out the first import statement.

(2) In your Main.init function you create an instance of player. And then? Already in the next line of code nobody remembers your player instance. So python decides to delete it again, since it is useless from now on and a waste of memory.

Bad luck, but life isn’t fair. Your player lives only for a very, very short time.

Maybe your player will be more lucky is SOMEONE keeps a reference to it. More explicit: store it in a variable.

enn0x

...
from source.Player import *
import source.Player

class Main(DirectObject):
    def __init__(self):
        Player.Player()...

enn0x means you have to change this line-

Player.Player()

To this:

 p = Player.Player()

Almost there. The player instance will now live until the END of the init function.

This is ONE possible way to make the player instance live for longer:

    self.p = Player.Player( )

enn0x

so its
self.p = player.player???
wehn i tried that it still deletes player
YEA IM A NOOB!

No, it doesn’t.

Assuming you have been nice and cared about capitation: then this will give you a traceback, since there is no player.player, only Player.Player!

Assuming you have been lazy and mixed up capitation: then this will assign the Player class object to the variable self.p. This is not to be mixed up with a class instance!

To create a class instance you have to call the class object, like this:

    self.p = Player.Player( )

Nothing wrong with being a noob. We all have been noobs. Here a a few tips that will get you further:

Take time to write a post here or one other places! Other who try to help spend time on helping you.

Be as exact as possible! That means for example, spell everything right, even if this takes more time. See above.

Be as clear a possible! This mean, use words that other understand too. When talking about coding problems it is very, very important to use the right terms. Terms that otherse use too. Otherwise nobody knows what you are talking about. To know the right terms you have to spend some time on learning them. That means, read the basic Python tutorials.

Finally, to find out when your player instance get created and destroyed, you can use print statements:

class Player( DirectObject ):
    def __init__( self ):
        print "Player instance created:", self
        # rest of init code
    def __del__( self ):
        print "Player instance deleted:", self

Now you can see how long your instance is alive, if it is created at all.

enn0x

Hmm… now that (hopefully) player is alive for longer: there are two other things that seems strange.

(1) In Player.init you create an empty node (“camera_dummy_node”), but there is no geometry assigned to this node. I mean, no visible model. So you won’t see anything.

    def __init__(self):
        self.player = render.attachNewNode("camera_dummy_node")
        #Position the camera dummy node.
        self.player.setPos(-5, 50, 8)
        # Set angles
        self.player.setHpr(0, 0, 0)
        # Attach the camera to the dummy node.
        camera.reparentTo(self.player)
        # Position the camera
        camera.setPosHpr(Vec3(0,10,0),Vec3(0,10,0))
        self.prevtime = 0
        self.controls()
        #end 

(2) The rest of the Player class seems to be about player movement. In particular there is a task method gameLoop( self, task ), which checks keyboard state and then calls some other methods. But this task is never started!

You know, code like this:

        taskMgr.add( self.gameLoop, 'game loop' )

You could add a print statement to the method gameLoop. For example print the elapsed time. This way you will see if gameLoop is every called.

enn0x

i did that right caps.
i made a test script with the print commands, then imported into main.py, but it doesnt say Player instance created:

But the line of code where you create the player instance is called, isn’t it?
Verify it:

class Main(DirectObject):
    def __init__(self):
        print '--> before creating player instance'
        self.player = Player.Player()
        print '--> after creating player instance'

w = Main()
run()   #Run script

Seems like it is time to reveal your code again. Oh, and please print file names (path!) too.

enn0x

Main.py

from pandac.PandaModules import * # Import the Panda Modules
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
from direct.actor import Actor
from direct.task.Task import Task
from direct.showbase.DirectObject import DirectObject
import random, sys, os, math

loadPrcFileData("", "win-title Test Game")
loadPrcFile("cfg/config.prc")

import direct.directbase.DirectStart
from source.missiondata import *
from source.Player import *

class Main(DirectObject):
	def __init__(self):
		print "--> before creating player instance"
		self.player = Player.Player()
		print "--> after creating player instance"
		
run()   #Run script

Player.py

# Player Script

class Player(DirectObject):
    def __init__(self):

        self.player = render.attachNewNode("camera_dummy_node") 
        #Position the camera dummy node. 
        self.player.setPos(-5, 50, 8)
        # Set angles
        self.player.setHpr(0, 0, 0)
        # Attach the camera to the dummy node. 
        camera.reparentTo(self.player)
        # Position the camera 
        camera.setPosHpr(Vec3(0,10,0),Vec3(0,10,0))
        self.prevtime = 0
        self.controls()
        #end
        
        
    def controls (self):
        self.sens = 100
        self.crouch = False
        self.moveforward = "w"
        self.moveforwardup = "w-up"
        #Key Library. all controls HAVE to go here
        self.keys = {"turnLeft" : 0, "turnRight": 0,"accel": 0, "fire": 0, "deaccel":0, "jump" : 0, "crouch" : 0}
        self.accept("escape", sys.exit)            #Escape quits
        #Other keys events set the appropriate value in our key dictionary
        self.accept("a",     self.setKey, ["turnLeft", 1])
        self.accept("a-up",  self.setKey, ["turnLeft", 0])
        self.accept("d",    self.setKey, ["turnRight", 1])
        self.accept("d-up", self.setKey, ["turnRight", 0])
        self.accept(self.moveforward,       self.setKey, ["accel", 1])
        self.accept(self.moveforwardup,    self.setKey, ["accel", 0])
        self.accept("s",       self.setKey, ["deaccel", 1])
        self.accept("s-up",    self.setKey, ["deaccel", 0])
        self.accept("space",    self.setKey, ["jump", 1])
        self.accept("space-up",    self.setKey, ["jump", 0])
        self.accept("control",     self.setKey, ["crouch", 1])
        self.accept("control-up",   self.setKey, ["crouch", 0])
        self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
        self.gameTask.last = 0 
        
    
    def setKey(self, key, val):
        self.keys[key] = val

    def gameLoop(self, task):
        self.elapsed = task.time - self.prevtime
        self.MouseTask()
        if self.keys["turnLeft"]:
            self.turn(-1)
        if self.keys["turnRight"]:
            self.turn(1)
        if self.keys["accel"]:
            self.walk()
        if self.keys["deaccel"]:
            self.back()
        if self.keys["jump"]:
            self.jump()

        self.prevtime = task.time
        
        return Task.cont
    
    def turn(self,dir):
        elapsed = self.elapsed
        strafe = self.c_node.getNetTransform().getMat().getRow3(0)
        strafe.setZ(0)
        strafe.normalize()
        self.c_node.setPos(self.c_node.getPos() + strafe*(elapsed*45*dir))
  
    def walk(self):
        elapsed = self.elapsed
        backward = self.c_node.getNetTransform().getMat().getRow3(1)
        backward.setZ(0)
        backward.normalize()
        self.c_node.setPos(self.c_node.getPos() + backward*(elapsed*46))
       
        
    def jump(self):
        backward = self.c_node.getNetTransform().getMat().getRow3(1)
        backward.normalize()
        self.c_node.setPos(self.c_node.getPos() + backward)

        
    def back(self):
        elapsed = self.elapsed
        backward = self.c_node.getNetTransform().getMat().getRow3(1)
        backward.setZ(0)
        backward.normalize()
        self.c_node.setPos(self.c_node.getPos() + backward*(elapsed*-45))

    def MouseTask(self):
        try:
            x = base.win.getPointer(0).getX()
            y = base.win.getPointer(0).getY()
            if base.win.movePointer(0, 100, 100):
                self.heading = self.heading - (x - 100)*0.2
                self.pitch = self.pitch - (y - 100)*0.2
            if (self.pitch < -self.sens): self.pitch = -self.sens
            if (self.pitch >  self.sens): self.pitch =  self.sens
            self.c_node.setHpr(self.heading,self.pitch,0)
        except: pass

-------------------1----------------------

If you want Main.init to be executed you have to create a instance of class Main. You did this in your very first post! Why did you remove this?

So please add this line again:

w = Main()

-------------------2----------------------
My advice from above:

And this is your original code:

You kicked out the second import statement. I told you to kick out the first!

There are only two possible ways. Use one of them. Mixing doesn’t work!

Number one:

from source.Player import *
o = Player( )

Number two:

import source.Player
o = Player.Player( )

-------------------3----------------------
You are missing a few import statements at the beginning of source/Player.py:

from direct.showbase.DirectObject import DirectObject
from direct.task.Task import Task
from pandac.PandaModules import *
import sys

-------------------4----------------------
In source/Player.py you are working a lot with an attribute self.c_node. This attribute gets never assigned! Perhaps you meant self.player?

I have added this line for testing:

    def __init__( self ):
        ....
        self.c_node = self.player

-------------------5----------------------
Use “try” and “except” only if you are 100% sure that the code inside if free of bugs! This is very important!!!

For example, if you remove the try/exept in Player.MouseTask, then you will see that your code tries to use an attribute self.heading, without initializing this attribute!

Besides this the code works fine. At least I can see the player move if I press w/a/s/d keys, and add a print statement at the end of gameLoop( self, task ):

        print self.player.getPos( )

Oh, a last, basic tip: use the right words for variables/attributes/methods/classes! For example, if you mean “strafe”, then don’t use the method “def turn( … )”. Nobody, not even you, will be able to read your code. Or consider using Perl.

enn0x

thanks for the tips ennox it works now, but i also saw how it didnt work. it also showed how stupid i am. i accidently put run() in another py file i imported.

darksmaster923…

i noticed you were using some of my fps_template code, i’ve made some improvements sinse i last posted it, ironicly enough it now has a player class, uneven terrian, and i’ve begun working on projectiles, i could let you take a look at the current version, that old code snipplet of mine was really hackney (as ennox pointed out i didn’t even bother to rename the turn() function to strafe()) i think we’re both trying to do that same thing…a panda3d fps :smiley:

You are not stupid! You have little experience with Python, ok, but if you keep coding you will gain experience.

For example the “try/except” trap is the same in any programming language which offers this feature. You should never ignore an error by using “except: pass”. At least report the error in a print statement. And if you use “except”, then you should catch only the particular error type you are expecting with “except ErrorType: handle error”. Once everybody made this particular mistake.

I think one only learns if he or she sees the problem, and understands it. This is why I just gave mysterious hints. It something like “symptom -> cause -> cure”. You see the symptom, and you have to know what could be the cause (coding experience). Then you see the cause of the problem, and you have to know how to cure it (again, coding experience).

By the way, if you add self.heading and self.pitch to Player.init, then the code works as it should (I think). You can move forward with ‘w’, strafe with ‘a’/‘d’, and turn with the mouse.

    def __init__( self ):
        ....
        self.c_node = self.player
        self.heading = 0.0
        self.pitch = 0.0

enn0x

ok, but i already got uneven terrain in there. just need to learn jumpy.