forked from jpwright/cocos2d-python-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
80 lines (54 loc) · 1.99 KB
/
main.py
File metadata and controls
80 lines (54 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Python Cocos2d Game Development
# Part 2: Scrollable Map
# Tutorial: http://jpwright.net/writing/python-cocos2d-game-2/
# Github: http://github.com/jpwright/cocos2d-python-tutorials
# Jason Wright (jpwright0@gmail.com)
# Imports
import pyglet
from pyglet.window import key
import cocos
from cocos import actions, layer, sprite, scene, tiles
from cocos.director import director
# Player class
class Me(actions.Move):
# step() is called every frame.
# dt is the number of seconds elapsed since the last call.
def step(self, dt):
super(Me, self).step(dt) # Run step function on the parent class.
# Determine velocity based on keyboard inputs.
velocity_x = 100 * (keyboard[key.RIGHT] - keyboard[key.LEFT])
velocity_y = 100 * (keyboard[key.UP] - keyboard[key.DOWN])
# Set the object's velocity.
self.target.velocity = (velocity_x, velocity_y)
scroller.set_focus(self.target.x, self.target.y)
# Main class
def main():
# Declare these as global so they can be accessed within class methods.
global keyboard
global scroller
# Initialize the window.
director.init(width=800, height=600, do_not_scale=True, resizable=True)
# Create a layer and add a sprite to it.
player_layer = layer.ScrollableLayer()
me = sprite.Sprite('human-female.png')
player_layer.add(me)
# Set initial position and velocity.
me.position = (100, 100)
me.velocity = (0, 0)
# Set the sprite's movement class.
me.do(Me())
# Create scroller object and load tiles.
scroller = layer.ScrollingManager()
map_layer = tiles.load('tiles/map.xml')['map0']
# Add map and player layers.
scroller.add(map_layer)
scroller.add(player_layer)
# Create a scene and set its initial layer.
main_scene = scene.Scene(scroller)
# Attach a KeyStateHandler to the keyboard object.
keyboard = key.KeyStateHandler()
director.window.push_handlers(keyboard)
# Play the scene in the window.
director.run(main_scene)
if __name__ == '__main__':
main()