|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Python Cocos2d Game Development |
| 3 | +# Part 1: Getting Started |
| 4 | + |
| 5 | +# Tutorial: http://jpwright.net/writing/python-cocos2d-game-1/ |
| 6 | +# Github: http://github.com/jpwright/cocos2d-python-tutorials |
| 7 | + |
| 8 | +# Jason Wright ([email protected]) |
| 9 | + |
| 10 | + |
| 11 | +# Imports |
| 12 | +import pyglet |
| 13 | +from pyglet.window import key |
| 14 | + |
| 15 | +import cocos |
| 16 | +from cocos import actions, layer, sprite, scene |
| 17 | +from cocos.director import director |
| 18 | + |
| 19 | +# Player class |
| 20 | + |
| 21 | +class Me(actions.Move): |
| 22 | + |
| 23 | + # step() is called every frame. |
| 24 | + # dt is the number of seconds elapsed since the last call. |
| 25 | + def step(self, dt): |
| 26 | + super(Me, self).step(dt) # Run step function on the parent class. |
| 27 | + # Determine velocity based on keyboard inputs. |
| 28 | + velocity_x = 100 * (keyboard[key.RIGHT] - |
| 29 | + keyboard[key.LEFT]) |
| 30 | + velocity_y = 100 * (keyboard[key.UP] - keyboard[key.DOWN]) |
| 31 | + |
| 32 | + # Set the object's velocity. |
| 33 | + self.target.velocity = (velocity_x, velocity_y) |
| 34 | + # Main class |
| 35 | + |
| 36 | +def main(): |
| 37 | + global keyboard # Declare this as global so it can be accessed within class methods. |
| 38 | + # Initialize the window |
| 39 | + director.init(width=500, height=300, autoscale=True, resizable=True) |
| 40 | + |
| 41 | +# Create a layer and add a sprite to it. |
| 42 | + player_layer = layer.Layer() |
| 43 | + me = sprite.Sprite('sprites/molecule.png') |
| 44 | + player_layer.add(me) |
| 45 | + |
| 46 | + # Set initial position and velocity. |
| 47 | + me.position = (100, 100) |
| 48 | + me.velocity = (0, 0) |
| 49 | + |
| 50 | + # Set the sprite's movement class. |
| 51 | + me.do(Me()) |
| 52 | + |
| 53 | + # Create a scene and set its initial layer. |
| 54 | + main_scene = scene.Scene(player_layer) |
| 55 | + |
| 56 | + # Set the sprite's movement class. |
| 57 | + keyboard = key.KeyStateHandler() |
| 58 | + director.window.push_handlers(keyboard) |
| 59 | + |
| 60 | + # Play the scene in the window. |
| 61 | + director.run(main_scene) |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + main() |
0 commit comments