PyGame
Python
Sample PyGame files
Sample Python files
PyGame
I actually ran across a good introductory one on the web, so will simply post a link for now, from Comp Sci at UNSW
To determine the direction from one object's position to another in PyGame, here's a direction function using a quick and dirty bit of trig. You can use pygame.mouse.get_pos() to look up the current position of the mouse and pass that as x2,y2.
# compute the direction from (x1,y1) to (x2,y2) # assuming 0-360 degrees goes counterclockwise # with 0 degrees facing directly to the right def comp_direction(x1, y1, x2, y2): # handle a few special cases if (x1 == x2): if (y1 < y2): return 0 else: return 180 elif (y1 == y2): if (x1 < x2): return 90 else: return 270 # compute the degrees in radians, using tan = opp/adj # and arctan(tan) to get the actual angle rad_tan = (x2 - x1) / (y2 - y1) rad_angle = math.atan(rad_tan) # now convert the angle to degrees deg_angle = 180 * rad_angle / math.pi # note that deg_angle will be in the range -90 to +90, # and we have to convert to a 0-360 degree value based # on which quadrant (x2,y2) falls into relative to (x1,y1) # | # deg_angle < 0 | deg_angle > 0 # we want 90-180 | we want 0-90 # | # ----------------+---------------- # | # deg_angle > 0 | deg_angle < 0 # we want 180-270 | we want 270-360 # | if (x1 < x2): if (y1 < y2): return deg_angle else: return 360 + deg_angle elif (y1 < y2): return 180 + deg_angle else: return 180 + deg_angle
Python
# you can use a list of lists to act like a two-dimensional array arr2d = [ [0, 1], [2, 3], [4, 5] ] print arr2d # to access an entire row, refer to it by the row index, e.g.: print arr2d[0] # to access a single element, use the [row][column] style, e.g.: print arr2d[0][0] # add a new row to the array (i.e. append a new element to the list) use the append method: arr.append([6,7]) print arr2d # similarly, to add a new element to the end of a row, apply append to a specific row, e.g: arr2d[0].append(-1) print arr2d
# __del__ is the Python equivalent of a destructor, e.g. class myObj: def __init__(self): print "object created" def __del__(self): print "object destroyed" myvar = x() del x
Language trivia: sometimes developers create objects that reference themselves, or cyclic references where A references B and B references A. In such cases, the order they get destroyed in would be arbitrary, and Python won't destroy them if you have created your own __del__ method for the objects. |