usf Package

usf Package

Ultimate Smash friends is a game designed to provide tons of fun :D

It also focus on being easy to mod and to be easilily extensible both in code and in gameplay.

ai Module

This module takes care of managing non human players

class usf.ai.AI[source]

Bases: object

This object allows to plan and execute movements for a character depending on its situation, trying to do intelligent moves.

update(game, iam)[source]

iam represent the index of the player being controlled in the game.players list, this method will either create a list of future actions to do, or use actions that where planned before if there are some left to do.

class usf.ai.Movement(time, movement, reverse, walk)[source]

Bases: object

A simple structure to store a planet movement, contains the planned time of the movement, the direction (reversed or not) of the movement, if the movement is done with walking vectors activated or not, and the name of the movement executed.

usf.ai.displacement_movement(*args, **kwargs)[source]

return True if a movement is considered a diplacement movement

usf.ai.fight_movement(*args, **kwargs)[source]

return True if a movement is considered a fight movement

usf.ai.heuristic_distance(player, others)[source]

this function evaluate the distance of the player to the next other player

usf.ai.heuristic_fight(player, others)[source]

this function evaluate a situation, from a fighting point of view

usf.ai.heuristic_state(game, player, others)[source]

return a score for the current state of the game, allow to chose a set of movement to do.

value to take into account:
number of lives % of damages number of lives of others % of damages to others
usf.ai.over_some_plateform(game, player)[source]

return true if the player is currently verticaly over a plateform (that’s different than not being lower than the lowest plateform)

usf.ai.possible_movements(*args, **kwargs)[source]

return the list of current legal movements for the player

usf.ai.search_path(game, iam, max_depth)[source]

from a known position, search the most interresting position availaible in the future, and how to get there.

usf.ai.simulate(game, iam, m)[source]

change the player movement to movement, and jump TIMESTEP in the future. if movement is none, just jump TIMESTEP in the future.

usf.ai.try_movement(movement, game, gametime, iam, others, h)[source]

simulate a movement, in all direction, walking or not, and return the scores of these configurations

usf.ai.under_lowest_plateform(game, player)[source]

return True if the caracter is currently lower than the lowest plateform

animations Module

This module provide animations for entities, animations are composed of frames, which are a bit more than an image...

class usf.animations.Frame(image, gametime, hardshape, trails=None)[source]

Bases: object

A Frame is an image of n animations, plus some information on the player when on this instant of the animation:

  • The hardshape is an inner rectangle than delimitate the area that can

    collide the world.

  • The agressiv points are the damaginds points of a player/entity when it hit some other player.

  • The Vector indicate the speed and direction taken by the entity when in this state, this combine with the current direction/speed of the entity.

add_agressiv_point((c_x, c_y), (vect_x, vect_y))[source]

add an agressive points of coords, and vector specified, to the list of agressivpoints of the frame

class usf.animations.PreciseTimedAnimation(frames, attribs, server=False)[source]

Bases: object

This object store the frames of an animation and update the image of the entity skin.

frame(anim_time)[source]

return the current frame depending on the time since the beggining of the animation.

start(gametime)[source]

set the animation start as now, and the animation as started.

start_time[source]
update(gametime, reverse=False, server=False)[source]

update the state of the animation.

config Module

Provides a class used for reading and writing various configurable options throughout the game.

This class produces an INI formated config file as opposed to an XML formatted one. The reason that python’s built-in ConfigurationParser isn’t sufficient is because comments aren’t preserved when writing a config file, the order in which the options are written isn’t preserved, and the interface used with this class is arguably more convenient that ConfigParser’s.

A default config file may be generated by envoking this module from the

command line::
python -m config.py [-f filename]

filename is an optional name for the config file (system.cfg by default)

class usf.config.Config(config_path='', system_path='', user_path='', filename='user.cfg')[source]

Bases: object

An object that represents a config file, its sectons, and the options defined within those sections.

config_file[source]
config_path[source]
filename[source]
static generate(filename)[source]

Takes filename and generates a default config file using DEFAULT_CONFIG

paths[source]
static platform_paths(system=None)[source]
read(filenames=None, sanitize=True)[source]

Reads a config file and populates the config object with its sections and options. Calling this method without any arguments simply re-reads the previously defined filename and paths

@param filenames: name of files to be parsed. @type path: string or list

@param sanitize: whether or not to scrub the last file read or not @type sanitize: boolean

sanitize(filename)[source]

Scrubs filename, removing options that don’t exist, and appending those that are missing.

@param filename: file to be sanitized @type filename: string

sections[source]

Returns a list of existing sections

system_path[source]
user_path[source]
write(filename=None)[source]

Writes a config file based on the config object’s sections and options.

@param filename: Name of file to save to. By default, this is
the user config file.

@type path: string

class usf.config.Section(name)[source]

Bases: object

An object that represents a section in a config file.

Options can be added to a section by simply assigning a value to an attribute:

section.foo = baz

would produce:

[section]
foo = baz

Options that do not exist on assignment are created dynamcially.

Values are automatically converted to the appropriate python type. Options that begin and end with brackets([, ]) are converted to lists, and options that are double-quoted (”) are converted to strings. Section also recognizes booleans regardless of case, in addition to the literals ‘yes’ and ‘no’ of any case. Except in the case of double-quoted strings, extra white-space is trimmed, so you need not worry. For example:

foo = bar

Equivalent to:

foo   =             baz
entries[source]

Returns a dictionary of existing entries

options[source]

Returns a list of existing options

values[source]

Returns a list of existing values

controls Module

This module manage controls, mainly on the keyboard, and either trigger player’s animations, or pass events to the menu system.

class usf.controls.Controls[source]

Bases: object

Catch pygame keyboard events and decides of the interaction with the game, game menu and entity instances. Key configuration are taken from sequences.cfg. This class can update and save configuration.

handle_game_key(state, key, game_instance)[source]

Call handle_game_key_down of handle_game_key_up whether if the key event is DOWN or UP

handle_game_key_down(key, game_instance)[source]

manage key_down events

handle_game_key_up(key, game_instance)[source]

manage key up events

load_keys()[source]

load player keys from configuration

load_sequences()[source]

construct player combo sequences, using config (sequences.cfg) and known player keys

poll(game_instance, state)[source]

This function manages key events aquiered from local keyboard or sent by clients in the case of a networkk game.

test_sequences(game_instance, numplayer)[source]

test all sequences against player state/sequence if a sequence is recognized, the animation is applied

class usf.controls.Sequence(keys, action, condition=None)[source]

Bases: object

Used to bind a character animation to a sequence of key of a player. condition allow to restrict the avaiability of the animation to certain current animation (the player can only double jump if he is already jumping for example)

compare(seq, player)[source]

Compare a sequence of key events against our sequence

compare_local(seq, player, index)[source]

compare a sequence of keys events against our sequence starting from index

usf.controls.get_key_code(name)[source]

return key code for the key associated with the keyboard config name

usf.controls.key_down_left(the_key, player, game_instance)[source]

manage incidence on walk animation if the player push down his left key

usf.controls.key_down_right(the_key, player, game_instance)[source]

manage incidence on walk animation if the player push down his right key

usf.controls.key_shield(the_key, player, game_instance)[source]

activate shield if asked by the player, and if possible, return True, if the shield was activated

usf.controls.key_up_left(player, game_instance)[source]

manage incidence on walk animation if the player release his left key

usf.controls.key_up_right(player, game_instance)[source]

manage incidence on walk animation if the player release his right key

usf.controls.reverse_keymap(keycode)[source]

provide a name of key for a codekey, should not break on weird international keyboards

debug_utils Module

This module provide functions made to make easier the debug work, may diseapear in the future.

usf.debug_utils.draw_rect(surface, rect, color=(255, 255, 255, 255))[source]

a simple function to draw a colored rect on a surface

usf.debug_utils.log_result(function)[source]

this decorator will log the result of a function before returning it

entity Module

This module provide the Entity classe, that represent any physical object in the game, character or item.

class usf.entity.Actor(game, **kwargs)[source]

Bases: object

An actor is the physical presence of something

BOTTOM_LEFT = 4
BOTTOM_RIGHT = 3
LOWER_LEFT = 5
LOWER_RIGHT = 2
TOP_LEFT = 7
TOP_RIGHT = 0
UPPER_LEFT = 6
UPPER_RIGHT = 1
dist(entity)[source]

Return the distance to a Rect or to another entity.

gravity[source]

True if the entity should react to gravity

is_present()[source]

callable form of the property

on_ground[source]

True if the entity is currently in collision with the ground

physic[source]

True if the entity should have any physical reaction

physics[source]

Set if the player has to manage collisions properly, if not, it will be destroyed when colliding anything

place[source]

current position in level of the entity

present[source]

return True if the entity is currently in game

reversed[source]

is the entity looking left

set_gravity(value)[source]

Set if the player is bound to obey gravity

set_place(value)[source]

move the entity to an arbitrary position

set_present(value)[source]

set the entity presence in game

set_reversed(value)[source]

set the direction of the entity

set_vector(value)[source]

set the (dx/dt, dy/dt) of the entity

set_walking_vector(value)[source]

” set entity walking vector

vector[source]

current dx/dt and dy/dt of the entity

walking_vector[source]

current walking vector of the entity (this is different of the vector, as it’s defined only by the fact the player uses direction keys)

class usf.entity.Entity(**kwargs)[source]

Bases: usf.entity.Actor

Provide an entity object, which will take care of lifes, movements, collisions of an Entity. Players and Items are Entities.

This is a big class, and it uses a few counter intuitive concepts, first, its vectors are defined relatively, that mean moving “forward/backward” instead of moving “left/right”, also the vector representing the walking movement of the entity is seperated from the main vector.

add_percents(value)[source]

increment the current player percents

agressiv_points[source]

return agressiv points of the current frame

ai = False
ai_ = None
alive()[source]

True if the player still have lives left

armor[source]

return current armor state

backup()[source]

save important attributes of the state of the player, to a dict

collide_back(game)[source]

if one of the two left points collide and the entity is reversed or one of the two right points collide and the entity is not reversed and the player bounce back.

collide_bottom(game)[source]

test of points and consequences on vectors if one of the two uppers points collide, the entity bounce down.

collide_front(game)[source]

if one of the two left points collide and the entity is not reversed or one of the two right points collide and the entity is reversed and the player is pushed forward.

collide_top(game)[source]

if one of the two lowers points collide, the entity bounce up and it’s horizontal speed is lowered

counter = 0
draw(coords, zoom, surface, debug_params={})[source]

Draw the entity on the surface(i.e: the screen), applying coordinates offsets and zoom scaling as necessary, implementation depends on the definition of the global “SIZE”, as a 2 elements list of in integers, containing respective height and width of the screen.

coords is a tuple containing the current position of the camera, zoom is the current zoom of the camera.

hardshape[source]

return current hardshape from entity_skin

hit(point, reverse)[source]

enforce the effect of a collision with an aggressive point, the point is a list of x, y,dx, dy coords, and reverse is a flag indicating if the attacking entity is reversed (to apply projection vectors)

i = 7
invincible[source]

status of the entity vulnerability to hits

lighten[source]

True if the entity should be currently displayed lightened

list_sin_cos = [[0.3826834323650898, 0.9238795325112867], [0.9238795325112867, 0.38268343236508984], [0.9238795325112867, -0.3826834323650897], [0.3826834323650899, -0.9238795325112867], [-0.38268343236508967, -0.9238795325112868], [-0.9238795325112865, -0.38268343236509034], [-0.9238795325112866, 0.38268343236509], [-0.3826834323650904, 0.9238795325112865]]
list_sin_cos_1 = [(1.3826834323650898, 1.9238795325112867), (1.9238795325112867, 1.3826834323650898), (1.9238795325112867, 0.6173165676349103), (1.3826834323650898, 0.07612046748871326), (0.6173165676349104, 0.07612046748871315), (0.07612046748871348, 0.6173165676349097), (0.07612046748871337, 1.38268343236509), (0.6173165676349096, 1.9238795325112865)]
lives[source]

return current number of lives of the entity

move((x, y))[source]

move the entity relatively to his referencial (if he look left, moving positively on x mean going left).

name[source]

name of the entity

nb_points = 8
num[source]

return entity number

percents[source]

return current percents

point(n)[source]

Return a collision point of the entity

rect[source]

return current player rect

restore(backup)[source]

restore the game to the state described in backup

set_invincible(value)[source]

set the entity invulnerability status

set_lighten(value)[source]

Set lighten attribute of entity to value

set_lives(value)[source]

change current number of lives of the entity

set_percents(value)[source]

change percents value

set_upgraded(value)[source]

Set the upgraded state of the player, True or False

set_visible(value)[source]

Set the visibility statue of the entity

shield[source]

return current state of the shield

test_hit(entity)[source]

test entity aggressive points collisions with other entity

update(deltatime, gametime, game)[source]

Global function to update everything about entity, deltatime is the time ellapsed since the precedent frame, gametime is the time since beginning of the game

update_points(x=0, y=0)[source]

Points are created as follows:

+-------------------+
|       7   0       |
|   6           1   |
|                   |
|   5           2   |
|       4   3       |
+-------------------+

As can be seen, they are oriented clock-wise, beginning in the upper-right corner and ending in the upper-left.

upgraded[source]

return True if the player is currently upgraded

visible[source]

set if the entity is currently visible on screen

entity_skin Module

this module deal with what’s definied in xml files for entities

class usf.entity_skin.EntitySkin(dir_name, server=False, xml_from_str=None, keep_xml=False, animation='static')[source]

Bases: object

An EntitySkin contains all information about a player or an item, which is mainly animations frames, with their timings and vectors, and less importants information as the character/item name and such details.

add_events(anim_name, game, params)[source]

add events of the animation to the game

add_vectors(anim_name, game, params)[source]

add vectors of the animation to the game as events

backup()[source]

save current state of the entity skin

change_animation(anim_name, game=None, params={})[source]

Change animation of the entity skin, updating hardshape and agressiv points. Add associated events to game.

load_hardshape(attribs)[source]
load_movements(a, dir_name, server)[source]
load_shield_center(attribs)[source]
restore(backup)[source]

restore entity_skin from a backup state

update(t, reverse=False, upgraded=False, server=False)[source]

Update the skin’s animation if necessary.

valid_animation(anim_name)[source]

return true if the animation is in the character animations and is ‘static’ or not the current animation.

event_manager Module

This module provides a manager/ordonnancer for events in the game, this is a simple but critical part, as a lot of mecanisms in the game are implemented through events (movements/adding player to games/missiles...)

class usf.event_manager.EventManager[source]

Bases: object

This simple module takes care of the state of events in the game

add_event(name, *args, **kwargs)[source]

add an event of the requested type to the manager, args and kwargs are passed to the event creation

backup()[source]

return the current state of the events

get_events(cls=None, params={})[source]

return events filtered by name and target parameters, None mean no filter on this parameter

restore(backup)[source]

restore the events to a known state

update(deltatime, gametime)[source]

Called every frame, update every instancied event.

font Module

usf.font.Font(*args, **kwargs)[source]

#TODO documentation

usf.font.FontList(*args, **kwargs)[source]

game Module

The game module is centered about the core of the game, the Game class initiate and update all elements of the game, namely level, entities and events.

exception usf.game.BadPlayersNetworkParamError[source]

Bases: exceptions.Exception

Raised when the player params of a network server game is not correct.

class usf.game.Game(screen, level='biglevel', players_=(None, None, None, None))[source]

Bases: object

The game base object, initiate and update everything when in game (not in menu).

add_item(item='heal', place=(550, 50), reverse=False, upgraded=False, vector=(0, 0), bullet=False, physics=True, animation='static')[source]

Insert an item into game.

add_world_event()[source]

Insert level events into the game, those are configured in level.xml of each levels, level-specific events can be defined in level_events.py in the level directory.

backup()[source]

save events, items, levels, players of the game in their current state

backup_items()[source]

return a backup of the state of the items in game

backup_players()[source]

return a backup of the state of the players in game

backup_skins()[source]

return a backup of the entity skins current state

center_zoom_camera()[source]

set the camera place and zoom to display as much player as possible, without moving the camera too fast.

display_game_state()[source]

Display if the game is ended by a won, or a draw, does nothing if the game is still running

draw(debug_params={})[source]

Draw every parts of the game on the screen.

draw_debug(debug_params)[source]

manae all de debug drawings provided by the class

draw_debug_player_controls(num, controls)[source]

displays current key sequence of player, useful for debuging

draw_debug_player_coords(num, player)[source]

draw player coords, useful for debugging.

draw_notif(notif)[source]

drow notifications on the screen

draw_player_lives(player)[source]

draw as much hearth as the player has lives on it’s portrait

draw_player_portrait(player)[source]

draw, like... the player portrait? :D

draw_portraits()[source]

Draw player’s portraits at bottom of the screen

draw_progress_bar_for_lives(player)[source]

heh, draw progree bar for lives of the player

load_player(i, player)[source]
load_players(players_)[source]

this function is responsible of adding the requested players to the game.

players_barycenter[source]

return the barycenter of all present players, to help place the camera

precise_zoom[source]

Return the minimum scale of the level to use so every player is visible on screen, provided there is more than one player

restore(backup)[source]

restore the game state from _backup

restore_items(backup)[source]

restore items and their states from a known backup state in the game

restore_players(backup)[source]

restore players and their states from a known backup state in the game

restore_skins(backup)[source]

restore skins of entities from a known backup state

update(deltatime)[source]

sync everything to current time. Return “game” if we are still in game mode, return “menu” otherwise.

At the beggining of the game, we add world events, and then wait for the next frame before adding players, resolve bug 76585 on slower machines.

update_items(deltatime)[source]

trigger update on all the present items

update_notif()[source]

update and draw notifs,

update_physics()[source]

all physical interaction here would probably better in a physics engine, but lie here for now.

update_players(deltatime)[source]

trigger update on all the present players

class usf.game.NetworkClientGame[source]

Bases: usf.game.Game

This class is intended for defining network client game implementation, not yet implemented!

class usf.game.NetworkServerGame[source]

Bases: usf.game.Game

This class is intended for defining network server game implementation, not yet implemented!

gui Module

The Gui module provide interfaces to build custom screens with widgets and callback to use them.

class usf.gui.Gui(surface)[source]

Bases: object

Main class of the GUI. Init and maintain all menus and widgets.

handle_keys(event)[source]

This function handles keyboard event which are send from the update function.

handle_mouse(event)[source]

This function handles mouse event which are send from the update function.

handle_reply(reply)[source]

This function handles the callback return by the screens with the function event_callback(). This callback needs to be a dictionary, otherwise, it will be ignored.

The reply can be:
{‘goto’: ‘myscreen’}
where my screen is the name of the screen loaded in __init__()
{‘goto’: ‘back’}
go to the last menu, it is usually used for a back button
{‘game’: ‘new’}
to start a new game
{‘game’: ‘new_server’}
to start a new game in server mode
{‘game’: ‘join_server’}
to join a network game
{‘game’: ‘continue’}
to resume the game, it is used in the in-game menu
{‘game’: ‘stop’ }
to stop the game, it is used to qui the game in the in-game menu
launch_game(server=False)[source]

Function to launch the game, use precedant user choices to initiate the game with level and characters selected.

screen_back()[source]

Go to the last screen.

transition_fading(old_screen, old_surface, new_screen, new_surface)[source]
transition_slide(old_screen, old_surface, new_screen, new_surface)[source]
update()[source]

Update the GUI, it draws the mouse, and the menu.

update_youhere()[source]
usf.gui.get_text_transparent(name)[source]

level Module

Levels implementation, levels are constituted of different parts graphics: background, middle and foreground, plus decorum elements architecture: blocs, moving blocs, bounching blocs

class usf.level.Block(position, texture, levelname, texture_fg)[source]

Bases: object

An abstraction class to define methods shared by some level objects.

collide_rect(rect)[source]

Return True if the point at (x, y) collide this bloc’s rects.

draw(surface, coords=(0, 0), zoom=1)[source]

Draw this moving bloc on the passed surface, taking account of zoom and placement of camera.

draw_after(surface, coords=(0, 0), zoom=1)[source]

Draw this moving bloc foreground on the passed surface, taking account of zoom and placement of camera, if there is one.

class usf.level.Decorum(frames, coords, depth, update_fctn)[source]

Bases: object

A simple class to represent decorum in levels. A decorum is an element displayed, but non interractive, as opposed to a block, it can be at any depth between background and camera, and will be diplayed with the appropriate zoom at the appromirate moment. It can be animated, by containing several frames, and move, by providing dx and dy update functions. which can use time and random.

frames are (image, time) couples, time being the END of the display of the corresponding image (and thus, begin display of the next), image is the path to the image, relative to the data directory.

depth is [-1, 1[, 0 meaning the place of the level, a negative value mean behind the level and a positive, before.

draw(surface, coords, zoom)[source]

Render the Decorum to a surface

update(gametime)[source]

Update position and texture

class usf.level.Level(levelname='baselevel', server=False)[source]

Bases: object

This object contain information about the world within the characters move, it contains the textures of background, stage and foreground, the coords of collision rects, the size of the leve;t.

backup()[source]

return a backup of the level state, that mean backup of moving blocs, because it’s the only thing that change

collide_rect((x, y), (h, w)=(1, 1))[source]

This fonction returns True if the rect at coords (x, y) collides one of the rects of the level, including the moving blocks and vector blocks.

#XXX: any decent optimisation of this welcomed

draw_after_players(surface, level_place, zoom, levelmap=False)[source]

draw everything that need to be drawn after players

draw_background(surface, coords=(0, 0), zoom=1)[source]

Draw the background image of the level on the surface

draw_before_players(surface, level_place, zoom, shapes=False)[source]

draw everything that need to be drawed before players

draw_debug_map(surface, level_place, zoom)[source]

draw the map before the level, to show the real level shape

draw_foreground(surface, coords, zoom)[source]

draw the decorations of the level that are before the player

draw_level(surface, coords, zoom, shapes=False)[source]

draw the center part of the level

draw_minimap(surface)[source]

draw minimap in the upper/right corner of the screen, showing blocs

get_events()[source]
load_blocs(xml)[source]

load and instanciate basic blocs defined in the xml

load_borders(attribs)[source]

calculate actual size of the level, with level image size and borders

load_decorums(xml)[source]

load decorums defined in xml

load_entrypoints(xml)[source]

set entry points to the level, from xml, create some if there are none (and log that, there should be some)

load_events(name, xml)[source]
load_images(attribs, levelname)[source]

create image paths from indications in xml, don’t actually load images, as they will be loaded as needed by loaders.image

load_layers(xml)[source]

load and instanciate layers if any defined in xml

load_moving_blocs(xml, server, levelname)[source]

load and instanciate moving blocs defined in xml

load_particle_generators(xml)[source]
load_vector_blocs(xml, server, levelname)[source]

load vector blocs defined in xml

load_water_blocs(xml, server=False)[source]

#XXX used anywhere?

restore(backup)[source]

restore game state from a backup

update(time, deltatime)[source]

Update moving blocs and decorums

class usf.level.MovingPart(rects, patterns, *args, **kwargs)[source]

Bases: usf.level.Block

This define a level bloc that move, with a defined texture, and a defined set of collision rects. It moves following a pattern of (position(x, y): time( % maxtime)).

backup()[source]

return old and current position, to restore later

get_movement()[source]

Return the movement between the position at the precedent frame, and now, usefull to communicate this movement to another entity.

restore(backup)[source]

restore backed up positions

update(level_time)[source]

Update the position of the moving bloc, based on time since the bigining of the game, calculating the percentage of time we are between two positions. And update the coords of colliding rects.

class usf.level.VectorBloc(rects, vector, relative, *args, **kwargs)[source]

Bases: usf.level.Block

This define a bloc that apply a vector to any entity falling/walking on it.

apply_vector(entity)[source]

This method simply add the bloc’s vector to the passed player.

collide_rect(*args, **kwargs)[source]

return True if the rect collide with our bloc

usf.level.get_xml(levelname)[source]

return xml tree of the level

loaders Module

pygame_loaders is a set of classes/functions, to use mainly for image loadings/processing with pygame, it uses memoization to accelerate successive loadings of images, and repeating the same process on the same images, acting as a real cache for image loading and manipulations, it help to load tracks and such too.

This module was originaly a simple syntaxic sugar for a pygame project,

for performances sake it quickly gained memoization, allowing you to call for images, not carring if you already loaded them or not. As you may need to do that for result of process on those images, the image loader gained a lot of keywords, that allow to call images with a zooms, blending, reversing, scaling, rotating, and all sort of combinations, everytime doing only the required parts of those processings, and using previous results of processings. Okay, it can takes up big memory amounts, but well, i found it’s most of the time less of the problem than CPU, so if you agree, you will probably agree that for games, it’s an acceptable tradeoff.

Oh, for convenience sakes, it can load bunch of text and musics, too, the processing part is less developped on these ones, but contributions are welcomed, and memoization is done for them too.

Anyway, using it is quite simple, simply import the needed loaders from loaders.py, and for an image filepath, image() will return a tupple containing the image and it’s size, no need to store it away, calling the loader a second time or more is basically free, thanks to memoization.

pygame must be loaded and display_mode set to perform most image operations.

>>> from pygame_loaders import image
>>> image('myimage.png') # actual loading
(<Surface(491x546x32 SW)>, <rect(0, 0, 491, 546)>)
>>> image('myimage.png') # returning same result, without any loading
>>> image("myimage.png", zoom=1.5) # only performing zoom
(<Surface(736x819x32 SW)>, <rect(0, 0, 736, 819)>)
>>> image("myimage.png", zoom=1.5, alpha=0.4) # only changing alpha
(<Surface(736x819x32 SW)>, <rect(0, 0, 736, 819)>)
usf.loaders.get_gconfig(*args, **kwargs)[source]
usf.loaders.image(*args, **kwargs)[source]

A function to load an image, memoized, and with manipulation capabilities: scale, zoom reverse horizontaly, produce a lightened version of an image, change alpha of an image, crop and extand an image.

usf.loaders.image_layer(*args, **kwargs)[source]

return a copy of the first image, with the second one blitted on it

usf.loaders.paragraph(*args, **kwargs)[source]

Load a bunch of text in a surface, formated depending on it’s length

usf.loaders.text(*args, **kwargs)[source]

return a surface with the text rendered on it, in the color passed in parameter

usf.loaders.track(*args, **kwargs)[source]

Load an audio file to play in the game

main Module

This is the main file for ultimate-smash-friends, that initiate configs, parse parameters, and initiate games

class usf.main.Main(init=True, run=True)[source]

Bases: object

The main class, load some parameters, sets initial states and takes care of the game main loop.

display_fps()[source]

FPS counter

init()[source]
init_client()[source]

connect to a server to play a network game

init_screen()[source]

various screen initialisations

init_server()[source]

start a server to host a network game

init_sound()[source]

various audio initialisations

init_standalone()[source]

start a non network instance of the game

initate_options_parser()[source]

Set options and usage to parse users choices

loading_screen()[source]

update the screen display during loading

manage_ai()[source]

update the ai

manage_game(dt)[source]

call the various submethod to update the whole game and render it to the screen

manage_menu()[source]

manage input and update menu if we are in the menu state

parse_options()[source]

parse the command line options

run()[source]

The main game loop, take care of the state of the game/menu.

usf.main.author()[source]

print credits in the terminal

memoize Module

This module provide simple implementation of the memoize pattern, implemented as a decorator.

usage:

@memoize
def my_determinist_pure_function(*args, **kwargs):
    do stuff

my_determinist_pure_function(some_params) # first call with those params, slow ...

my_determinist_pure_function(some_params) # return result imediatly

...

my_determinist_pure_function(other_params) # slow again, because new params

...

my_determinist_pure_function(other_params) # return result immediatly

of course, if params/results are memory huger, or the function is called with lot of different params, that will eat some memory, but if you often need the same result, that can bring you a lot of speed.

usf.memoize.memoize(function)[source]

Any function decorated with memoize will cache it’s results and send them directly when called with same parameters as before, without calling the actual code, please only use with functions which result depend only of parameters (not time, state of the game or such).

music Module

USF module to load and play musics depending on the situation, not hightly reusable code.

class usf.music.Music[source]

Bases: object

This class take care of the background music in menus and games, it load the “playlist” and change the music in random order.

change_music(music, fading=True)[source]

This change the currently played music. With an optional fading.

update(state)[source]

This check various parameters (state of game, time since last music change), and may choose to change music (with a fading) if it seems necessary.

particles Module

This module provide a particle class and a ParticlesGenerator class, you probably only need to manipulate the later. This allow you to generate textured particles with variable initial coordinate, variable direction, and custome initial speed and friction.

class usf.particles.Particle(position, speed, direction)[source]

Bases: object

A particle object is used as a part of a flow of particles to render effects as watter, smoke, fire or other dynamic elements. This Particle object is not very useful in itself, as it only store position, speed, direction and age of the particle, most of the management being done by the ParticlesGenerator parent object.

draw(surface, texture, pos, zoom, lifetime)[source]
update(deltatime, friction)[source]
class usf.particles.ParticlesGenerator(attribs)[source]

Bases: object

A simple particle generator implementation for levels, Particle generators are used to represent dynamic things like water, fire, rain, smoke, and so on.

To use a ParticlesGenerator you should override the parametters in self.params with your own (in attribs), note that attribs is managed to extract information from xml files into it, so all data are represented in strings.

position: the initial (center) position of the particles (in pixels) position_delta: allows to add a range of possible values around the center speed: initial speed of particles (in pixels/seconds) rate: rate of production of particles (in particles/seconds) direction: the main direction of particle emission, the value is in radian/pi (so 1 mean 1pi, which is 180 degrees, or half a circle, 0 mean left to right.) direction_delta: as for position_delta, allow to provide a range of randomness, same unit as direction lifetime: the lifetime of particles, note that the alpha of particles will decrease linearly to completly diseapear at end of life. friction: speed will decrease of this value each second, up to 0.

draw(surface, pos, zoom)[source]

draw existing particles on surface, needs position and zoom of the camera.

update(deltatime)[source]

update particles, delete too old ones, create new ones if time_accumulator allows it

usf.particles.random() → x in the interval [0, 1).

skin Module

This module allows to customize GUI representation

class usf.skin.Layer(node)[source]

Bases: object

A layer class. It is mainly used to have animated background in both the gui and the game.

It is created from an ElementTree xml node.

Here is the syntax:

<layer sizex="35" sizey="46" src="path.png">
    <frame time="2" x="0" y="-70" />
    <frame time="0" x="30" y="600" />
</layer>

The path (path.png) of the image must be an absolute path from the data directory of USF, e.g. levels/blobplanet/leaf.png.

Time is the duration of the frame (seconds), here, the image will go to the second frame in 2 seconds (and then, it will go to the first in 0).

get_image(dt=-1)[source]

Get the image surface.

Parameters:dt – The current time. Usually, it is -1, and it is set to time.time() when it is -1. It can be useful to specify the time for unit testing.
Return type:pygame surface
get_pos(dt=-1)[source]

Get the position of the layer.

Parameters:dt – The current time. Usually, it is -1, and it is set to time.time() when it is -1. It can be useful to specify the time for unit testing.
Return type:tuple which contains the coordinates of the layer (x, y)
class usf.skin.Skin[source]

Bases: object

Skin class contains GUI configuration informations.

get_background()[source]

FIXME: doc!

timed_event Module

This module allow to create timed and condition based events, to create complexe effects and behaviours in the game.

class usf.timed_event.BlobSpecial(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

A boomerang like attack with the eye of blob

condition()[source]
delete()[source]
execute(deltatime)[source]
class usf.timed_event.BombExplode(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This Event timely trigger the bomb explostion.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.Bounce(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event will make the entity bounce when touching the ground

condition()[source]
delete()[source]
execute(deltatime)[source]
class usf.timed_event.DelItemEvent(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Event used to timely delete an item, because it was used, or because it got a timeout.

condition()[source]
delete()[source]
execute(deltatime)[source]
class usf.timed_event.DropPlayer(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event is called to drop a player in game.

condition()[source]
delete()[source]
execute(deltatime)[source]
class usf.timed_event.DropRandomItem(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Add a random item in game.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.Gost(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Chasing ‘AI’ for a little chasing gost.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.HealEvent(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Event used to timely drop a player’s percentage to zero.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.InvinciblePlayer(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

The target player is invincible and half invisible during this event.

condition()[source]
delete()[source]
execute(deltatime)[source]
class usf.timed_event.ItemShower(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Add periodicaly an item into game.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.LaunchBullet(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Launch a fireball in front of the player.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.PlayerOut(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event is called when a player is hitting the level border

condition()[source]
execute(deltatime)[source]
class usf.timed_event.PlayerStaticOnGround(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event will set the player on static animation when he touch the ground

condition()[source]

Return false if the player is on ground so the event effect occure.

delete()[source]
execute(deltatime)[source]
class usf.timed_event.ShieldUpdateEvent(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event, launched for one character, update the energy of it’s shield at every loop, depending on if it’s on or off.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.ThrowBomb(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Launch a bomb in front of the player.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.ThrowFireBall(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Launch a fireball in front of the player.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.ThrowMiniGost(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

Insert a little chasing gost in game.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.TimedEvent(manager, period, params={})[source]

Bases: object

An event allow to define a function to be executed later and/or during a certain period of time.

backup()[source]

This method return the state of the event in a dict, to restore latter

condition()[source]

This method must be overriden, it will be called every frame by the event, to verify if the event must continue.

del_()[source]

please don’t override this method if you want a special behaviour, override “delete” method instead.

delete()[source]

you can override this one if you want special behaviour

execute(deltatime)[source]

This method must be overriden, it will be called every frame by the event.

restore(backup)[source]

This method restore the event in a previous state from a backup()

update(deltatime, gametime)[source]

This method make the event up to date, by executing the various functions of the event.

class usf.timed_event.UpgradePlayer(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event will upgrade the player to his upper state, that state ends when the player dies.

condition()[source]
execute(deltatime)[source]
class usf.timed_event.VectorEvent(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

This event is used to assign time-based vector (accelerations) to a player. Used by animations.

condition()[source]

Return false so the addition is only performed once.

delete()[source]

Add the vector to the player vector.

execute(deltatime)[source]
class usf.timed_event.XeonCharge(manager, period, params={})[source]

Bases: usf.timed_event.TimedEvent

a charge attack for Xeon

condition()[source]
delete()[source]
execute(deltatime)[source]

translation Module

This module setup translation environment and provide the _ function, which you should import from it to use.

from usf.translation import _