knerr cs21 notes...
back to schedule
WEEK04: computer graphics, using objects
---------------------------------------------------------------
M: more graphics...
LAB4: due next week
QUIZ 2 this Friday
Final Exam is Dec 17, 7-10pm
ODDS AND ENDS:
- strings are immutable! lists are not
- you can't change a letter in a string (even though
you can use indecies to print particular letters)
>>> s = "hello world"
>>> s[0]
'h'
>>> s[0]='H'
Traceback (most recent call last):
File "< stdin > ", line 1, in < module >
TypeError: 'str' object does not support item assignment
- you *can* change elements in a list:
>>> x = range(4)
>>> x[0]
0
>>> x[0] = "pony"
>>> print x
['pony', 1, 2, 3]
OBJECT TERMINOLOGY:
object: a combination of data and methods, all in one thing
data: info about the object (like radius, color)
method: functions to access or modify the object data
constructor: special function called when object is created
instance: constructed objects (ex: c = Circle(p,20)...c is an
instance of the Circle class)
BULLSEYE PROGRAM:
note use of width and height, how color changes for each
ring, how circles created in the for loop all use the same
variable name (c), how the radius decreases with each iteration
of the for loop
from graphics import *
def main():
width = 500
height = 500
w = GraphWin("bullseye",width,height)
w.setBackground("gray40")
# center point
cp = Point(width*0.5,height*0.5)
nrings = 4
maxradius = width*0.5
r = maxradius
dr = maxradius / nrings
# draw nring rings, each time decreasing the radius
for i in range(nrings):
c = Circle(cp, r)
# make the ring color alternate
if i % 2 == 0:
c.setFill("red")
else:
c.setFill("white")
c.draw(w)
r = r - dr
# wait for mouse click to close the window
ptext = Point(width*0.5,10)
t = Text(ptext, "Click mouse to quit.")
t.draw(w)
w.getMouse()
w.close()
main()
CLONE AND TEXT:
- how are c1 and c2 different?
>>> c = Circle(p,50)
>>> c1 = c
>>> c2 = c.clone()
answer: c2 is a whole new object. c1 just refers to the same
object that c does. saying c1 = c is called aliasing, and you
usually DO NOT want that (i.e., use the clone method!).
- can change displayed text with setText (no need to
undraw, recreate object, then draw again):
>>> t = Text(p,"hello")
>>> t.draw(w)
>>> t.setText("goodbye")
CIRCLE SHIFT:
- start with my circleShift.py program:
cp /home/jk/inclass/circleShift.py circleShift.py
- now modify it to move the circle to wherever the user
clicks the mouse. see if you can move it 4 times, then
close the window.