CSC111 Lab 9 Solutions 2011
--D. Thiebaut 15:51, 2 November 2011 (EDT)
Graphics
from graphics import *
def isInside( xc, yc, x1, y1, x2, y2 ):
if x1 <= xc <= x2 and y1 <= yc <= y2:
return 1
return 0
def main():
w = 600
h = 400
x1 = 20
y1 = 30
x2 = w // 3
y2 = h - y1
win = GraphWin( "Click me to stop!", w, h )
c = Circle( Point( w//2, h//4 ), 20 )
c.setFill( "yellow" )
c.draw( win )
r = Rectangle( Point( x1, y1 ), Point( x2, y2 ) )
r.setWidth(3)
r.draw( win )
dirX = 5
dirY = 3
while True:
c.move( dirX, dirY )
xc = c.getCenter().getX()
yc = c.getCenter().getY()
if not ( 0 <= xc <= w ): dirX = -dirX
if not ( 0 <= yc <= h ): dirY = -dirY
if isInside( xc, yc, x1, y1, x2, y2 )== 1:
# center inside rectangle
c.setFill( "red" )
else:
# center outside rectangle
c.setFill( "yellow" )
if win.checkMouse() != None:
break
win.close()
main()
- with points:
from graphics import *
def isInside( center, P1, P2 ):
if ( P1.getX() <= center.getX() <= P2.getX()
and P1.getY() <= center.getY() <= P2.getY() ):
return 1
return 0
def main():
w = 600
h = 400
x1 = 20
y1 = 30
x2 = w // 3
y2 = h - y1
win = GraphWin( "Click me to stop!", w, h )
c = Circle( Point( w//2, h//4 ), 20 )
c.setFill( "yellow" )
c.draw( win )
P1 = Point( x1, y1 )
P2 = Point( x2, y2 )
r = Rectangle( P1, P2 )
r.setWidth(3)
r.draw( win )
dirX = 5
dirY = 3
while True:
c.move( dirX, dirY )
xc = c.getCenter().getX()
yc = c.getCenter().getY()
if not ( 0 <= xc <= w ): dirX = -dirX
if not ( 0 <= yc <= h ): dirY = -dirY
if isInside( c.getCenter(), P1, P2 )== 1:
# center inside rectangle
c.setFill( "red" )
else:
# center outside rectangle
c.setFill( "yellow" )
if win.checkMouse() != None:
break
win.close()
main()
- with objects
- with points:
from graphics import *
def isInside( circle, rect ):
if ( rect.getP1().getX() <= circle.getCenter().getX() <= rect.getP2().getX()
and rect.getP1().getY() <= circle.getCenter().getY() <= rect.getP2().getY() ):
return 1
return 0
def main():
w = 600
h = 400
x1 = 20
y1 = 30
x2 = w // 3
y2 = h - y1
win = GraphWin( "Click me to stop!", w, h )
c = Circle( Point( w//2, h//4 ), 20 )
c.setFill( "yellow" )
c.draw( win )
P1 = Point( x1, y1 )
P2 = Point( x2, y2 )
r = Rectangle( P1, P2 )
r.setWidth(3)
r.draw( win )
P1 = Point( x1+300, y1 )
P2 = Point( x2+300, y2 )
r2 = Rectangle( P1, P2 )
r2.setWidth( 3 )
r2.draw( win )
dirX = 5
dirY = 3
while True:
c.move( dirX, dirY )
xc = c.getCenter().getX()
yc = c.getCenter().getY()
if not ( 0 <= xc <= w ): dirX = -dirX
if not ( 0 <= yc <= h ): dirY = -dirY
if isInside( c, r )== 1:
# center inside rectangle
c.setFill( "red" )
elif isInside( c, r2 ) == 1:
c.setFill( "blue" )
else:
# center outside rectangles
c.setFill( "yellow" )
if win.checkMouse() != None:
break
win.close()
main()