Python

Software Development Elective Resources

This page and its subpages contain the documentation for the Software Development elective at TSA. Students will learn programming by working on an independent game development project. The programming language used in the course is Python, along with a custom game development library created specifically for this elective called tsagame.py. It uses a combination of pygame for graphics and sound and pybox2d for a physics simulation engine.

Useful links:

TSA Game Module Source Code

Basic Python Tutorial

TSA Game Library Reference

TSA Game Object Reference

 

If you want to install these libraries for use at home, use the following downloads and install them in this order. Note that these installers only work in Windows. There are Mac OSX versions of these utilities, but they require manual file moving into administrative areas of the Mac file system. If you wish to install at home on a Mac, contact the instructor.

1. Python Programming Language

2. PyGame game development module

3. PyBox2D physics simulation engine module

Finally, there’s the TSA-specific files, which includes the custom simplified TSA Game library, tsagame.py. Unzip this file into a work folder of your choice and put all of your projects in it. You can right-click the “gametest.py” file and use “Edit with IDLE” then Run (F5) to make sure everything works. It contains sample graphics and sound files. Add new graphics to the gfx folder (.png format only) and sound to the snd folder (.wav format only.)

4. Sample graphics/sound/test file

 

Quick Reference

Quick reference for basic python and all tsagame library and object features.

 

Gaming library usage: from tsagame import *

 

game.mousemouse object

game.viewx, game.viewyview position

 

game.run() – start the game (after initialization)

game.terminate() – tells the game to quit

game.clear() – tells game to erase all objects

game.setscale(tiles) – how tall is the window?

game.setgravity(gx, gy) – x/y gravitational pull

game.setbackground(‘filename’) – set background image

game.settileinfo(‘c’, DEF) – set up tile ‘c’ attributes

game.setboard(text, builderfunction) – set the board from multi-line string

game.settile(column, row, ‘c’) – set the specified tile letter

game.drawline(x, y, endx, endy, RED, lineweight)

game.drawrect(x, y, endx, endy, RED, lineweight)

game.drawcircle(x, y, radius, RED, lineweight)

BLACK, WHITE, RED, GREEN, BLUE, YELLOW

homemade (red, green, blue) colors

COLORNAME = (0-255, 0-255, 0-255)

 

game.isholding(CONTROL) returns True/False

game.ispressing(CONTROL) returns True/False

CONTROL values: LEFTBUTTON, CENTERBUTTON, RIGHTBUTTON, WHEELUP, WHEELDOWN, UP, DOWN, LEFT, RIGHT, SPACE, A_KEY – Z_KEY, 0_KEY – 9_KEY

game.tile(column, row) – returns ’tile letter at position

game.centerview(object) or (x, y) – center board view

game.boardcolumns() – returns number of columns

game.boardrows() – returns number of rows

game.getlist(DEF) – returns all DEF objects

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

game.persec(n) – returns n as amount per second

game.playsound(‘wavfilename’) – play sound file once

game.playsound(‘wavfilename’, True) – loop sound file

game.stopsound(‘wavfilename’) – stop sound playback

game.datagame.data[‘score’] = 10 is stored permanently

 

 

Objects:

 

ob = Object(OBJECTDEF, x, y, handler) – create object

ob.delete() – delete object

 

ob.x, ob.yposition, ob.angle – rotation(in degrees)

ob.width, ob.heightsize

NOTE: do not change x/y/angle/width/height on physics objects. Use move/spin/goto/pointto/etc. functions

ob.zoverlap depth order (defaults to 100)

ob.isflippedFalse = right, True = left

ob.iscentered – False = set to True for top/left handle

ob.isoverlay – False = set True for menu/text/icon

ob.touchingwhat tile letter is this object touching?

ob.data what definition data was used to make this object? (CIRCLE, ROCKET, etc.)

 

ob.setimage(‘filename’) – change the image

ob.setfont(‘fontname’, 0.5) – set the font and size

ob.settext(‘text’, RED) – change the image to text/color

ob.weldto(other, x, y) – weld this object to another

ob.springto(other, x, y, my_x, my_y, 0.5) – connect by an invisible spring (0.0 = no flex, 1.0 = very flexible)

ob.axleto(other, x, y, my_x, my_y, minangle, maxangle) – connect by a freely rotating joint with optional limits

ob.move(speed, angle, force) – move at max speed m/s in angle direction accelerating with optional force

ob.moveto(speed, other, force) – move at max speed m/s towards other or x, y with optional force

ob.spin(degrees, force) – spin at plus or minus degrees per second with optional force

ob.point(angle) – instantly rotate to a new angle

ob.pointto(other) or (x, y) – rotate to point to something

ob.goto(x, y) – go instantly to a new position

 

ob.ismouseover() – returns True/False

ob.ontile() – returns tile letter this object is directly over

ob.iscolliding(other) – did object just hit another?

ob.istouching(other) – is object still touching another?

ob.iscolliding() – did object just hit the board?

ob.istouching() – is object still touching the board?

ob.distanceto(otherobject) or (x, y) – returns a number

ob.isonscreen() returns True/False

ob.getclosest(DEF) – return closest DEF object

 

Object definition attributes:

Think of the object definitions as a blueprint for the object being created.

DEF = copy(BOX) – start by copying a default definition

DEF.image = ‘filename’ – image file name OR

DEF.image = (LINECOLOR, FILLCOLOR) for polygon

DEF.shape = shapedef – define shape of object (CIRCLESHAPE, BOXSHAPE or list of points in clockwise order [(0, -0.5), (0.5, 0.5), (-0.5, 0.5)])

DEF.isflipped = False – should the image point left?

DEF.width = 1.0 – width of object

DEF.height = 1.0 – height of object

DEF.depth = 100 – initial depth (z-order) of object

DEF.angle = 0 – initial angle of object

DEF.density = 1.0 – kg / square meter density

DEF.bounce = 0.5 – 1.0 for rubber, 0.0 for rock

DEF.friction = 0.5 – 1.0 for glue, 0.0 for ice

DEF.slowing = 1.0 – meters/s/s of directional drag

DEF.spinslowing = 90 – degrees/s/s of rotational drag

DEF.isfast = False – set to True for extremely fast items such as bullets

DEF.isfixed = False – set to True to lock in place

DEF.isturnable = True – set to False to lock angle only

DEF.isoverlay = False – for menus/text/icons on top

DEF.type = 1 – 1-15 for physical objects, 16+ for visuals

DEF.collidetypes = [1, 2, 3] – a list of object types that this object type collides with

 

Built-in object definitions:

 

BOX, CIRCLE, TRIANGLE, TRAPEZOID, CHARACTER, ROCKET, BULLET, PLATFORM, BLOCKS, TREE, TEXTBOX, ICON, RAMPLEFT[LOW/HIGH], RAMPRIGHT[LOW/HIGH]

Generic Python syntax:

 

Numbers:

x = 3 assignment (NOT “==”)

y = x + 5 – 2 addition, subtraction

y = x / 3 division

y = x * (x + 1) multiplication, precedence

y = x % 2 modulus (remainder)

y = 7 / 2 division

x = x + 1 different from algebra, x is now 4

 

Text strings:

w = ‘hello’ strings are different from numbers

w = ‘help’ + ‘ful’ string adding

c = w[3] accessing single letters(result: ‘p’)

try x = 5 and a = ‘7’, then

y = x + a ERROR! no adding strings+numbers

y = x + int(a) but you can convert (result: 12)

b = str(x) + a (result: ’57’)

 

Lists:

grades = [85, 92, 97]

print(grades[1]) this will be 92, NOT 85

del grades[1] grades is now [85, 97]

grades.append(74) grades is now [85, 97, 74]

for g in grades : print(g) this runs for EACH value in the list

curvedgrades = [g + 3 for g in grades]

curvedgrades will now be [88, 100, 77]

stuff = [2, ‘hello’, 1, Object()] items can vary!

multi = [[6, 3], [1, 4], [5, 2]] lists inside a list!

print(len(multi)) prints the length (3, not 6!)

 

Dictionaries:

student = {‘name’:’Joe’, 1:’biology’, 2:’calculus’}

print student[‘name’] – works like a list, but indexed by any type at all, not just numbers

student[‘grades’] = gradelist – add or change items

del student[‘name’] – remove items completely

if ‘name’ in student : print “student has a name” – test to see if a dictionary contains a particular index or not

spring = {3:’art’, 4:’games’, ‘name’:’Joseph’}

student.update(spring) – adds or changes for each item

use {index:value for item in list_or_dictionary} to build a dictionary easily

gradedict = {i + 1:grades[i] for i in range(len(grades))}

gradedict is now {1:85, 2:97, 3:74}

 

Objects:

ob = Object(CHARACTER) – this creates a new object

ob.name = “Joe” – objects can contain any variables

ob.items = [2, 6, 7] – even lists! Use for inventory, etc.

 

game.player = Object(CHARACTER) – assign variables to the global “game” object if they need to be used everywhere else in the game

 

 

True/False conditions:

 

if x == y : print(x) equal-to (NOT “=”)

if x < y or x > y : print(x) less-than, greater-than

if x <= y : print(x) less-or-equal

if x >= y : print(x) greater-or-equal

if x != y : print(x) not-equal

if x < y and x != 3 : print(x) logical AND

if x < y or y <= 5 : print(x) logical OR

if not ob.isonscreen() : ob.delete() NOT

if x == 2 and (y < 5 or x > 1) : print (x) precedence

elif z == 7 : print(z) “elif” is short for “else if”

else : print(y) use the else statement if something else should happen

 

Looping with the “while” statement:

x = 1
while x <= 10 : as long as x <= 10
    print(x) keep performing indented step(s)
    x = x + 1
print('done!') this only happens once at the end

 

Looping with the “for” statement:

 

for x in range(0, 10) : makes values from 0 to 9
    print(x + 1)

 

Using a “for” loop to use all objects in a list:

 

for bullet in game.getlist(BULLET) :
    if bullet.iscolliding(game.player) :
        game.player.isdead = True

 

this gets a list of bullets and runs the “if” statement for each one of them

 

use “def” to create functions

 

def makebullet(start, target) : 
    b = Object(BULLET, start.x, start.y)
    b.pointto(target)
    b.moveto(10, target)

 

after defining this function, you can now just do one step

makebullet(game.player, enemy) instead of three

 

Object-defining functions

 

def runmissile(m) :
    m.pointto(game.player)
    m.moveto(3, game.player)

 

m = Object(ROCKET, 0, 0, runmissile)

 

The object is defined by how it behaves. In this case, it continuously follows the player around after launch

what tile letter is this object touching?

css.php