SGL Library Reference¶
sgl.lib
is where a lot of the functions useful for making games will live. Not much of it is written right now, and you should probably avoid using most of what’s there, as it might change. Here’s a brief summary of the modules it currently includes, though:
sgl.lib.Script
- Provides a small domain specific markup language for writing in game cut scenes. Is designed to be easy for writers to understand and for programmers to implement support for. The syntax of this language is currently undergoing a great revision. This is the module that you should avoid using the most right now.sgl.lib.Time
- Provides the ability to register functions to happen at specific times or intervals. Useful for making pieces of code happen at a specific frame rate, for animated sprites and such.sgl.lib.Tween
- Provides “tweening” functionality, which lets you specify start and end values for any numerical property of any object, and animate them moving from point A to point B in a given amount of time with the given interpolation. Makes it much easier to add dynamic animations to in game GUIs and game elements.
Sound exciting? Hopefully, because there will be even more in the future! :p
Actual Reference¶
sgl.lib.Sprite¶
This module provides the bulk of the functionality of
sgl.lib. Nearly every other class in sgl.lib inherits from or uses
sgl.lib.Sprite
somehow.
-
class
sgl.lib.Sprite.
AnimatedSprite
¶ A subclass of
Sprite
that provides extra functions useful for managing frame-based animations.-
animation
¶ string: Property containing the name of the currently playing animation. This name should correspond to one of the keys in
animations
.If you set this property, it will immediately switch to the animation of that name. The current playing state (whether this sprite is playing whatever the current animation is, or paused), however, will remain unchanged.
-
pause
()¶ Pauses playment that the current point. You can call
play
to resume playment from this point.
-
play
()¶ Starts playing the active animation.
-
playing
¶ bool: Returns whether this sprite is currently playing whatever the active animation is.
-
preupdate
()¶ Overridden to handle animation logic, in addition to what
Sprite.preupdate
doas.- Todo:
- It might be useful to be able to restrict how many times an animation can loop, so you can, say, only play an animation once. Currently you can simulate this callbacks, but that’s a little cumbersome.
- Maybe make this attempt to make up for lost time, like
sgl.lib.Time
does.
-
-
class
sgl.lib.Sprite.
App
(first_scene)¶ A very simple object that wraps over scenes in order to let you easily switch between multiple scenes.
Parameters: first_scene ( Scene
) – The scene that will be active by default. The scene will be activated byswitch_scene
.
-
class
sgl.lib.Sprite.
Camera
¶ A small object to hold the coordinates of the camera in a given scene.
-
position
¶ tuple: The position of the camera—or, in other words, the coordinates in the scene that will be displayed at the top left corner of the window.
Can also be accessed through the
x
andy
attributes.
-
-
class
sgl.lib.Sprite.
EllipseSprite
¶ A subclass of
ShapeSprite
that draws an ellipse (or circle, ifwidth
andheight
are the same) in the bounding box of the sprite.
-
class
sgl.lib.Sprite.
PerspectiveGroup
¶ A subclass of
SpriteGroup
that disregards the usual sprite rendering order and instead draws every sprite inside in the order of their y coordinates. This means that sprites positioned higher on the screen are drawn below sprites positioned lower on the screen. In most two-dimensional projections of perspective, this provides the illusion that some sprites are positioned “behind” other sprites.By default, it completely flattens the sprite hierarchy inside when drawing sprites. This can be customized with the
max_level
attribute, or by setting ano_perspective
attribute toTrue
on a given sprite instance—this will make it so children of that sprites are not flattened out, and are drawn in their intended order.-
draw_children
()¶ You should not need to deal with this function yourself, but it is useful to note—
PerspectiveGroup
‘s implementation of draw_children reimplements most ofSprite.draw_children
without reusing code. The two method implementations may become the synchronized. If you experience bugs inPerspectiveGroup
that do not occur in normal sprites, this function is likely the cause.
-
-
class
sgl.lib.Sprite.
RectSprite
¶ A subclass of
ShapeSprite
that draws a rectangle in the bounding box of the sprite.
-
class
sgl.lib.Sprite.
Scene
¶ A special kind of
Sprite
designed to provide a few additional functions useful in managing larger game levels.
-
class
sgl.lib.Sprite.
ShapeSprite
¶ A subclass of
Sprite
designed to handle shapes drawn with the SGL drawing commands instead of blitting surfaces to the screen.This will often be faster than drawing the equivalent surface.
-
draw_shape
()¶ Override this function to specify what shape this sprite should draw. The stroke and fill properties will have already been set by the other functions of this class, and will automatically be restored to their previous values after this function has been executed.
-
-
class
sgl.lib.Sprite.
Sprite
(graphic=None)¶ Provides a class to represent drawable objects.
Parameters: graphic (SGL Surface) – A graphic that will be loaded by Sprite.load_surface
during initialization.-
add
(sprite)¶ Adds a child sprite to this end of this sprite’s sprite list.
Parameters: sprite ( Sprite
) – ASprite
instance to add.
-
anchor
¶ tuple: The position of the anchor point of this sprite. This determines the coordinates that is considered (0, 0) for this sprite, and impacts which point it is rotated around if you use that effect.
If either dimension is a floating-point number, they’ll be interpreted as a percentage of the sprite’s width or height. So, setting the anchor point to (0.5, 0.5) will placed in the center of the sprite’s graphic.
Can also be accessed through the
a_x
anda_y
attributes.
-
autosize
()¶ Updates this sprite’s size to match the size of its surface. Automatically called by
Sprite.load_surface
and when sprites are initialized with surfaces.
-
center
()¶ Utility function to place this sprite in the center of its parent sprite. If it has no parent sprite, it will be placed in the center of the screen.
-
collision_rect
¶ sgl.lib.Rect.Rect
: The bounding box that the collision functions will use to determine when this sprite is overlapping with others. If none is specified, it will assume you want the entire sprite to be collidable.
-
draw
()¶ Handle drawing this sprite and its children. Should not be overwritten to define custom drawing logic, unless you want to break drawing child sprites. Instead, override
Sprite.draw_self
.
-
draw_children
()¶ Loops through and draws child sprites. Ideally, should not be called manually.
Currently, this updates each sprite’s screen position one more time, to make them slightly more predictable.
-
draw_self
()¶ Handle drawings this sprite. If you want to customize how sprite drawing works, override this function.
-
fill
()¶ Utility function to make this sprite completely fill its parent sprite. If it has no parent sprite, it will fill the screen.
-
is_being_collided
(other)¶ Returns whether this sprite is colliding with another one.
Parameters: sprite ( Sprite
) – AnotherSprite
instance to test.Returns: Whether this sprite is colliding with the other one. Return type: bool
-
is_colliding_with
(other)¶ Returns whether this sprite is colliding with another one. Currently just passes responsibility to the other sprite by calling its
Sprite.is_being_collided
function.Parameters: sprite ( Sprite
) – AnotherSprite
instance to test.Returns: Whether this sprite is colliding with the other one. Return type: bool
-
is_mouse_over
()¶ Returns whether the mouse cursor is currently inside this sprite’s bounding box.
Returns: Whether the mouse is inside. Return type: bool - Todo:
- Come up with some type of GUI-like event system. Simple functions like these will not help determine whether there’s a sprite above this one that should get the focus first and such.
-
kill
()¶ Marks this sprite to be deleted on the next frame.
-
load_surface
(surface)¶ Sets the graphic for this sprite, and makes the size match the size of this graphic.
Parameters: surface (SGL Surface) – A surface containing the graphic you want this sprite to draw.
-
on_add
()¶ Exectued when a sprite is added. It’s recommended to put initialization code here instead of
__init__
, so that the sprite will have proper access to its parent elements during and after initialization. (Not all the examples have been updated to work like this, though.)
-
position
¶ tuple: The local position of this sprite (before any transformations have been applied).
Can also be accessed through the
x
andy
attributes.
-
preupdate
()¶ Called before this sprite updates. Currently, contains logic to save the previous position and update the screen position.
-
prev_position
¶ tuple: Read-only property returning the local position of this sprite on the previous frame.
Can also be accessed through the
prev_x
andprev_y
attributes.
-
real_anchor
¶ tuple: Read-only property returning the position of the anchor point of this sprite after percentage values (such as 0.5) have been converted to real coordinates.
-
rect
¶ sgl.lib.Rect.Rect
: Read-only property returning the bounding box of this sprite in local coordinates.
-
screen_collision_rect
¶ sgl.lib.Rect.Rect
: Read-only property returning the bounding box of this sprite in screen coordinates (after parent and camera transformations have been applied).
-
screen_position
¶ tuple: Read-only property returning the screen position of this sprite (after parent and camera transformations have been applied). Can also be accessed through the
screen_x
andscreen_y
attributes.
-
screen_rect
¶ sgl.lib.Rect.Rect
: Read-only property returning the bounding box of this sprite in screen coordinates (after camera and parent transformations have been applied).
-
size
¶ tuple: The size of this sprite. Used for positioning the anchor point, determining whether a sprite is visible and should be drawn, and as a default size for the sprite’s collision bounding box.
-
update
()¶ Called every frame to update this sprite and its child sprites’ logic. To define logic for your sprite, override this function. If you want child sprite updating to work properly, though, make sure to call the
Sprite
base classes’ update function before yours.
-
update_screen_positions
()¶ Screen positions are slightly broken. By default, screen coordinates are only updated in the
Sprite.preupdate
function. This means that sometimes they will update a frame late if you change a parent sprite’s position during itsSprite.update
phase. In addition, even when it does update, sometimes position changes will not propagate through the hierarchy correctly.This function can help you work around that by forcing all of this sprite and all of its child sprites to recursively update their screen coordinates to the correct value. If you see child sprites behaving strangely, try adding a call to this in the parent sprite’s code.
I realize this is a bit of a hack, but it is the lesser evil. I tried to update all screen positions on every frame, but that slowed the sprite system down significantly and created new positioning problems that, unlike these, could not be solved with a single extra function call.
-
world_collision_rect
¶ sgl.lib.Rect.Rect
: Read-only property returning the bounding box of this sprite in world coordinates (after parent, but not camera transformations have been applied).- Todo:
- Make this property only disregard camera transformations, instead of all of them.
-
world_to_screen
(x, y)¶ Converts local coordinates in this sprite’s space to screen coordinates.
Parameters: - x (number) – The x coordinates to convert.
- y (number) – The y coordinates to convert.
Returns: The new coordinates.
Return type: tuple
-
-
class
sgl.lib.Sprite.
SpriteGroup
¶ A subclass of
Sprite
designed to do nothing but hold other sprites.Identical to a plain
Sprite
, exceptinfinite_space
is turned on by default.
-
sgl.lib.Sprite.
Spritesheet
(surface, frame_width=0, frame_height=0)¶ Takes a surface containing a spritesheet and extracts each individual frame from it. Often necessary to use
AnimatedSprite
effectively.Parameters: - surface (SGL Surface) – A graphic containing a spritesheet with
equally sized frames starting from (0,0). This function
does not do anything in regards to transparency. You must
load your graphic with
sgl.set_transparent_color
orsgl.load_alpha_image
for transparency to work. - frame_width (int) – How wide each frame is.
- frame_height (int) – How high each frame is.
Returns: A list of each frame in this spritesheet.
Return type: list
- Todo:
- This may eventually be a class, so that spritesheets can blit chunks from a single surface instead of initializing possibly hundreds of tiny little surfaces for each frame. I think that will be more efficient, particularly with hardware accelerated backends. I’ll try to make this class behave identically to a list in most cases, but keep in mind that code depending on modifying the frames of a spritesheet like a list could break when this change happens.
- surface (SGL Surface) – A graphic containing a spritesheet with
equally sized frames starting from (0,0). This function
does not do anything in regards to transparency. You must
load your graphic with
-
class
sgl.lib.Sprite.
Viewport
¶ A
Sprite
that behaves identically to aScene
in most circumstances, except it is only rendered in the bounds of its bounding box.- Todo:
- Make scenes and viewports the same thing. Like, a scene automatically become a viewport if its size does not fill the screen, it will be drawn bigger if at a scale, etc.
- When this happens, force all the examples to run in wiggling (or at least bouncing) viewports. It should be possible to embed scenes in other scenes arbitrarily. The ability to make game anthologies, or browsable demo packages, like the WxPython demo, should be nearly automatic.
sgl.lib.Collision¶
This module provides some functions for working with bounding box based collisions. It is fairly basic, and not very optimized, but for most use cases, it works out of the box and does not let objects randomly get stuck in and fall through each other, something a disturbing amount of game engines lack.
-
class
sgl.lib.Collision.
CollisionChecker
(object1, object2, callback)¶ An object that checks whether sprites are overlapping every frame, and takes user-specified action as a result.
This is mostly used by the backend of
sgl.lib.Collision
. From an end user’s perspective, this class will mostly be used to stop and resume collision checking.-
pause
()¶ Temporarily pauses this collision checker, without deleting it.
-
resume
()¶ Resumes a previously paused collision checker.
-
stop
()¶ Stops a collision checker entirely by deleting the object.
-
-
class
sgl.lib.Collision.
SlidingCollisionChecker
(object1, object2, callback)¶ Identical to a normal
CollisionChecker
, except that its update function provides additional logic to move objects outside of each other.
-
sgl.lib.Collision.
add
(object1, object2, callback)¶ Creates a basic collision checker, which will call a callback on every frame two objects overlap.
Will use a sprite’s visible rectangle for collisions, unless a Sprite has a custom
Sprite.collision_rect
defined.Parameters: - object1 (
Sprite
) – The first object to test. This must be a single sprite—subsprites will not be tested for collision. - object2 (
Sprite
) – The second object to test. This can be any kind of sprite, and subsprites will be tested for collision. - callback (function) –
The function to call when the objects overlap. This function will have different information passed to it depending on how many arguments it accepts.
- If it accepts no arguments, nothing special will be passed to it.
- If it accepts 1 argument, it will be passed a reference
to the subsprite of
object2
thatobject1
collided with on that frame. - If it accepts 2 arguments, it will be passed a
reference to
object1
, and then the subsprite ofobject2
thatobject1
collided with on that frame. - If it accepts 3 arguments, it will be passed all of the
above, and then a
sgl.lib.Rect.Rect
representing the intersected area between the two sprites.
Returns: An object that can be used to pause or stop this collision checking if necessary.
Return type: - object1 (
-
sgl.lib.Collision.
add_sliding
(object1, object2, callback=None)¶ Creates a sliding collision checker, which will prevent
object1
from going inside any of the sprites ofobject2
. It is called a “sliding” collision checker because if an object is moving diagonally, it will continue to move in the free direction even if it collides against a wall. Because the collision algorithms are bounding box based, though, diagonal obstacles are not supported.The sliding collision algorithm checks every pixel position between
object1
‘s position on the current and previous frame to check collision, so object should not be of the slide through each other when they are moving fast or if the frame rate gets low. A consequence of this, however, is that this means manual position updates are subject to collision checking as well–if you want to teleport an object through a wall, you must temporarily turn off sliding collision checking for that to work.Because of this, it’s recommended you always save a reference to the
SlidingCollisionChecker
object this function returns.Will use a sprite’s visible rectangle for collisions, unless a Sprite has a custom
Sprite.collision_rect
defined.Parameters: - object1 (
Sprite
) – The first object to test. This must be a single sprite—subsprites will not be tested for collision. - object2 (
Sprite
) – The second object to test. This can be any kind of sprite, and subsprites will be tested for collision. - callback (function) –
The function to call when the objects overlap. This function will have different information passed to it depending on how many arguments it accepts.
- If it accepts no arguments, nothing special will be passed to it.
- If it accepts 1 argument, it will be passed a list of
strings that can contain various permutations of
"left"
,"right"
,"top"
, and"bottom"
. The strings present in this list will tell you on what sidesobject1
was hit before its position was corrected by the collision checker.
Returns: An object that can be used to pause or stop this collision checking if necessary.
Return type: - object1 (
-
sgl.lib.Collision.
update
()¶ Must be called every frame for any of the collision checkers to work.
- Todo:
- It might be handy to have this and the other continuously executing libraries (tween, time...) automatically inject themselves into the SGL event loop instead of making the user manually call their update functions every frame. Currently it is slightly annoying that one has to plan out a way to make sure these update functions are called exactly once every frame in their entire program. I’m not sure if handling this automatically is too “magic,” though...
sgl.lib.Layout¶
This module mainly provides one class, FlowLayout
, that
lets one arrange sprite similarly to the automatic layout functions of
some GUI frameworks. This can be useful for laying out game GUIs in a
resolution independent way.
-
class
sgl.lib.Layout.
FlowLayout
(horizontal=False)¶ A Sprite that provides similar functionality to wxWidget’s BoxSizer.
Parameters: horizontal (bool) – Whether this layout runs horizontally or not. If this is False, the default, it will run vertically. This can be set later with the horizontal
property.-
add
(sprite, proportion=0.0, proportion_other_way=0.0, align=0.0)¶ Behaves similarly to
Sprite.add
, but with additional parameters to determine how the added sprite will be fit into the layout.Parameters: - sprite (
Sprite
) – ASprite
instance to add. - proportion (float) –
The amount of space this sprite will take up in the direction that the layout flows (which is set by
horizontal
). If this value is 0, this sprite will merely take up its original size. If it is anything else, its size will be calculated relative to the size of the layout and the other sprites.Basically, the way it works is this: take all of the sprites with proportion values, and add those numbers up. That will be the total proportion value. The size of each sprite will be its own proportion value over the total proportion value.
So, if the proportion value is 1 for every sprite in a layout, their sizes will be distributed evenly across the layout.
If one of those sprites has a proportion value of 2, however, it will be twice as large as the other ones, and the other sprites’ sizes will be twice as small. It all balances out in the end.
It would be equally valid to set the larger sprite’s proportion value to 1, and the smaller sprites’ to 0.5 for this—the exact values do not matter as much as how the proportion values relate to each other. This is slightly different from wxWidgets, in which proportion values must be whole numbers.
It may make it easier to understand certain layouts if you specify proportion values as fractions (such as 0.25), and make sure they add up to 1.0 in the end.
It is also important to note that the space taken into account for proportioned sprites is the space left behind by non-proportioned sprites. So, if you have a layout with a few non-proportioned sprites, and add a sprite with a proportion value of 1 to that layout, it will not fill the entire layout—it will take up the entire space left behind by the other sprites.
This gives you many possibilities for positioning non-proportioned sprites. If you have two normal sprites and put a sprites with a proportion value of 1 between them, for example, you will force both normal sprites to be on opposite ends of the layout. If you want to distribute normal sprites equally across an area, you can space them out with proportion 1 spaces. And so on.
Proportion values are slightly difficult to understand, but once you get them, they will open up many possibilities for layout.
- proportion_other_way (float) –
This argument is much easier to understand than the proportion value.
It is a percentage value specifying how much space the sprite will take up on the axis perpendicular to the direction the layout flows. So, if the layout flows vertically, this specifies how a sprite’s horizontal size will be affected by it.
Usually, you will either want this value to be 0, which will leave the sprite’s size in that direction untouched, or 1.0, which will make the sprite completely fill the layout in that direction. Anything in between will leave the sprite somewhere in the middle of that. (Or, more accurately, the size of the layout in that direction times this value.)
- align (float) –
If
proportion_other_way
leaves any breathing room for the sprite, this specifies how that sprite should be positioned in the layout.If this is 0, the sprite will rest along the left or top edge of the layout. If this is 0.5, it will be centered along that direction. If this is 1.0, it will be bottom or right aligned. And other values will be somewhere inbetween.
You will not need to set this argument in most cases. If you do, 0.5 will likely be the most common value you’ll use for it.
- sprite (
-
horizontal
¶ Whether this layout runs horizontally or not. If this is False, the default, it will run vertically.
-
reflow
()¶ Repositions and resizes the elements inside to adhere to the layout rules. Must always be manually called to update the objects inside, even after adding new objects. (I tried having it automatically update the layouts, and the annoyance of having sprites move around at unpredictable times outweighed the benefits.)
Is a potentially expensive function. If there are proportioned sprites in the layout, it must run two passes through the objects inside. In most cases, is recommended to call this function once—after this layout has been positioned and sized correctly, and after all of its items have been added.
If any sprites inside this layout have a
reflow
method, it will call it. This is useful for embedding layouts hierarchically, or specifying custom logic for sprites when they are resized.
-
-
class
sgl.lib.Layout.
Spacer
(width=0, height=0)¶ A dummy object you can add to
FlowLayout
instead of aSprite
when you want to have an invisible spacer sprite to affect the positioning of other sprites.Provides the absolute minimum amount of data required of an object to interact with the sprite system.
Parameters: - width (int) – The width of the spacer, if you do not plan to have it controlled by a proportion value.
- height (int) – The height of the spacer, if you do not plan to have it controlled by a proportion value.
sgl.lib.ScriptParser¶
This module provides the functionality to parse SGLscript. It is
mainly used behind the scenes to provide sgl.lib.Script
with
the data it needs to operate, but you may need to interact with this
module for real-time script manipulation.
An SGLscript file is formatted like follows:
First, there is a header section. The format of this section is documented in
ScriptParser.header
. (Please read that after reading this, though—the documentation for that function assumes some familiarity with the format of commands.)Then, you must specify the beginning of a “label” by having a line that begins with
@
, with the rest of the line consisting of the label name. Any line beginning with a@
starts a new label.Warning
This may be deprecated in favor of just using the normal command syntax to define labels in the future. Even if that happens, though, it will be possible to replicate the current behavior through slightly more configurable macros.
Every line after that is interpreted as the body of a given label.
In the body, two main rules apply:
- Normal text is interpreted as dialogue that will get output to the screen.
- Anything with in square braces (
[
and]
) is interpreted as a command.
Commands can consist of three components:
- All commands must have a command name. This determines what function is used to handle this command when the script is executed.
- Then, after this, they can have positional arguments. These, like positional arguments in Python, or arguments that are specified by order instead of by name.
- Then, after (or instead of) positional arguments, commands can have keyword arguments. These are arguments in which their name is specified, and then their value.
There are two syntaxes of commands:
There are the old-style commands, which behave like HTML tags. In this syntax, the command name is specified at the beginning, and is ended by whitespace. After this whitespace, you can have whitespace separated positional arguments, and then whitespace separated keyword arguments. Keyword arguments are given in a
key=value
form, and any amount of whitespace is accepted before and after the=
.The type of commands look like this:
[show-background "tree.png" transition="fade-in" fade-time=5]
.Warning
These types of commands will be deprecated as soon as possible. Don’t use them. I’m merely documenting them so the source code makes more sense.
There are the new-style commands, or pretty commands. With this syntax, command names are first, but are ended by a colon (
:
). Because of this, command names can have spaces in them. Then, positional arguments can be specified the same way as with the old-style. Then, keyword arguments can be specified, but in akey: value
form. Thus, keyword arguments, like command names, can also have spaces in their names. This creates some ambiguous parsing situations, but these commands are much easier to read.These types of commands look like this:
[show background: "tree.png" transition: "fade-in" fade time: 5]
.With the sense of commands, command and keyword argument names are case insensitive, and can handle arbitrary whitespace in the middle of them. As long as you don’t misspell them, you can mangle their formatting quite a bit and they will parse correctly.
- Todo:
- Okay, we might have to see about that “arbitrary” whitespace... :|
Warning
These types of commands will be what SGLscript uses in the future. Positional arguments may be deprecated in the future, so please stick to using keyword arguments only if you want to play it safe. This will also make your scripts easier to read.
Both styles use identical syntax for values for arguments:
If a value begins with a
"
or'
, it is a string. These behave the same as Python strings—you must escape the other type of quote with backslashes.If a value begins with a digit or
-
, it is a number. Mathematical expressions are not currently allowed—you must just input numbers.Anything else is interpreted as a keyword—or a single word string. This string must have no spaces is in it, and it will be converted to lowercase during parsing. This is a shortcut for specifying short string arguments without having to type quotes.
For example, the earlier example could be inputted as
[show background: tree.png transition: fade-in fade time: 5]
with no information being lost.Warning
Quoteless string values may be deprecated in the future. They can create some annoyingly ambiguous parsing situations with pretty commands, like
[show thing: cool transition: "dissolve"]
. Is “cool” a positional argument or is the name of the keyword argument “cool transition”?
I cannot guarantee the behavior of anything left undescribed here. You have been warned.
In addition, the parser supports some automatic manipulation of
commands during parsing. This is documented more thoroughly in
ParserSettings
.
-
class
sgl.lib.ScriptParser.
Command
(name, pos_arg=[], key_arg={})¶ Represents a single command in a script. Converting this to a string should yield a parsable command.
- Todo:
- Make that yield a parsable pretty command.
-
class
sgl.lib.ScriptParser.
Label
(name, body)¶ A class to represent labels in the script.
-
class
sgl.lib.ScriptParser.
Parser
(text='')¶ A base class for handling recursive descent parsers (possibly badly).
You should definitely not use this class in your own programs, but I need to document it for myself, so there.
Parameters: text (string) – If this argument is specified, it will call load_text
with this text during initialization.-
at_content_beginning
()¶ Returns if we’re at the beginning of the content of the line. (As in, past the whitespace.)
-
at_line_beginning
()¶ Returns if we’re at the beginning of the given line.
-
at_literal
()¶ Returns whether we currently at the beginning of a string or number literal.
-
char
¶ Returns the current character.
-
eat
(char)¶ Eats a character, and if it’s not what you specify, raises an error with
error
.Parameters: char (string) – The character the current character must be equal to.
-
error
(text)¶ Raises an error and prints information about the state of the parser.
Parameters: text (string) – A short description of the error. Raises: ParserError
– Will always raise this.- Todo:
- Maybe I should be using normal exceptions like a normal person? Not really sure how to easily do that while keeping track of the line and column position, though.
-
line_empty
()¶ Peeks ahead to see if the current line has any non-whitespace content or not.
-
literal
()¶ Reads a string or number literal, and returns the parsed value.
-
load_text
(text)¶ Loads text into the parser, and resets all the position counters.
Parameters: text (string) – A string containing the text to load. Should be able to deal fine with Unicode. Should.
-
newline
()¶ Expects a newline at char.
-
next
()¶ Moves the position onwards, keeping track of the current line and column.
-
next_char
¶ Read-only property returning the character after the current one.
-
position_valid
()¶ Returns if we’re in the document.
-
prev_char
¶ Read-only property returning the character before the current one.
-
symbol
()¶ Reads a symbol name.
- Todo:
- Has a bunch of hardcoded values for SGLscript. Factor out.
-
whitespace
(allow_newline=True)¶ Keeps advancing the cursor until reaching non-whitespace characters.
Parameters: allow_newline (bool) – Whether to eat newlines as well.
-
-
exception
sgl.lib.ScriptParser.
ParserError
(text, line, char)¶ This exception handles errors that happened while parsing a script.
-
class
sgl.lib.ScriptParser.
ParserSettings
¶ An object for holding settings on how the SGLscript parser behaves that the user is meant to be able to change.
-
class
sgl.lib.ScriptParser.
ScriptParser
(text='')¶ The object you’ll be interacting with the most if you use this module. This is what actually lets you take a string, parse it, and get back the proper objects.
- Todo:
- Trash a good portion of BodyParser.
- Un-hardcode the concept of labels. Have labels just be commands whose position is tracked so they can be quickly accessed.
Parameters: text (string) – If this argument is specified, it will call load_text
with this text during initialization.-
header
()¶ Parses special commands before the first label. You should not be calling this yourself, but the header is strange enough to warrant additional documentation.
Currently, you can only use two commands here:
define macro
: This takes two positional arguments. The first one is the original text, the second one is what to replace that text with.use pretty commands
: This determines whether to parse all commands as pretty commands or not. It only takes one positional argument, which must be the string or keyword “yes” to activate this.
If you attempt to use any other commands, or normal body text here, it will raise a HeaderError. Comments and all permutations of whitespace are fine.
You can potentially raise a MacroError by defining macros that begin with characters that conflict with SGLscript (currently
\
,[
, and@
). Don’t do this.Both of those types of exceptions only have one parameter,
text
, so I’m not documenting them in detail.
-
parse
()¶ Parses a script loaded by
load_text
and returns a dictionary of labels.Returns: A dictionary in which the keys are the name of a given level, and the value is the corresponding Label
object.Return type: dictionary - Todo:
Label
objects also contains the name of the label. There has to be a less dumb way to do this.
-
reset_settings
()¶ Resets all parser settings to their default values.