TSA Game Library Reference

TSA Game Library Reference

A complete description of the tsagame.py library used in the TSA Software Development elective. This contains detailed examples of how to use each of the features of the global “game” object included in the tsagame.py library, such as game.setbackground and game.run. The documentation describing the features available to individual game objects such as object.move can be found on a different page: TSA Game Object Reference

game.mouse – the mouse object

Use this any time you wish to perform operations relating to the position of the mouse pointer.

Examples of use: parameters in pointto, moveto, distanceto, etc.

from tsagame import *

def runfollower(f) :
    f.setimage('bluerocket')
    f.pointto(game.mouse)
    f.moveto(2, game.mouse) 

def startgame() :
    Object(ROCKET, 0, 0, runfollower)

startgame()
game.run()

game.viewx, game.viewy – view position
Use these to change the view position when navigating a map larger than the screen. Example of use: Note that the player object is not moving, just the view:
from tsagame import *

MAP = '''
aaaaaaaaaaaaaaaa
a   a   a  aa  a
a     a   a  aaa
aaaaaaaaaaaaaaaa
'''

def runplayer(p) :
    if game.isholding(RIGHT) :
        game.viewx += game.persec(3)
    elif game.isholding(LEFT) :
        game.viewx -= game.persec(3)

def startgame() :
    game.settileinfo('a', TREE)
    game.setboard(MAP)
    Object(CHARACTER, 1, 2, runplayer)

startgame()
game.run()

game.data — a data dictionary for storing the game state permanently

game.restore() — Use this function to restore the data from the previous game.

game.data is a dictionary, which means that it can store any information indexed as a label. The label is entirely up to you:

game.data[‘score’] = 123

game.data[‘gold’] = 3290

game.data[‘playername’] = ‘Joe’

game.data[‘inventory’] = [‘key’, ‘baseball’, ‘microscope’]

game.data[‘stats’] = {‘health’:100, ‘strength’:15, ‘magic’:18}

You can see from the inventory and stats examples that the data dictionary can contain not just numbers and text, but can contain lists and even other dictionaries! It’s true that you can store data in the game object itself by doing things like game.score = 123. However, that data is not remembered after you close the game. Any time you need to remember something permanently, store it in the data dictionary: game.data[‘score’] = 123.

Use this for any information that needs to remain persistent from one game to the next. Otherwise, every time you close the program and start it up again, you’ll be starting over from scratch. You can keep track of which rooms have already been visited, what treasure has already been collected, which enemies have been killed, which puzzles have been solved, how much the player has upgraded or purchased or found, etc., etc.

This information is automatically saved to a file for you. When you exit the game, you’ll see a file called yourgamename.py.dat in the same folder as the game.

The loading does not happen automatically. In order to load the data, you must call game.restore() first. Do this right at the beginning of the game:

from tsagame import *
game.restore()

#everything else goes here

game.run()

game.setbackground(‘filename’) – Sets the background image for the game. game.run() – start the game (after initialization) game.terminate() – tells the game to quit game.clear() – tells game to erase all objects
Example: A simple menu example which uses “clear” to erase the game world when moving between the menu and the play environment, and uses “terminate” to quit the game. Note that in this example, “startmenu” is used immediately before running the game because you want the menu to be the first thing the user sees. Also, pressing the right button returns from the game to the menu.

from tsagame import *

def runplayer(p) :
    p.moveto(3, game.mouse, 20)
    if game.ispressing(RIGHTBUTTON) :
        startmenu()

def startgame() :
    game.clear()
    game.setbackground('stars1')
    Object(CIRCLE, 0, 0, runplayer)

def levelselect() :
    print 'no levels yet'

def runitem(ob) :
    if ob.ismouseover() and game.ispressing(LEFTBUTTON) : ob.item['function']()
    ob.settext(ob.item['title'], [BLACK, RED][ob.ismouseover()])

def startmenu() :
    game.clear()
    game.setbackground('paper')
    menu = [
        {'title':'PLAY GAME', 'function':startgame},
        {'title':'Level select', 'function':levelselect},
        {'title':'Quit', 'function':game.terminate}
    ]
    Object(MENUBACK, 4, 3)
    for item in menu :
        Object(TEXTBOX, 2, 1.8 + menu.index(item) * 0.8, runitem).item = item 

startmenu()
game.run()

game.isholding(CONTROL) returns True/False game.ispressing(CONTROL) returns True/False
These functions tell you whether the user is pressing or holding any of the controls, including mouse buttons or keys on the keyboard. The possible values for the control are as follows: LEFTBUTTON, CENTERBUTTON, RIGHTBUTTON, WHEELUP, WHEELDOWN, UP, DOWN, LEFT, RIGHT (the cursor keys), SPACE, A_KEY – Z_KEY, 0_KEY – 9_KEY In this example, pressing the left button once causes a new object to be created at the cursor position, but holding the button down does nothing. Holding the right button down continuously draws a green line between the player object and the mouse

from tsagame import *

def runplayer(p) :
    if game.ispressing(LEFTBUTTON) :
        Object(BOX, game.mouse)
    if game.isholding(RIGHTBUTTON) :
        game.drawline(p.x, p.y, game.mouse.x, game.mouse.y, GREEN)

def startgame() :
    Object(CIRCLE, 4, 3, runplayer)

startgame()
game.run()

game.setgravity(x, y) – set the gravitational force in the x and y directions

game.settileinfo(‘c’, DEF) – set the info for the board map tile letter ‘c’

game.setboard(text, builderfunction) – set the tile-based board map from a multi-line string or array. Can use an optional function defined as def builder(x, y, tileletter) in your program, called for each tile.

game.settile(column, row, ‘c’) – set the tile at column and row to a letter

game.tile(column, row) – returns ‘c’, check the tile letter at column and row

game.centerview(object) or

game.centerview(x, y) – center the view on a specific position

game.boardcolumns() returns int

game.boardrows() returns int

 

These are all functions that manage the tile-based board system. Here is a small example that uses them.

This creates a player object that slowly follows the mouse. The game centers the view around the player object. If the mouse moves over a block tile, it gets changed to a tower, illustrating that you can both look at individual tiles in a map and change them dynamically. The “builder” function demonstrates how to use the map to place objects

from tsagame import *

MAP = '''
aaaaaaaaaaaa
a          a
a       aa a
a   a   a  a
a t    t   a
aaaaaaaaaaaa
'''

def runplayer(p) :
    game.centerview(p)
    p.moveto(1, game.mouse)
    if game.tile(game.mouse.getx(), game.mouse.gety()) == 'a' :
        game.settile(game.mouse.getx(), game.mouse.gety(), 'c')

def builder(tile, x, y) :
    if tile == 't' : Object(TREE, x, y)

def startgame() :
    game.setbackground('paper')
    game.settileinfo('a', BLOCKS)
    game.settileinfo('c', TOWER)
    TREE.width, TREE.height = 1.5, 2
    game.setboard(MAP, builder)
    Object(CHARACTER, 1, 1, runplayer)
startgame()
game.run()

game.getlist(DEF) – returns a list of all objects with that definition
The getlist function will return a list of all objects that use that definition. If you leave the definition blank, getlist will return a list of all of the objects currently in the game. This sample uses getlist to draw lines between the player and every other circle object

from tsagame import *

def runplayer(p) :
    p.moveto(2, game.mouse)
    for c in game.getlist(CIRCLE) :
        game.drawline(p.x, p.y, c.x, c.y, RED)

def startgame() :
    Object(CHARACTER, 4, 3, runplayer)
    for n in range(10) :
        Object(CIRCLE, random() * 8, random() * 6)

startgame()
game.run()

game.drawline(startx, starty, endx, endy, BLACK, thickness)

game.drawrect(startx, starty, width, height, BLACK, thickness)

game.drawcircle(x, y, radius, BLACK, thickness)

 

(thickness is always optional)

BLACK, WHITE, RED, GREEN, BLUE, YELLOW

homemade (red, green, blue) colors: COLORNAME = (0-255, 0-255, 0-255)

 

Drawing primitives. These can be used for bounding rectangles, user-interface items, etc. This sample draws a line between the player object and the mouse, and also draws a rectangle and circle at the mouse position.

from tsagame import *

def runplayer(p) :
    game.drawline(p.x, p.y, game.mouse.x, game.mouse.y, RED)
    game.drawrect(game.mouse.x, game.mouse.y, 3, 1, GREEN)
    game.drawcircle(game.mouse.x, game.mouse.y, 2, BLUE)

def startgame() :
    Object(CIRCLE, 4, 3, runplayer)

startgame()
game.run()

Here’s a recipe for a status bar that appears above a character object. It can be used for health bars, power bars, ammo bars, etc. The parameters are (object, current value, maximum value, empty color, full color, vertical offset). Here is the general-purpose function, followed by examples of a health bar and a power bar, followed by examples of using them inside the runplayer and runenemy functions (if you already have runplayer and runenemy functions, just add the draw function calls inside your existing functions.)

def drawbar(o, current, maximum, empty = RED, full = GREEN, offset = 0.1) :
    w = o.width / 2
    y = o.y - o.height / 2 - offset
    if current < maximum : 
        game.drawline(o.x - w, y, o.x + w, y, empty)
    if o.health > 0 : 
        game.drawline(o.x - w, y, o.x - w + o.width * current / maximum, y, full)

def drawhealthbar(o) :
    drawbar(o, o.health, o.maxhealth)

def drawpowerbar(o) :
    drawbar(o, o.power, o.maxpower, YELLOW, BLUE, 0.2)

def runplayer(p) :
    drawhealthbar(p)
    drawpowerbar(p)

def runenemy(e) :
    drawhealthbar(e)
    drawpowerbar(e)

game.animate([value1, value2, value3], n) – return a value from the list animated at n items per second

This is one of the most important functions in the library. It can animate ANYTHING, not just images. What it does is return the appropriate value from a list so that the item animates and changes n times per second.

This sample demonstrates animating a sequence of colors, a sequence of images, and even using the animation function to iterate through a sequence of directions, making the object pace in a square pattern.

from tsagame import *

def runplayer(p) :
    images = ['blueman1', 'blueman2', 'blueman3', 'blueman4']
    p.setimage(game.animate(images, 6))
    color = game.animate([RED, GREEN, BLUE, WHITE], 10)
    game.drawline(p.x, p.y, game.mouse.x, game.mouse.y, color)
    directions = [0, 90, 180, 270]
    p.move(1, game.animate(directions, 0.5))

def startgame() :
    Object(CHARACTER, 2, 5, runplayer)

startgame()
game.run()

game.persec(n) – returns value of n broken into amount per second

Use this any time you need to modify a value according to a certain amount per second. This is most frequently used with timers. In this sample, the player accumulates 20 gold per second. When holding down the leftbutton, it fires 3 bullets per second. Once every 5 seconds, a new object appears

from tsagame import *

def rungold(g) :
    g.settext('gold: %d' % game.player.gold)

def runplayer(p) :
    p.gold += game.persec(5)
    p.bullettimer -= game.persec(3)
    if game.isholding(LEFTBUTTON) :
        if p.bullettimer <= 0 :
            p.bullettimer = 1
            b = Object(BULLET, p.x, p.y)
            b.pointto(game.mouse)
            b.moveto(3, game.mouse)
    else :
        p.bullettimer = 0

    p.spawntimer -= game.persec(1)
    if p.spawntimer <= 0 :
        Object(CIRCLE, random() * 8, random() * 6)
        p.spawntimer = 5

def startgame() :
    game.player = Object(ICON, 4, 3, runplayer)
    game.player.setimage('blueman1')
    game.player.bullettimer = 0
    game.player.spawntimer = 0
    game.player.gold = 0
    Object(TEXTBOX, 4, 1, rungold)

startgame()
game.run()

game.playsound(‘soundname’) – play sound file (add , True to for looped music) game.stopsound(‘soundname’) – stop sound file

from tsagame import *

def runplayer(p) :
    if game.ispressing(LEFTBUTTON) :
        game.playsound('bonk')
    if game.ispressing(RIGHTBUTTON) :
        game.playsound('boing')
    if game.ispressing(P_KEY) : 
        game.stopsound('polka')

def startgame() :
    game.playsound('polka', True)
    Object(CHARACTER, 4, 3, runplayer)

startgame()
game.run()

random() — get a random decimal number between 0 and 1. To get a random number anywhere from A to B, use random() * (B – A) + A. For example, to get a random number between 10 and 15, use random() * 5 + 10.

randint(A, B) — get a random integer between A and B (inclusive.)

colors = [YELLOW, RED, BLACK, ORANGE]
randomcolor = colors[randint(0, 3)] # select a random color from the above list
obj.move(2, random() * 360) # move obj Object instance in a random direction
various recipes

Example of a “store” screen which features rows and columns of items, a cost text box, an attribute text box, a gold indicator and a “done” button. Note that everything in this example is designed to be modified, so you can have more or fewer items, a different resource other than gold, etc.

Remember to set up the attributes ahead of time before allowing the user to visit the store. In other words, they must have started a game first, and the startgame function must have items such as game.data[‘strength’]=10 and game.data[‘strengthcost’]=100 or whatever values are appropriate for your game design.

def runstoregold(g) :
    g.settext('gold: %d' % game.data['gold'])

def runstoreitem(i) :
    datalabel = i.item['data']
    value = game.data[datalabel]
    cost = game.data[datalabel + 'cost']
    i.text.settext(datalabel + ': %d' %  value)
    i.cost.settext('($%d)' % cost, BLACK)
    isover = i.ismouseover() or i.text.ismouseover() or i.cost.ismouseover()
    if game.ispressing(LEFTBUTTON) and isover and game.data['gold'] >= cost:
        game.data[datalabel] += 1
        game.data['gold'] -= cost

def rundone(d) :
    if d.ismouseover() and game.ispressing(LEFTBUTTON) :
        startmenu()

def startstore() :
    game.clear()
    game.setbackground('paper')
    game.setscale(12)

    MENUBACK.width = 14
    MENUBACK.height = 10
    Object(MENUBACK, 8, 6)

    store = [
        {'icon':'redcircle', 'data':'strength'},
        {'icon':'greencircle', 'data':'speed'},
        {'icon':'bluecircle', 'data':'damage'},
        {'icon':'blackcircle', 'data':'capacity'},
        {'icon':'whitecircle', 'data':'magic'},
        {'icon':'graycircle', 'data':'potions'}
    ]

    ICON.depth = 1100
    ICON.iscentered = False
    ICON.image = 'yellowcircle'
    goldind = Object(ICON, 1, 1)
    goldind.text = Object(TEXTBOX, 2, 1, runstoregold)

    done = Object(TEXTBOX, 13, 10, rundone)
    done.settext('Done >>')

    index = 0
    COLUMNSIZE = 3
    ROWSIZE = 3
    for row in range(2) :
        for column in range(3) :
            storeitem = store[index]
            index += 1
            ICON.image = storeitem['icon']
            icon = Object(ICON, column * COLUMNSIZE + 4, row * ROWSIZE + 4, runstoreitem)
            icon.item = storeitem
            icon.text = Object(TEXTBOX, column * COLUMNSIZE + 3, row * ROWSIZE + 4.5)
            icon.text.setfont('Arial', 0.5)
            icon.cost = Object(TEXTBOX, column * COLUMNSIZE + 3, row * ROWSIZE + 5)
            icon.cost.setfont('Arial', 0.5)
css.php