WEEK04: computer graphics, using objects
---------------------------------------------------------------
F: getting mouse and key clicks, getX() and getY(), using sleep for animations
ANIMATION and SLEEP:
this simple animation doesn't look very good:
>>> from graphics import *
>>> w = GraphWin("hello",600,600)
>>> p = Point(100,300)
>>> c = Circle(p,50)
>>> c.draw(w)
>>> c.setFill("blue")
>>> for i in range(200):
... c.move(1,0)
try adding the sleep command to slow down the animation:
>>> from time import sleep
>>> for i in range(200):
... c.move(1,0)
... sleep(0.05)
MOUSE AND KEY CLICKS:
gw = GraphWin("title", 500, 500)
for i in range(10):
p = gw.getMouse()
print p
print p.getX()
print p.getY()
- getMouse() returns a graphics Point object, so we can save
it to a variable (p) and do something with it (put a Circle
at that point?)
- getKey() will do the same but with keyboard clicks:
>>> from graphics import *
>>> gw = GraphWin("title", 500, 500)
>>> for i in range(10):
... key = gw.getKey()
... print key
...
space
Escape
Right
Left
BackSpace
Return
a
b
c
Shift_L
(with the focus in the graphics window, I hit these keys:
space bar, Esc, right arrow, left arrow, backspace, enter,a,b,c,shift)
- similar to these, checkMouse() and checkKey() check for clicks
but don't pause the program. If there's a click, they return it
(the point or the key); if there was no click, they return None
- if you want to animate something until the user clicks the mouse:
while True:
p = gw.checkMouse()
if p != None:
break # we got a mouse click, so user is done
else:
#
# go on with animation code here
#
** see if you can write this program:
- ask user to click 10 times and put a circle at each click-point
- animate the 10 circles moving in random directions
- here's the pseudo code for this:
open graphics window
initialize empty list
loop 10 times:
- get mouse click
- create and draw circle at that point
- add circle object to list
infinite loop:
check if mouse clicked
if yes, break out of loop
else:
loop over all circles in list:
pick random x, y amounts (small)
move circle by x,y