| |
- __builtin__.object
-
- gummworld2.basicmap.BasicLayer
- gummworld2.basicmap.BasicMap
-
- gummworld2.tiledmap.TiledMap
- gummworld2.basicmaprenderer.BasicMapRenderer
- gummworld2.camera.Camera
- gummworld2.context.Context
-
- gummworld2.engine.Engine
- gummworld2.gameclock.GameClock
- gummworld2.hudlight.HUD
- gummworld2.popup_menu.PopupMenu
- gummworld2.screen.View
-
- gummworld2.screen.Screen
- gummworld2.spatialhash.SpatialHash
- gummworld2.state.State
- gummworld2.subpixel.SubPixelSurface
- gummworld2.supermap.MapHandler
- gummworld2.supermap.SuperMap
- gummworld2.vec2d.Vec2d
class BasicMap(__builtin__.object) |
| |
Methods defined here:
- __init__(self, width, height, tile_width, tile_height)
- Construct a BasicMap object.
- collapse(self, collapse=(1, 1), which_layers=None)
- Collapse which_layers by joining num_tiles into one tile. The
original layers are replaced by new layers.
The collapse argument is the number of tiles on the X and Y axes to
join.
The collapse_layers argument is a sequence of indices indicating to
which TiledMap.layers the collapse algorithm should be applied. See the
tiledmap.collapse_map.
- get_layer(self, layer_index)
- get_layers(self, which_layers=None)
- merge_layers(self, which_layers=None)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class BasicMapRenderer(__builtin__.object) |
| |
Methods defined here:
- __init__(self, basic_map, tile_size=0, max_scroll_speed=10)
- clear(self)
- clear all tile caches
- draw_tiles(self)
- draw the visible tiles on the screen
- get_rect(self)
- get_tiles(self)
- call once per tick to calculate visible tiles
The constructor does this automatically, and it is done each time
set_rect() is called. It may be necessary to call get_tiles()
manually depending on the implementation; for example, if the
renderer object is created before the map is loaded.
- set_dirty(self, *areas)
- specify areas to re-render
The areas argument must be one or more pygame.Rect.
Marking areas dirty is necessary only if the underlying BasicMap
tiles are procedurally modified during runtime. Though it involves
some management, it is potentially much more efficient than
triggering the entire view be recreated.
- set_rect(self, **kwargs)
- set the world location of the renderer's view rect
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- basic_map
- lifespan
- max_scroll_speed
- tile_size
Data and other attributes defined here:
- DEFAULT_LIFESPAN = 60
|
class Camera(__builtin__.object) |
|
A Camera provides a few services:
* Track a moving target in world coordinates.
* Convert coordinates between world and screen space.
* Interpolated view scrolling to take advantage of higher frame rates.
Dependencies:
* A target with a Vec2d attribute target.position.
* A surface from which to derive its viewing dimensions.
* State.clock is needed by interpolate().
To use the camera do the following:
1. In the game's update routine set camera.position to move the target.
2. Also in the game's update routine call Camera.update() to update the
camera's state.
3. In the game's draw routine call Camera.interpolate() to micro-update
the scrolling between the position prior to step 1 and final
position specified in step 1. This may sound complicated, but it is
all handled behind the scenes.
Screen-to-world and world-to-screen conversions are used to convert between
world coordinates and screen coordinates.
Note that using mouse position can be tricky if the camera is using a
subsurface of the screen, or an alternate surface. pygame always reports
mouse position relative to the top-level surface. Keep this in mind when
positioning graphics based on the mouse position under these circumstances.
Sometimes it may just be simplest, for example, to blit directly to the
top-level surface.
If creating multiple cameras to save and restore in State contexts, by
default the state_restored() method updates the new camera from the old.
This solves a split-brain condition that occurs when the cameras' internals
fall out of sync. In some scenarios you may want to have two independent
cameras. To prevent them from syncing during a restore, set the cameras'
update_when_restored=False. |
|
Methods defined here:
- __init__(self, target, view=None)
- Construct an instance of Camera.
The target argument is the object that camera should track. target must
have a position attribute which is its location in world coordinates.
The view argument is the screen.View object upon which to base
conversions between world and screen space. The view.surface attribute
is exposed view the Camera.surface property.
- anti_interp(self, obj)
- Return x,y to reverse interpolation jitter on an object
obj must have a pygame rect attribute.
Example:
screen.blit(thing.image, thing.rect.move(camera.anti_interp))
- init_position(self, pos)
- Hard set position to pos.
This circumvents interpolation, which may be desirable if for example
setting the initial position of the camera, or moving the camera a
great distance when you don't want it to pan.
- interpolate(self, *args)
- Interpolate camera position towards target for smoother scrolling
After updating the target position in the main program's update(), call
this every frame in the main program's draw() before any drawing
commands. It works best when frame speed is much higher than update
speed.
- screen_to_world(self, xy)
- Convert coordinates from screen space to world space.
- state_restored(self, prev)
- Sync a stale camera after swapping it in.
If switching states either manually, you may want to call this to
avoid video flashing or whizzing by. This typically happens when using
Camera.interpolate() and swapping in the old camera, which has stale
values in the _move_to and _move_from attributes. When swapping a camera
in via State.restore(), this method is called automatically.
- update(self, *args)
- Update Camera internals to prepare for efficient interpolation.
Call in the game's update routine after changing Camera.position.
- world_to_screen(self, xy)
- Convert coordinates from world space to screen space.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- abs_offset
- Offset position camera.subsurface inside its top level parent surface.
This is equivalent to camera.surface.get_abs_offset(). The value is
cached whenever the camera.surface attribute is set.
- abs_screen_center
- The absolute coordinates of the camera surface's center.
In general, this is typically useful in mouse-map calculations.
This is equivalent to camera.surface.get_rect().center +
camera.surface.abs_offset(). The value is cached whenever the
camera.surface attribute is set.
- interp
- The clock's interpolation value after the last call to
Camera.interpolate.
- position
- Move Camera.target in world coordinates.
- screen_center
- The coordinates of the camera surface's center.
In general, this is typically useful in screen-map calculations.
This is equivalent to camera.surface.get_rect().center. The value is
cached whenever the camera.surface attribute is set.
- steady_target_position
- Return x,y to reverse interpolation jitter on the camera target
Example:
screen.blit(thing.image, thing.rect.move(camera.steady_target_position))
- surface
- The surface from which to derive the viewing dimensions.
- target
- The target that camera is tracking.
- view
- The view from which to derive the surface and viewing dimensions and,
for subsurfaces, the rect for the subsurface in the parent surface.
|
class Context(__builtin__.object) |
| |
Methods defined here:
- __init__(self)
- draw(self, dt)
- Refresh the screen
- enter(self)
- Called when this context is pushed onto the stack.
- exit(self)
- Called when this context is popped off the stack.
- resume(self)
- Called when another context is popped off the top of this one.
- suspend(self)
- Called when another context is pushed on top of this one.
- update(self, dt)
- Called once per frame
Static methods defined here:
- pop(n=1)
- push(c, do_enter=True)
- top()
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class Engine(gummworld2.context.Context) |
| |
- Method resolution order:
- Engine
- gummworld2.context.Context
- __builtin__.object
Methods defined here:
- __init__(self, screen_surface=None, resolution=None, display_flags=0, caption=None, camera_target=None, camera_view=None, camera_view_rect=None, map=None, tile_size=None, map_size=None, update_speed=30, frame_speed=30, world_type=0, set_state=True)
- Construct an instance of Engine.
This constructor does the following:
The pygame display is initialized with an optional caption, and the
resulting screen.Screen object is placed in State.screen.
An empty map.BasicMap object is created and placed in State.map.
An empty model.World* object is created and placed in State.world.
State.world_type is set to one of the engine.*_WORLD values
corresponding to the world object in State.world.
A camera.Camera object is created and placed in State.camera. The
camera target is either taken from the camera_target argument, or an
appropriate target for world type is created. The target is *NOT*
added to the world, as the target does not need to be an object
subject to game rules. If target happens to be an avatar-type object
then add it manually to world with the rest of the world entities.
A game_clock.GameClock object is created and placed in State.clock.
Joystick objects are created for connected controllers.
The following arguments are used to initialize a Screen object:
The screen_surface argument specifies the pygame top level surface
to use for creating the State.screen object. The presence of this
argument overrides initialization of the pygame display, and
resolution and display_flags arguments are ignored. Use this if
the pygame display has already been initialized in the calling
program.
The resolution argument specifies the width and height of the
display.
The display_flags argument specifies the pygame display flags to
pass to the display initializer.
The caption argument is a string to use as the window caption.
The following arguments are used to initialize a Camera object:
The camera_target argument is the target that the camera will track.
If camera_target is None, Engine will create a default target
appropriate for the world type.
The camera_view argument is a screen.View object to use as the
camera's view.
The camera_view_rect argument specifies the pygame Rect from which
to create a screen.View object for the camera's view.
State.screen.surface is used as the source surface. This argument is
ignored if camera_view is not None.
The following arguments are used to initialize a BasicMap object:
The tile_size and map_size arguments specify the width and height of
a map tile, and width and height of a map in tiles, respectively.
The following arguments are used to initialize a model.World* object:
The world_type argument specifies which of the world classes to
create. It must be one of engine.NO_WORLD, or engine.SIMPLE_WORLD.
The following arguments are used to initialize a Clock object:
update_speed specifies the maximum updates that can occur per
second.
frame_speed specifies the maximum frames that can occur per second.
The clock sacrifices frames per second in order to achieve the desired
updates per second. If frame_speed is 0 the frame rate is uncapped.
Engine.update() and Engine.draw() are registered as callbacks in the
clock.
- draw(self, interp)
- Override this method. Called by run() when the clock signals a
frame cycle is ready.
Suggestion:
State.screen.clear()
... custom draw the screen ...
State.screen.flip()
- enter(self)
- Called when the context is entered.
If you override this, make sure you call the super.
- on_active_event(self, gain, state)
- # Override an event handler to get specific events.
- on_joy_axis_motion(self, joy, axis, value)
- on_joy_ball_motion(self, joy, ball, rel)
- on_joy_button_down(self, joy, button)
- on_joy_button_up(self, joy, button)
- on_joy_hat_motion(self, joy, hat, value)
- on_key_down(self, unicode, key, mod)
- on_key_up(self, key, mod)
- on_mouse_button_down(self, pos, button)
- on_mouse_button_up(self, pos, button)
- on_mouse_motion(self, pos, rel, buttons)
- on_quit(self)
- on_user_event(self, e)
- on_video_expose(self)
- on_video_resize(self, size, w, h)
- resume(self)
- Called when the context is resumed.
If you override this, make sure you call the super.
- set_state(self)
- update(self, dt)
- Override this method. Called by run() when the clock signals an
update cycle is ready.
Suggestion:
move_camera()
State.camera.update()
... custom update the rest of the game ...
Data descriptors defined here:
- joysticks
- List of initialized joysticks.
Data and other attributes defined here:
- NO_WORLD = 0
- SIMPLE_WORLD = 1
Methods inherited from gummworld2.context.Context:
- exit(self)
- Called when this context is popped off the stack.
- suspend(self)
- Called when another context is pushed on top of this one.
Static methods inherited from gummworld2.context.Context:
- pop(n=1)
- push(c, do_enter=True)
- top()
Data descriptors inherited from gummworld2.context.Context:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class GameClock(__builtin__.object) |
| |
Methods defined here:
- __init__(self, max_ups=30, max_fps=0, use_wait=False, time_source=<built-in function time>, update_callback=None, frame_callback=None, paused_callback=None)
- pause(self)
- Pause the clock so that time does not elapse.
While the clock is paused, no schedules will fire and tick() returns
immediately without progressing internal counters. Game loops that
completely rely on the clock will need to take over timekeeping and
handling events; otherwise, the game will appear to deadlock. There are
many ways to solve this scenario. For instance, another clock can be
created and used temporarily, and the original swapped back in and
resumed when needed.
- resume(self)
- Resume the clock from the point that it was paused.
- schedule_interval(self, func, interval, life=0, args=[])
- Schedule an item to be called back each time an interval elapses.
While the clock is paused time does not pass.
Parameters:
func -> The callback function.
interval -> The time in seconds (float) between calls.
life -> The number of times the callback will fire, after which the
schedule will be removed. If the value 0 is specified, the event
will persist until manually unscheduled.
args -> A list that will be passed to the callback as an unpacked
sequence, like so: item.func(*[item.interval]+item.args).
- tick(self)
- unschedule(self, func)
- Unschedule managed functions. All matching items are removed.
- unschedule_by_id(self, id)
- Unschedule a single managed function by the unique ID that is
returned by schedule_interval().
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- game_time
- Virtual elapsed time in game milliseconds.
- interpolate
- max_fps
- max_ups
- paused
- The real time at which the clock was paused, or zero if the clock
is not paused.
|
class HUD(__builtin__.object) |
|
HUD class for a basic Heads Up Display
Not supported:
- Per-item details (font, size, style, antialias, color).
Tips and tricks:
Color arguments may be string names, color sequences, or pygame.Color.
Note the difference between set_color(None) and set_background(None). The former is ignored. The latter
has the side effect of making the background transparent.
set_bold() and set_italic() are software rendering effects. If bold and italic fonts exist they give
more pleasing results.
If you want per-item details (font, size, style, antialias, color) or want to use HUD in a more robust
dashboard-like way, you can make multiple HUDs with custom x, y positions. If you want to calculate
their size for positioning, use the hud_size() method, keeping in mind that changing SysFont styles,
font file, etc. will change the rendered size. One can use the same trick with the HUD that is often
done with words: render the longest strings with the widest character (usually "W") and then remember
the size for layout calculations.
The font items are rendered in the order they are added. Order can be rearranged at any time by
modifying the hud.order list, which is simply a list of the item names. When modifying hud.order and/or
hud.items take care to keep the contents one-to-one. |
|
Methods defined here:
- __init__(self, fontname=None, fontsize=24, sysfontname='sans', bold=False, italic=False, underline=False, color='gold', background=None, gcolor=None, ocolor=None, scolor=None, owidth=1, shadow=(1, 1), antialias=True, alpha=1.0)
- create a basic HUD
The defaults are simply sysfont_name='sans', fontsize=16, antialias=True.
Positioning is anchored at topleft. Modify via x and y attribute. The default is 10, 10.
Vertical spacing for items is 3 pixels by default. Modify via space attribute.
:param fontname: the name of a font file
:param fontsize: point size of the font
:param sysfontname: the name of a system font
:param bold: boolean
:param italic: boolean
:param underline: boolean
:param color: text foreground color
:param background: text background color
:param gcolor: text gradient color
:param ocolor: text outline color
:param scolor: text shadow color
:param owidth: int (float?), width in pixels of outline
:param shadow: tuple of int, (x, y) offset for drop shadow
:param antialias: boolean
:param alpha: float, valid values are 0.0 - 1.0
:return: HUD
- add(self, name, text, *args, **kwargs)
- add a HUD item
HUD items are rendered in the order they are added. Order can be rearranged at any time by modifying
hud.order, which is simply a list of the item names.
An item can use varargs or kwargs, not both. The choice is enforced when the item is updated.
:param name: unique ID
:param text: format text compatible with str.format()
:param args: arguments for str.format()
:param kwargs: optional, callback=func
:return: None
- draw(self, surf)
- draw all the items
:param surf: target surface
:return: None
- fps(self)
- get_alpha(self)
- get_antialias(self)
- get_background(self)
- get_bold(self)
- get_color(self)
- get_font(self)
- get the current font object
:return: pygame.font.Font
- get_fontname(self)
- get_fontsize(self)
- get_gcolor(self)
- get_italic(self)
- get_ocolor(self)
- get_owidth(self)
- get_scolor(self)
- get_shadow(self)
- get_sysfontname(self)
- get_underline(self)
- hud_size(self)
- get the total rendered size of the HUD (may change depending on style, etc.)
:return: w, h
- set_alpha(self, alpha)
- change the surface alpha value
Valid values are 0.0 to 1.0.
:param alpha: int, 0 to 255; if None it is disabled
:return: self
- set_antialias(self, boolean)
- render antialiased font
:param boolean
:return: self
- set_background(self, color)
- change background color
If color is None, the background will be transparent.
:param color: a pygame.Color, color sequence, or name string
:return: self
- set_bold(self, boolean)
- change the bold style
:param boolean
:return: self
- set_color(self, color)
- change foreground color
:param color: a pygame.Color, color sequence, or name string
:return: self
- set_font(self, fontname=None, fontsize=None, sysfontname=None, bold=None, italic=None, underline=None)
- change font
If any of the args are not specified the instance variables are used. The instance variables are
updated to reflect the supplied values.
Font creation and re-rendering of items is triggered.
:param fontname: the name of a font file
:param fontsize: point size of the font
:param sysfontname: the name of a sysfont
:param bold: boolean
:param italic: boolean
:param underline: boolean
:return: self
- set_fontname(self, name)
- change the font source to a file font
:param name: the name of a font file or system font
:return: self
- set_fontsize(self, fontsize)
- change the font size
:param fontsize: int
:return: self
- set_gcolor(self, color=None)
- change gradient color
If color is None, the gradient effect will be removed.
:param color: a pygame.Color, color sequence, or name string
:return: self
- set_italic(self, boolean)
- change the italic style
:param boolean
:return: self
- set_ocolor(self, color=None)
- render an outline color
If color is None, the outline effect will be removed.
:param color: a pygame.Color, color sequence, name string, or None
:return: self
- set_owidth(self, width)
- set outline width
:param width: int >= 0
:return: self
- set_scolor(self, color=None)
- render a drop shadow color
If color is None, the shadow effect will be removed.
:param color: a pygame.Color, color sequence, name string, or None
:return: self
- set_shadow(self, shadow)
- set the x, y distance in pixels to project the shadow
:param shadow: tuple of two ints; the offset of the shadow; e.g. (1, 1), (0, 1), (-2, -2)
:return: self
- set_sysfontname(self, name)
- change the font source to a sysfont
:param name: the name of a font file or system font
:return: self
- set_underline(self, boolean)
- change the underline style
:param boolean
:return: None
- update(self, *args)
- update all items, using the callbacks provided with add()
Logic uses the type of the value passed in add() to determine how to update the value.
The order of evaluation is dict, str, sequence, then discrete value.
:param args: not used; for compatibility with timers, etc. that supply args by default
:return: None
- update_item(self, name, *args, **kwargs)
- update the value of an item (does not invoke the callback)
If the item was created with varargs, then the item must be updated with varargs. If item was created with
kwargs, if must be updated with kwargs.
:param name: item's name
:param args: item's new value
:return: None
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class MapHandler(__builtin__.object) |
|
A MapHandler object is responsible for sensing when triggers have been
tripped by a triggering rect (e.g. the camera), and loading and unloading
its map. |
|
Methods defined here:
- __init__(self, name, **kwargs)
- Construct a MapHandler object.
name is a tuple representing the 2D vector of this map in the SuperMap.
The position in the SuperMap is relative to the origin map, so negative
values are valid.
kwargs are user-defined arguments that can be used by the overloaded
methods.
Attributes:
name : The name argument from the constructor.
map_file : The map_file argument from the constructor.
rect : The bounding rect of this map in world space.
supermap : The parent SuperMap object.
map : The map object containing tiles. Current supported: BasicMap
and TiledMap.
triggers : The list of trigger objects linking this map to
neighboring maps.
timestamp : The time that this handler was last updated.
- __str__(self)
- enter(self)
- Optional. Override this class to perform actions when the map is
promoted to SuperMap.current.
- exit(self)
- Optional. Override this class to perform actions when the map is
demoted from SuperMap.current.
- get_objects(self, map_range)
- Return a dict of tiles in the specified bounds.
supermap_range is a dict of range specifications, such as returned by
SuperMap.get_tile_range_in_rect().
- get_objects_in_rect(self, rect)
- Return a dict of objects that intersect rect.
rect is a pygame.Rect expressed in world coordinates.
- get_tile_range_in_rect(self, rect)
- Return a list of tile ranges, one for each layer, that intersect
rect.
rect is a pygame.Rect expressed in world coordinates.
- load(self)
- Override this class. It must set self.map to a valid BasicMap or
TiledMap object.
This stub method does absolutely nothing to manage the map. To load the
tile map, call the appropriate loader.
Considerations:
If a map is loaded (self.map is not None), this method will not be
called.
If a map was loaded, the unload method does not necessarily have to
completely shut down a map. For example, Tiled maps can provide data
for non-tile objects. Such object may have AI, or otherwise serve
a purpose in the game logic. *IF* the tiles were unloaded but the
objects were not, then you will need to extend this class to handle
that situation since it will be desirable to reload the tiles on
demand but undesirable to create more objects.
- local_to_world(self, xy)
- Convert a 2D vector in local space to a 2D vector in world space.
This conversion is needed to translate maps, which use local space.
- run_triggers(self, triggering_rect)
- Run all triggers in this map versus the triggering_rect.
The triggering rect is typically the camera rect. It is collision-
checked against each trigger's rect to assess if neighboring map needs
to be loaded.
- unload(self)
- Optional. Override this class to perform actions, such as saving the
state of dynamic context, when the map is unloaded from memory.
This stub method does absolutely nothing to manage the map. To unload
the tile map, set self.map=None.
- update(self, dt, *args)
- Optional. Override this class to perform actions when the map is
updated via SuperMap.update().
- world_to_local(self, xy)
- Convert a 2D vector in world space to a 2D vector in local space.
This conversion is needed to translate maps, which use local space.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- neighbors
|
class PopupMenu(__builtin__.object) |
|
popup_menu.PopupMenu
PopupMenu(data, block=True) : return menu
data -> list; the list of strings and nested lists.
pos -> tuple; the xy screen coordinate for the topleft of the main menu; if
None, the mouse position is used.
block -> boolean; when True popup_menu will run its own event loop, blocking
your main loop until it exits; when False popup_menu.get_events() will
intercept events it cares about and return unhandled events to the
caller.
Note: For a non-blocking menu, use the NonBlockingPopupMenu instead. This
class supports non-blocking, but it is more cumbersome to use than the
NonBlockingPopupMenu class.
The first string in the data list is taken as the menu title. The remaining
strings are menu items. A nested list becomes a submenu. Submenu lists must
also contain strings for menu title and menu items. Submenus can be
theoretically infinitely nested.
The menu runs a mini event loop. This will block the caller until it exits.
Upon exiting, the screen is restored to its prior state.
Left-clicking outside the topmost menu will quit the entire menu. Right-
clicking anywhere will close the topmost submenu; if only the main menu
remains the menu will exit. Left-clicking a menu item in the topmost menu
will post a USEREVENT for the caller to process.
The USEREVENT will have attributes: code='MENU', name=popup_menu.name,
item_id=menu_item.item_id, text=menu_item.text. name is first element in a
menu data list. item_id corresponds to the Nth element in a menu data list,
incremented from 0; submenu items count as one menu_id even though they are
never posted in an event. text is the string value of the Nth element in the
menu data list. Thus, combinations of name and menu_id or name and text can
be used to uniquely identify menu selections.
Example menu data and resulting event data:
['Main', # main menu title
'Item 0', # name='Main', menu_id=0, text='Item 0'
['Submenu', # submenu title
'Item 0', # name='Submenu', menu_id=0, text='Item 0'
'Item 1', # name='Submenu', menu_id=0, text='Item 1'
],
'Item 2', # name='Main', menu_id=2, text='Item 2'
]
High-level steps for a blocking menu:
1. Fashion a nested list of strings for the PopupMenu constructor.
2. Upon creation, the menu runs its own loop.
3. Upon exit, control is returned to the caller.
4. Handle the resulting USEREVENT event in the caller where
event.name=='your menu title', event.item_id holds the selected item
number, and event.text holds the item label.
High-level steps for a non-blocking menu:
Note: This usage exists to support the NonBlockingPopupMenu class and
custom non-blocking implementations; for typical use NonBlockingPopupMenu
is recommended.
1. Fashion a nested list of strings for the PopupMenu constructor.
2. Store the menu object in a variable.
3. Devise a means for the main loop to choose whether to draw the menu and pass
it events.
4. Call menu.draw() to draw the menu.
5. Pass pygame events to menu.handle_events() and process the unhandled events
that are returned as you would pygame's events.
6. Upon menu exit, one or two USEREVENTs are posted via pygame. Retrieve
them and recognize they are menu events (event.code=='MENU').
a. The menu-exit event signals the main loop it has exited, with or
without a menu selection. Recognize this by event.name==None. Upon
receiving this event the main loop should stop using the menu's
draw() and get_events() (until the next time it wants to post the
menu to the user).
b. The menu-selection event signals the main loop that a menu item was
selected. Recognize this by event.name=='your menu title'.
event.menu_id holds the selected item number, and event.text holds
the item label.
7. Destroying the menu is not necessary. But creating and destroying it may
be a convenient means to manage the menu state (i.e. to post it or not). |
|
Methods defined here:
- __init__(self, data, pos=None, block=True)
- draw(self)
- handle_events(self, events, block=False)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class Screen(View) |
|
The pygame display.
Assign one of these to State.screen in order to make the library aware of
the main display surface. |
|
- Method resolution order:
- Screen
- View
- __builtin__.object
Methods defined here:
- __init__(self, size=0, flags=0, surface=None)
- Initialize the pygame display.
If surface is specified, it is used as the screen's surface and pygame
display initialization is not performed.
Otherwise, size and flags are used to initialize the pygame display.
Static methods defined here:
- flip()
- Flip the pygame display.
Methods inherited from View:
- blit(self, surf, pos, area=None, special_flags=0)
- Blit a surface to this surface.
- clear(self)
- Fill the surface with self.fill_color.
- fill(self, color, rect=None, special_flags=0)
- Fill this surface with color.
Data descriptors inherited from View:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- abs_offset
- The absolute offset of the subsurface.
- center
- The center coordinate of the surface.
- height
- The height of the surface.
- size
- The size of the surface.
- width
- The width of the surface.
|
class SpatialHash(__builtin__.object) |
| |
Methods defined here:
- __contains__(self, obj)
- __init__(self, cell_size=50)
- __iter__(self)
- This method honors self.sort_key.
- __len__(self)
- __repr__(self)
- __str__(self)
- add(self, entity)
- Add or re-add obj. Return True if in bounds, else return False.
If this method returns False then the object is completely out of
bounds and cannot be stored in this space.
Note that when obj changes its position, you must add it again so that
its cell membership is updated. This method first removes the object if
it is already in the spatial hash.
- addlist(self, entities)
- clear(self)
- Clear all objects.
- collide(self, entity)
- Return list of entities that collide with entity.
- collidealldict(self, rect=None)
- Return dict of all collisions.
If rect is specified, only the cells that intersect rect will be
checked.
The contents of the returned dict are: {entity: [entity, ...}
- collideany(self, entity)
- Return True if entity collides with any other object, else False.
- collidedict(self, entities)
- Return dict of entities that collide with entities.
- get_cell(self, cell_id)
- Return the cell stored at bucket index cell_id.
The returned cell is a list of entities. None is returned if a cell does
not exist for cell_id.
- get_cell_pos(self, cell_id)
- Return the world coordinates for topleft corner of cell.
- get_nearby_entities(self, entity)
- Return a list of entities that share the same cells as entity.
This method honors self.sort_key.
- index(self, cell)
- Return the bucket index of cell.
Returns None if cell does not exist in buckets.
Note that SpatialHash.buckets.index(cell) does *NOT* work because
list.index() tests equality, not identity.
- index_at(self, x, y)
- Return the cell_id of the cell that contains point (x,y).
None is returned if point (x,y) is not in bounds.
- intersect_cell_ids(self, rect)
- Return list of cell ids that intersect rect.
The return value is a list of int. Each int is a key for self.buckets. Note: the values are NOT checked for
presence in buckets; so if self.buckets[i] is accessed directly, empty buckets may be accidentally created.
:param rect: pygame.Rect; bounding rect
:return: list of int
- intersect_entities(self, rect)
- Return list of entities whose rects intersect rect.
This method honors self.sort_key.
- remove(self, entity)
- removelist(self, entities)
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- entities
- Return the entire list of entities.
This method honors self.sort_key.
|
class State(__builtin__.object) |
|
state.State
The State class stores runtime objects and settings for easy global access.
It is not intended to be instantiated.
Descriptions of class attributes:
name: The name of the current state context. This can be any immutable
value. Initial value is 'init', and the state is saved so that State
can be reset via State.restore('init').
screen: A Screen object, which is a wrapper for the top level
pygame surface.
world: A model.World* object used to store game model entities.
world_type: engine.NO_WORLD or engine.SIMPLE_WORLD if State was
initialized via the Engine class. Else it is None.
camera: A Camera object.
map: A BasicMap, TiledMap, or SuperMap object.
Class variable State.default_attrs holds the list of attributes that are
saved and restored by default when the static methods State.save() and
State.restore() are called. Modify default_attrs as desired. |
|
Static methods defined here:
- restore(name, attrs=['world', 'world_type', 'map', 'camera'])
- state.restore() - restore a state context by name
State.name is set to the value of the name argument.
The attrs argument is a sequence of strings naming the State attributes
to restore. If attrs is not specified then State.default_attrs is used.
If an object that is being restored has state_restored() method it will
be called. The method is intended to sync the object with other parts of
the game that may have updated while it was swapped out.
- save(name, attrs=['world', 'world_type', 'map', 'camera'])
- state.save() - save a state context by name
The attrs argument is a sequence of strings naming the State attributes
to save. If attrs is not specified then State.default_attrs is used.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
Data and other attributes defined here:
- camera = None
- camera_target = None
- clock = None
- default_attrs = ['world', 'world_type', 'map', 'camera']
- hud = None
- init_attrs = ['screen', 'world', 'world_type', 'camera', 'map', 'clock', 'menu', 'running', 'speed', 'dt', 'show_grid', 'show_labels']
- map = None
- menu = None
- name = 'init'
- screen = None
- show_grid = False
- show_labels = False
- speed = 4
- world = None
- world_type = None
|
class SubPixelSurface(__builtin__.object) |
| |
Methods defined here:
- __init__(self, surface, level=3)
- Creates a sub pixel surface object.
surface -- A PyGame surface
x_level -- Number of sub-pixel levels in x
y_level -- Number of sub-pixel levels in y (same as x if omited)
- at(self, x, y)
- Gets a sub-pixel surface for a given coordinate.
x -- X coordinate
y -- Y coordinate
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class SuperMap(__builtin__.object) |
|
SuperMap is a dict of MapHandler objects. The supermap is expressed in world
coordinates. It uses map handlers to trigger map loading and unloading as
the camera moves around the world.
This class implements the required method signature for integration with the
Camera class. Thus, State.map = SuperMap() is valid.
Note that map tools in the toolkit module will not work with the SuperMap
because those tools only know how to work with BasicMap or TiledMap objects
where the map represents the entire world.
The following SuperMap shows the names and relative positions of the maps
in world space. The name is a tuple of int, length 2. In general it makes
sense to have (0,0) be the origin map, but it is not required. A supermap
can be irregular, and even have holes in it.
+-------+-------+-------+
|(-1,-1)| (0,-1)| (1,-1)|
+-------+-------+-------+
|(-1,0) | (0,0) | (1,0) |
+-------+-------+-------+
|(-1,1) | (0,1) | (1,1) |
+-------+-------+-------+
The following code adds three maps in single-row layout, starting with map
(0,0) and proceeding to the right:
class MyMapHandler(MapHandler):
def load(self):
self.map = load_a_map()
supermap = SuperMap()
supermap.add_handler(MyMapHandler((0,0), 'map00.tmx'))
supermap.add_handler(MyMapHandler((1,0), 'map10.tmx'))
supermap.add_handler(MyMapHandler((2,0), 'map20.tmx')) |
|
Methods defined here:
- __init__(self, origin=(0, 0), max_maps=4)
- Construct a SuperMap object.
origin is a tuple representing the 2D vector in the SuperMap which
holds the SuperMap origin. The topleft of this maps rect will be set to
(0,0) and all other maps' world space will be relative to this map.
max_maps is an int representing the maximum number of maps to keep in
memory. Maps above this number will be unloaded via the MapHandler
based on the order in which they were last updated. The minimum
functional value is 1. A value of 0 will never unload maps.
Attributes:
origin : origin from the constructor.
max_maps : max_maps from the constructor.
rect : The world bounding rect.
handlers : A dict containing map handler objects, keyed by the tuple
MapHandler.name.
current : The current MapHandler object which contains the global
camera's position (State.camera.position).
visible_maps : The list of MapHandler objects that are visible
within the global camera's rect (State.camera.rect).
history : The list of loaded maps, ordered on last update.
- add_handler(self, map_handler)
- Add map_handler to this SuperMap.
map_handler is the MapHandler object to add to this SuperMap.
- draw(self)
- get_handler(self, name)
- Return the named MapHandler object.
name is a tuple representing the 2D vector of this map in this SuperMap.
- get_objects(self, supermap_range)
- get_objects_in_rect(self, rect)
- get_tile_range_in_rect(self, rect)
- rect must be in world space.
- set_current(self, map_handler)
- Promote map_handler as the current map handler.
map_handler is a MapHandler object to promote to current.
If the current map handler is a valid MapHandler object, its exit()
method will be called.
Finally, map_handler's map will be loaded (as a failsafe; typically it
is already loaded via a trigger), and its enter() method is called.
- update(self, dt, *args)
- Update this SuperMap.
This method runs each MapHandler's triggers, promotes a MapHandler to
current when appropriate, and calls each MapHandler's update() method.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class TiledMap(gummworld2.basicmap.BasicMap) |
| |
- Method resolution order:
- TiledMap
- gummworld2.basicmap.BasicMap
- __builtin__.object
Methods defined here:
- __init__(self, map_file_name, collapse=(1, 1), collapse_layers=None, load_invisible=True)
- Construct a TiledMap object.
the map_file_name argument is the path and filename of the TMX map file.
The collapse argument is the number of tiles on the X and Y axes to
join.
The collapse_layers argument is a sequence of indices indicating to
which TiledMap.layers the collapse algorithm should be applied. See the
tiledmap.collapse_map.
If you don't want every layer collapsed, or different collapse values
per layer, use the default of (1,1) and pick individual tile layers to
collapse via TileMap.collapse(), collapse_map(), or collapse_layer().
- get_layer_by_name(self, layer_name)
- get_object_groups(self)
- get_tile_layers(self)
Methods inherited from gummworld2.basicmap.BasicMap:
- collapse(self, collapse=(1, 1), which_layers=None)
- Collapse which_layers by joining num_tiles into one tile. The
original layers are replaced by new layers.
The collapse argument is the number of tiles on the X and Y axes to
join.
The collapse_layers argument is a sequence of indices indicating to
which TiledMap.layers the collapse algorithm should be applied. See the
tiledmap.collapse_map.
- get_layer(self, layer_index)
- get_layers(self, which_layers=None)
- merge_layers(self, which_layers=None)
Data descriptors inherited from gummworld2.basicmap.BasicMap:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
|
class Vec2d(__builtin__.object) |
|
2d vector class, supports vector and scalar operators,
and also provides a bunch of high level functions |
|
Methods defined here:
- __abs__(self)
- __add__(self, other)
- # Addition
- __and__(self, other)
- __bool__(self)
- __div__(self, other)
- # Division
- __divmod__(self, other)
- __eq__(self, other)
- # Comparison
- __floordiv__(self, other)
- __getitem__(self, key)
- __getslice__(self, i, j)
- __getstate__(self)
- __iadd__(self, other)
- __idiv__(self, other)
- __ifloordiv__(self, other)
- __imul__(self, other)
- __init__(self, x_or_pair, y=None)
- __invert__(self)
- __isub__(self, other)
- __itruediv__(self, other)
- __len__(self)
- __lshift__(self, other)
- # Bitwise operators
- __mod__(self, other)
- # Modulo
- __mul__(self, other)
- # Multiplication
- __ne__(self, other)
- __neg__(self)
- # Unary operations
- __nonzero__(self)
- __or__(self, other)
- __pos__(self)
- __pow__(self, other)
- # Exponentation
- __radd__ = __add__(self, other)
- __rand__ = __and__(self, other)
- __rdiv__(self, other)
- __rdivmod__(self, other)
- __repr__(self)
- # String representaion (for debugging)
- __rfloordiv__(self, other)
- __rlshift__(self, other)
- __rmod__(self, other)
- __rmul__ = __mul__(self, other)
- __ror__ = __or__(self, other)
- __rpow__(self, other)
- __rrshift__(self, other)
- __rshift__(self, other)
- __rsub__(self, other)
- __rtruediv__(self, other)
- __rxor__ = __xor__(self, other)
- __setitem__(self, key, value)
- __setslice__(self, i, j, seq)
- __setstate__(self, dict)
- __sub__(self, other)
- # Subtraction
- __truediv__(self, other)
- __xor__(self, other)
- convert_to_basis(self, x_vector, y_vector)
- cross(self, other)
- dot(self, other)
- get_angle(self)
- get_angle_between(self, other)
- get_dist_sqrd(self, other)
- get_distance(self, other)
- get_length(self)
- get_length_sqrd(self)
- # vectory functions
- interpolate_to(self, other, range)
- normalize_return_length(self)
- normalized(self)
- perpendicular(self)
- perpendicular_normal(self)
- projection(self, other)
- rotate(self, angle_degrees)
- rotated(self, angle_degrees)
Data descriptors defined here:
- angle
- gets or sets the angle of a vector
- length
- gets or sets the magnitude of the vector
- x
- y
|
class View(__builtin__.object) |
|
Views are used to access areas of a pygame surface. They are analogous
to surfaces and subsurfaces.
Access the pygame surface via the surface attribute.
Access the surface's rect via the rect attribute.
For subsurfaces, the rect for the subsurface in the parent surface can be
accessed via the parent_rect attribute. If this instance does not represent
a subsurface then rect and parent_rect will be equivalent. |
|
Methods defined here:
- __init__(self, surface=None, subsurface_rect=None)
- Create an instance of Surface.
If only surface is specified then it is used as the instance's surface.
If subsurface_rect is specified then a subsurface of the surface
argument is gotten for the instance's surface.
The surface argument is a pygame surface.
The subsurface_rect argument is the area of a subsurface to get from
the surface argument.
- blit(self, surf, pos, area=None, special_flags=0)
- Blit a surface to this surface.
- clear(self)
- Fill the surface with self.fill_color.
- fill(self, color, rect=None, special_flags=0)
- Fill this surface with color.
Data descriptors defined here:
- __dict__
- dictionary for instance variables (if defined)
- __weakref__
- list of weak references to the object (if defined)
- abs_offset
- The absolute offset of the subsurface.
- center
- The center coordinate of the surface.
- height
- The height of the surface.
- size
- The size of the surface.
- width
- The width of the surface.
| |