On Sun, Feb 16, 2014 at 2:34 PM, Robinson Risquez <[email protected]>wrote:

> *Hi, I'm trying to access to a variable called "score" created in a layer
> from a cocos.sprite.Sprite object. I tried this: "director.scene.score",
> but does not work, any help? Leave a basic code for a better understanding
> of the situation:*
>
> class Player(cocos.sprite.Sprite):
>     def __init__(self):
>         cocos.sprite.Sprite.__init__(self, "player.png", 100, 100)
>         *#How i access to score var here??*
>
>
If you want to access in __init__ the only way would be to pass a reference
to gameplay layer, but that looks clunky.

Probably I would prefer to make a property of Player like

class Player(cocos.sprite.Sprite):
...
    def on_enter(self):
        self._gameplay_layer = self.get_ancestor(Gameplay)

    def _set_score(self, value):
        self._gameplay_layer.score = value

    def _get_score(self):
        return self._gameplay_layer

    score = property(self._get_score, self._set_score)

Then in other methods of Player you can do
self.score += 10

And outside of Player
player.score += 10
or
gameplay.score +=10

Notice you must be sure player has entered the scene before referencing
player.score, or self._gameplay_layer would be undefined.


> class Gameplay(cocos.layer.Layer):
>     def __init__(self):
>         cocos.layer.Layer.__init__(self)
>         self.player = Player()
>         self.player.position = (director.window.width/2, 50)
>         self.add(self.player)
>         *self.score = 0*
>         self.schedule(self.update)
>
> def main():
>     director.init(width=640, height=480)
>     director.window.set_mouse_visible(False)
>     gameplay_layer = Gameplay()
>     main_scene = cocos.scene.Scene(gameplay_layer)
>     director.run(main_scene)
>
> if __name__ == '__main__':
>     main()
>

-- 
You received this message because you are subscribed to the Google Groups 
"cocos2d discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/cocos-discuss.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to