-
Notifications
You must be signed in to change notification settings - Fork 2
Program structure
Every program you create must include at least three actions to work properly:
- Import the packages -- to load in the tkgamelib modules
- Create the canvas with
create_canvas() - Call to
mainloop()at the end of your program, to draw your sprites and process your events.
Here's an example:
# 1, Import the library
from packages import *
# 2, Create the canvas
create_canvas()
# Your own program code here
sprite = ImageSprite('my_images/face.gif')
sprite.pen_down()
def move_sprite():
sprite.move(10,10)
when_key_pressed('<space>', move_sprite)
# 3, Finally, the main program loop
mainloop()
Most of your programs behaviour will be controlled through event handlers, these are instructions to call your code when specific events happen. You can see in the example above that when space is pressed the move_sprite function will be called.
when_key_pressed works will letters, numbers and special keys such as the arrow keys. The function they call can take one parameter event which gives details about what happens. Some examples:
when_key_pressed('<space>', move_sprite) # Note space is all lowercase
when_key_pressed('<Left>', move_sprite) # Note arrow key names are capitalised
when_key_pressed('w', move_sprite)
Other event handlers for mouse events:
when_button1_clickedwhen_button1_dragged-
when_mouse_enter-- the mouse has entered the canvas window when_mouse_motionwhen_button2_clicked
The function you pass to these when_ functions can take one parameter, event, use this to determine the position of the mouse, e.g.:
def drag(event):
sprite.move_to(event.x, event.y)
when_button1_dragged(drag)
You can repeatedly do something using the forever function, this calls a function you've defined periodically, according to the number of milliseconds you specify, e.g.:
forever(alien_follows_hero, 1000) # every second
forever(check_if_won, 500) # every half-second
forever(boulders_fall, 200)
These functions you write for forever (e.g. alien_follows_hero) take no parameters.