Cocos2 and pyglet Quick Reference (v1.7; © Richard Jones, 2010)

from cocos.director import director director.init(arguments) director.replace(scene) director.push(scene)

director. pop() director.get_window_size() director.get_virtual_coordinates(x, y) director.scene

by default cocos2d will auto-scale requested dimensions to the window size args include all pyglet.window.Window args and do_not_scale*

run the Scene

replace the currently-running Scene with the supplied one

run the supplied Scene with the ability to return to the current one

return to the previous scene after a push()

return the (width, height) of the window

map window coordinates to logical scene coordinates**

the currently-active Scene

director.return_value the value from the last Scene end( ) * turns auto-scaling off director.window the pyglet.window.Window * if auto-scaling is on A cocosnode is a layer, sprite, text, canvas, scene, ... (So sprite.position, layer.scale = .5, scene.pause(), ...)

-add(node), .remove(node), .kill() - schedule (callback)

-pause(), .resume() -are_actions_running() -on_enter(), .on_exit()





from cocos.scene import Scene


class MyScene(cocos.layer.Scene): def _init (self):

from cocos.layer import ...

Layer ()

MultiplexLayer(layer, layer, ...)

PythonInterpreterLayer( )


ColorLayer(r, g, b, a)

class MyLayer(cocos.layer.Layer): def init__(self): is_event_handler = False

from cocos.sprite import Sprite opacity color

from cocos.text import ...

Label(text, position, ...) HTMLLabel(text, position, ...) RichLabel(text, position, ...)

import cocos.tiles

level = cocos.tiles.load(‘my-level.xml’ map = level[‘map-1’ ]

scene = cocos.scene.Scene(map)

... scene.add(layer), sprite.add(text), layer.remove(sprite) or sprite.kill() ... and unschedule() etc. as per pyglet.clock API

pause and resume the execution of actions & scheduled calls

determine whether any actions are running

called as the node enters and leaves the stage (don’t forget to super ( )) pixel that position is relative to; used to transform about*

position in (x,y) coordinates

scale where 1.0 the default value

rotation in degrees * default is center

end the Scene and set director.return_value

initialise at creation; don’t forget to super (MyScene, self). init ()

standard layer containing sprites, text, layers, ... composite layer that displays one layer of many at a time runs an interactive Python interpreter in a Layer

requires the parent to be cocos.layers. ScrollingManager solid color layer

initialise at creation; don’t forget to super (MyLayer, self). init () True to register standard pyglet event handlers on this layer cocos2d adds scaling-aware on_cocos resize(width, height)

sprite = Sprite(‘data/ship.png’ ) Opacity of the sprite where 0 is transparent and 255 is solid color in R,G,B format where 0,0,0 is black and 255,255,255 is white

plain-text label HTML 4.01 subset text label (see pyglet.text.formats.html for details) rich text label with markup as per pyglet.text. DocumentLabel


) manager = cocos.layers.ScrollingManager ( ) manager .add(map) scene = cocos.scene.Scene (manager )

map.set_view(x, y, width, height) manager.set_focus(x, y) Or...

note: use do_not_scale when using tile maps manager.force_focus(x, y)

keboard status handler and key constants

from pyglet.window import key key .RIGHT key .SPACE

keys = key.KeyStateHandler() key .LEFT key.A -> key.Z

director.window.push_handlers (keys) key .UP key. _0 -> key. 9 key . DOWN key. ENTER

from import Menu, MenuItem menu = ‘My Game Title’) menu.create_menu( ([

also EntryMenultem, ToggleMenultem, ImageMenultem, ...

MenuItem('Play', lambda: director.push(TheGameScene())), MenuItem('Quit',])

menu.on_ quit = )

Cocos2 and pyglet Quick Reference (v1.7; © Richard Jones, 2010)

from cocos.actions import ...

MoveBy(delta, duration=5) (,, ...)

Moves the sprite delia=(x, y) pixels

S MoveTo Moves the sprite to position=(x,y) ® JumpBy(delta, height=100, jumps=1, duration=5) Jump the sprite delta=(x, y), height pixels using jumps hops c JumpTo(position, height=100, jumps=1, duration=5) |= Jump the sprite to position=(x,y), height pixels using jumps hops is Bezier(bezier, duration=5) Move the sprite through the bezier curve (cocos.path.Bezier instance) Place(position) Instantly place the sprite at the position=(x, y) a ScaleBy(scale, duration=5) Scale the sprite by scale times c © ScaleTo(scale, duration=5) Scale the sprite to scale E RotateBy(angle, duration=5) Rotate the target by angle degrees RotateTo(angle, duration=5) Rotate the sprite to the given angle Show() Show the sprite Hide() Hide the sprite from view z Blink(blinks, duration) Blink the sprite the number of blinks over the duration seconds io Toggle Visibility() Show if hidden and hide if shown $ Fadeln(duration) Fade the sprite into view over duration seconds FadeOut(duration) Fade the sprite out of view over duration seconds FadeTo(opacity, duration) Fade the sprite to a specific opacity over duration seconds is Accelerate(action, rate=2) Accelerate the action at its end by the given rate (1 is linear) @ AccelDeccel(action) Accelerate the action in its middle 3 Speed(action, rate) Speed up or slow down the action by the given rate (1 is normal) = Reverse(action) Perform the action in reverse < Sequence(action, action) (+ operator) Execute actions in sequence = Spawn(action, action) (| operator) Execute actions at the same time 5 Repeat(action) Repeat an action (or composite set of actions) forever Loop(action, times) (* operator) Loop the action n times Delay(time) Delay for time seconds i RandomDelay(low, high) Delay for some seconds below low and high 8 CallFunc(callable) Invoke the callable (with no arguments) ma CallFuncS(callable) Invoke the callable with the sprite as the first argument OrbitCamera(spherical coordinate arguments) Orbits the camera around the center of the screen Move() Move the sprite based on sprite parameters (velocity, acceleration, ...) ¢ BoundedMove(width, height) As above but limit movement to 0 < x < width and 0 <y < height S WrappedMove(width, height) As above but wrap movement outside 0 < x < width and 0 < y < height Driver() Drive the sprite like a car using sprite parameters (direction, speed, ...) class MyAction(cocos.actions.Action): def init(self): gets called at initialization time, before a target is defined def step(self, dt): called every frame with dt being the number of seconds since last call def done(self): return False while the step method must be called def start(self): start executing an action; is assigned and this method is called def stop(self): after we finish executing an action this method is called class MyIntervalAction(cocos.actions.IntervalAction) : def update(self, t): called every frame with tranging from O..1

(also init, start and stop)

Cocos2 and pyglet Quick Reference (v1.7; © Richard Jones, 2010)

import pyglet

window = pyglet.window.Window(...)

registering event handlers def on_draw(): window.clear()

window. push_handlers(on_draw) class MyClass(object):

def on_draw(self):

def on_text(self, text): my object = MyClass() window. push _handlers(my_object)

Window arguments fullscreen

width=640, height=480 resizable=False vsync=True caption=sys.argv[0] config=None screen=None

Image handling

pyglet.image.load(filename, file=None)

SolidColorImagePattern CheckerImagePattern image.width, image.height image.anchor_ x, image.anchor _y image.blit(x, y, 2=0), file=None) image.texture, texture.tex_coords

create a window with optional arguments run pyglet’s main loop to handle events

see next page for all possible window event names clear the window to the color put your other drawing code here

push the on_draw handler to the window

return pyglet.event.EVENT_HANDLED (True) if the event has been handled push al/ handlers defined on my_object onto the window’s event stack

(there are other arguments, these are just the most common) make the window fullscreen

create the window with these dimensions (ignored if fullscreen) allow the user to resize the window

synchronise to the monitor to avoid flicker

set the window title text

a display config as per

the screen to use if fullscreen

load the image from the named file or supplied file object

create an image filled with a single color

create an image with a tileable checker image of two colors image dimensions in pixels

coordinate of anchor, relative to bottom-left corner of image render the image to the active framebuffer

save the image as a PNG file

a pyglet.image. Texture view of this image

OpenGL texture target and id

12-tuple of float texture coordinates (may not be simply 0 and 1)

get_buffer_manager().get_color_buffer() get the active framebuffer as an Image load_animation(filename, file=None) load an animation from a file - currently only GIF is supported

Animation.from_image_sequence(sequence, period, loop=False) create an animation from a sequence of images

Sprites (all attributes are re-assignable) pyglet.sprite.Sprite(image, ...) create a sprite from the image or Animation instance sprite.position position of the sprite in (x, y) (also as sprite.x, sprite.y) sprite.image image rendered for the sprite (image anchor is honored) sprite.rotation sprite rotation in degrees

amount to scale the sprite image by - 1.0 is unscaled

control transparency - 0 is fully transparent, 255 is fully opaque coloring of sprite image, normal (white) is R, G, B (255, 255, 255) boolean controlling sprite visibility

render the sprite to the active framebuffer

sprite.scale sprite.opacity sprite.color sprite.visible sprite.draw()

Text rendering pyglet.text.Label(text, ...) pyglet.text.HTMLLabel(text, ...) text.draw()

(see the docs for the complete, extensive set of options you may pass) lay out some plain text

lay out some HTML (4.01, limited) text

render the laid-out text

Media playback, file=None) load the media file (audio, video or both) as a “source” source.audio_format an instance of or None if no audio source.video_format an instance of VideoFormat or None if no video a giving title, author, etc. if known convenience method to immediately play the source

create a player to manage playback; see possible events below queue the source to be played

control playback

report current position and seek to a different time

get the current video frame as a pyglet.image. Texture

the action the player will take when it reaches the end of the current source

player = Player()

player. queue(source), -pause(), .stop() player.time, player.get_texture() player.eos_action

Cocos2 and pyglet Quick Reference (v1.7; © Richard Jones, 2010)

Graphics abstraction batch up graphics drawing operations pyglet.sprite.Sprite(image, batch=batch) create a sprite belonging to the batch batch.draw() much faster than individual sprite.draw() calls group common OpenGL state objects in a batch

arbitrarily order objects in a batch (typically for display sorting) enable and bind a texture for a group of objects in a batch batch.add(count, mode, group, *data) create an OpenGL vertex list in the batch using data’s items batch.add(count, mode, group, indices, *data) create an OpenGL indexed vertex list

# draw a white line from (0, 1) to (1, 0)

vertex list = batch.add(2, GL_LINES, None, ('v2f', (0.0, 1.0, 1.0, 0.0)),


pyglet.resource.image( filename) filename) pyglet.resource.add_font( filename) pyglet.resource.file( filename) pyglet.resource.location( filename) pyglet.resource.path pyglet.resource.reindex()

Clock handling pyglet.clock.schedule(callback) ...-unschedule(callback) ...schedule_ interval(callback, n) -.--schedule once(callback, n)

fps = pyglet.clock.ClockDisplay()

pyglet media player events on_player_eos()

on_ source group _ eos() on_eos()

pyglet window events

on_key press(symbol, modifiers) on_key release(symbol, modifiers) on_text(text) on_text_motion(motion)

on_text motion select(motion)

on_mouse press(x, y, button, modifiers) on_mouse_release(x, y, button, modifiers)

on_mouse motion(x, y, dx, dy)

on_mouse drag(x, y, dx, dy, buttons, modifiers)

on_mouse_scroll(x, y, dx, dy) on_mouse enter(x, y)

on mouse leave(x, y) on_resize(width, height) on_draw()





on_move(x, y) on_activate() on_deactivate() on_context_lost() on_context_state_lost()

pyglet sprite event on_animation_end

('c4B', (255, 255, 255, 255) * 2))

abstract storage of application resources in directories or ZIP files load the named image file

load the named media file

make a font available to pyglet’s text rendering

open the named resource file, returning a file object

return the location of the resource file (only useful for on-disk files) list containing the places to look for resources

should be called if the path is modified

note: automatically calls pyglet.clock.tick()

callback when the clock is ticked, passing the seconds since last call remove callback from the schedule

callback every n seconds

callback once in n seconds

a simple FPS counter .. use fps.draw() to display

the player has run out of sources the current source group has run out of data the current source has run out of data

symbol and modifiers as in pyglet.window.key keys and MOD_ as above

text is a unicode string of the text input

motion as in pyglet.window.key.MOTION_*

as above but during a text selection event (MOD_SHIFT held) buttons and modifiers pressed at position (x, y)

as above but buttons released

mouse absolute (x, y) and movement (dx, dy) since last event as above but with buttons and modifiers held mouse scroll wheel scrolled by (dx, dy) at position (x, y) mouse entered window

mouse exited window

the window has been created or resized

application should draw (not relevant to cocos2d)

window has been made visible (or created)

window has been hidden

window close button pressed

redraw is needed

window has been moved to position (x, y)

window has been activated (focused)

window has been deactivated (lost focus)

window’s OpenGL context was lost (no drawing possible) window’s OpenGL context state was destroyed by pyglet

the sprite’s image animation has ended