Difference between revisions of "CSC111 Lab 10 2010"

From dftwiki3
Jump to: navigation, search
(A class for a wheel)
m (Thiebaut moved page CSC111 Lab 10 to CSC111 Lab 10 2010)
 
(20 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{|
 +
| width="40%" |
 +
__TOC__
 +
|
 
<bluebox>
 
<bluebox>
<br>
 
 
This lab deals with classes, objects, and graphics.  It builds on the examples we saw in class on Monday and Wednesday.
 
This lab deals with classes, objects, and graphics.  It builds on the examples we saw in class on Monday and Wednesday.
 
<br>
 
<br>
 
</bluebox>
 
</bluebox>
 
+
|}
  
 
<br />
 
<br />
Line 12: Line 15:
 
</tanbox>
 
</tanbox>
 
<br />
 
<br />
==A class for a wheel==
+
==Classes for a wheel and a Car==
  
 
Below is the code we wrote in class yesterday:
 
Below is the code we wrote in class yesterday:
  
 
<source lang="python">
 
<source lang="python">
      # lab10_1
+
# carNew.py
      # A program incorporating a class for a wheel
+
# D. Thiebaut
      # which can move freely on the screen
+
# first program using a class to define                                                                             
 +
# a new graphic object: a wheel, which                                                               
 +
# is made of 2 concentric circles.  The class
 +
# Wheel supports methods to initialize the
 +
# graphics object, draw it on the window,
 +
# and move it.
 +
 
 +
from graphics import *
 +
W = 400
 +
H = 400
 +
 
 +
#----------------------------------------------------------------
 +
class Wheel:
 +
    """A class with two concentric circles"""
 +
 
 +
    def __init__( self, center, r1, r2 ):
 +
        """constructor"""
 +
        self.radius1 = min( r1, r2 )
 +
        self.radius2 = max( r1, r2 )
 +
        self.circ1 = Circle( center, self.radius1 )
 +
        self.circ2 = Circle( center, self.radius2 )
 +
       
 +
    def draw( self, win ):
 +
        """draws the wheel on the graphics window win"""
 +
        self.circ2.draw( win )
 +
        self.circ1.draw( win )
 +
 
 +
    def move( self, dx, dy ):
 +
        self.circ1.move( dx, dy )
 +
        self.circ2.move( dx, dy )
 +
 
 +
    def setFill( self, color1, color2 ):
 +
        self.circ1.setFill( color1 )
 +
        self.circ2.setFill( color2 )
 +
 
 +
    def getRadius1( self ):
 +
        """returns the smallest radius"""
 +
        return self.radius1
 +
 
 +
    def getRadius2( self ):
 +
        """returns the largest radius"""
 +
        return self.radius2
 +
 
 +
class Car:
 +
    def __init__( self, P1, P2 ):
 +
        self.body = Rectangle( P1, P2 )
 +
        w =abs( P2.getX()-P1.getX() )
 +
        h =abs( P2.getY()-P1.getY() )
 +
        center1 = Point( w/4+P1.getX(), P2.getY() )
 +
        center2 = Point( P2.getX()-w/4, P2.getY() )
 +
        r2      = w/8
 +
        r1      = r2/2
 +
        self.w1 = Wheel( center1, r1, r2 )
 +
        self.w2 = Wheel( center2, r1, r2 )
 +
 
 +
    def setFill( self, bodyc, tirec, insidec ):
 +
        self.body.setFill( bodyc )
 +
        self.w1.setFill( tirec, insidec )
 +
        self.w2.setFill( tirec, insidec )
 +
 
 +
    def draw( self, win ):
 +
        self.body.draw( win )
 +
        self.w1.draw( win )
 +
        self.w2.draw( win )
 +
 
 +
    def move( self, dx, dy):
 +
        self.body.move( dx, dy )
 +
        self.w1.move( dx, dy )
 +
        self.w2.move( dx, dy )
 +
 
 +
#----------------------------------------------------------------
 +
def waitForClick( win, message ):
 +
    """ waitForClick: stops the GUI and displays a message. 
 +
    Returns when the user clicks the window. The message is erased."""
 +
 
 +
    # wait for user to click mouse to start
 +
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
 +
    startMsg.draw( win )    # display message
 +
    win.getMouse()          # wait
 +
    startMsg.undraw()      # erase
  
      from graphics import *
 
      WinXBR = 700    # window geometry
 
      WinYBR = 500
 
  
 +
def main():
 +
    """demo program for wheel: draws wheel on screen"""
 +
    global W, H
 +
    win = GraphWin( "wheel demo", W, H )
 +
    waitForClick( win, "click to start" )
  
      #----------------------------------------------------------------
+
    #--- create new wheel object ---
      # Wheel class
+
    #w = Wheel( Point( W/2, H/2 ), 20, 40 )
      #----------------------------------------------------------------
+
    #w.setFill( "black", "yellow" )
      class Wheel:
+
    #w.draw( win )
          """A wheel is two concentric circles that move as one unit"""
 
  
          def __init__( self, c, rs, rb ):
+
    car = Car( Point( 20, 20 ), Point( 120, 60 ) )
              """constructor.  Gets the center, the small radius and the large radius"""
+
    car.setFill( "red", "yellow", "black" )
              self.bigCircle  = Circle( c, rb )
+
    car.draw( win )
              self.smallCircle = Circle( c, rs )
+
    waitForClick( win, "click to move" )
  
          def move( self, dx, dy ):
 
              """moves the wheel by dx horizontally and dy vertically"""
 
              self.bigCircle.move( dx, dy )
 
              self.smallCircle.move( dx, dy )
 
  
          def draw( self, win ):
+
    #--- move the wheel ---
              """draws the circles on the window"""
+
    for i in range( 100 ):
              self.bigCircle.draw( win )
+
        car.move( 3, 0 )
              self.smallCircle.draw( win )
 
  
      #----------------------------------------------------------------
+
    waitForClick( win, "click to end" )
      # waitForClick: stops the GUI and displays a message. 
 
      #----------------------------------------------------------------
 
      def waitForClick( win, message ):
 
          # wait for user to click mouse to start
 
          startMsg = Text( Point( WinXBR/2, WinYBR/2 ), message )
 
          startMsg.draw( win )    # display message
 
          win.getMouse()          # wait
 
          startMsg.undraw()       # erase
 
  
 +
main()
  
      #----------------------------------------------------------------
 
      #----------------------------------------------------------------
 
      def main():
 
          win = GraphWin( "Demo: Wheeling Around", WinXBR, WinYBR  )
 
          waitForClick( win, "Click mouse to start" )
 
         
 
          #--- create a wheel ---
 
          w = Wheel( Point( 30, 50 ), 25, 30 )
 
          w.draw( win )
 
             
 
          waitForClick( win, "Click mouse to stop" )
 
          win.close()
 
  
      main()
 
 
</source>
 
</source>
  
  
* Run the program.
+
* Run the program a few times to make sure you understand how it works.
  
* Add a loop that will make the wheel move by 400 steps, horizontally.
+
* Assume that the programmer writing the main program (we always assume that the programmer writing the main program is different from the programmer writing the classes, as is most often the case in real life) forgot the rule that when building a car, the first point passed to the constructor is the top left point of the rectangle defining the body, and that the second point is the bottom right point of the body.
  
* Add a method to set the color of the wheel. This method will receive two colors, and set the color of the inside circle with the first color passed, and the color of the outside circle with the second color passed. Just look at how the methods of the class Wheel work to figure out how to write the setFill() method. It has to be logical. This is new syntax for us, so don't hesitate to ask for help if you aren't sure...
+
:Instead the programmer creates the object '''car''' as follows:
  
* Test the setFill() method.
+
    car = Car( Point( 120, 60 ), Point( 20, 20 ) )
  
* How does your program work if the user specifies the larger radius first in the constructor?  For example, replace the creation of the '''w''' object with this statement:
 
  
      w = Wheel( Point( 30, 50 ), 30, 25 )
+
:Make this modification and run your program.  What happens?
  
:What happens with the colors? 
+
* Fix the '''class''' ''Car'' so that the user can specify any point in any order (top-left, bottom-right), or (top-right, bottom-left), or (bottom-left, top-right), and constructor will correctly define the body and the wheels to fit the shape defined by the two points.
  
* Modify the class so that it swaps the radii around if the user does not specify them in the correct order.
+
* Oh, by the way, the car is a two-door convertible.  Add a door to the car.  The door should be a simple rectangle in the middle of the body of the car, between the two wheels.  (You may want to sketch the shape of the car on paper and figure out what proportions to use to position the door.)
  
* The Circle, Rectangle, Line and other objects supported by the graphics library all have an '''undraw()''' method, that does take no parameters. Add an '''undraw()''' method to your Wheel class.
+
* Add a windshield to the car as well.  You are free to define its shape, and the '''Polygon''' class will provide a nice solution for you.   '''Polygons''' are defined in Section 3.6 of [http://cs.smith.edu/dftwiki/images/1/17/ZelleGraphicsDescription.pdf Zelle's 4-page document on his graphics library].
  
* The wheel is very close to a circle. In fact it's a circle with a smaller circle inside, so some of the methods that apply only to circles should probably be added our wheel class.
+
==Random cars going in random directions==
** getCenter()
 
** getRadius()
 
  
: These are different from the others: they return values. Start with getRadius() first. Make it return the radius of the larger circle.
+
* Make your program create a list of 5 cars.
  
     
+
* Each car has a random horizontal velocity (dy=0), making it go left, or right.  Make dx and dy part of the class, i.e. make these variables '''member variables''' of the class '''Car'''.
: The getCenter() method of the Circle returns a point. Your method should return a point too. In fact, it is a simple method: it will return the point returned by the getCenter() method of any of the two circles... Think about it...
 
  
   
+
* Make your program move all 5 cars at the same time, until all the cars have exited the window.  As soon as the cars all disappear your program will stop.  Think of an efficient way to do this...  This is a bit tricky...  (But we are at a time in the semester where you can deal with tricky questions... :-)
* Test your method with the python statements below... They will energize all your methods:
 
  
          w = Wheel( Point( 30,30 ), 20, 25 )
+
==Fish==
          w.draw( win )
 
          waitForClick( win, "click to color" )   
 
          w.setFill( "orange", "black" )
 
          waitForClick( win, "click to hide" )
 
          w.undraw()
 
          waitForClick( win, "click to bring back" )
 
          w.draw( win )
 
          waitForClick( win, "click to get coordinates of wheel" )
 
          p = w.getCenter()
 
          x = p.getX()
 
          y = p.getY()
 
          waitForClick( win, "center of wheel is at (%d, %d)" % ( x, y ) )
 
          r = w.getRadius()
 
          waitForClick( win, "radius of the wheel is %d" % ( r ) )
 
  
==A class for a car==
+
This section is reported to [[CSC111 Lab 11| Lab 11]]...
  
Rather than telling you how to create the class for a car, try to figure it out by seeing how car objects are used in the simple example below. All you need to know is that a car contains 3 objects: two wheels, and a rectangle, which is horizontal, and whose two bottom corners correspond to the centers of the wheels. Only the outside radius of the wheel is specified. The inside radius is taken to be 60% the size of the outside radius.
+
* Point your browser to http://maven.smith.edu/~111c/index.html
  
Car is the class, and car1 the object.
+
* See all the fish?  Make a note of one of the fish, and get a copy of its file as follows
 +
 
 +
  getcopy fishxx.gif            ''(replace xx by the actual number of the fish you want)''
 +
 
 +
* Write a new graphics program and copy/paste the following code in it:
 +
<br />
  
 
<source lang="python">
 
<source lang="python">
 +
.
 +
 +
from graphics import *
 +
H = 400
 +
W = 400
 +
 +
def waitForClick( win, message ):
 +
    """ waitForClick: stops the GUI and displays a message. 
 +
    Returns when the user clicks the window. The message is erased."""
 +
 +
    # wait for user to click mouse to start
 +
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
 +
    startMsg.draw( win )    # display message
 +
    win.getMouse()          # wait
 +
    startMsg.undraw()      # erase
 +
 +
 +
def main():
 +
    global H, W
 +
    win = GraphWin( "Fish Tank", W, H )
 +
    waitForClick( win, "click to start" )
 +
 +
    fish = Image( Point( W/2, H/2 ), "fish15.gif" )  # replace 15 by the number of your fish
 +
    fish.draw( win )
  
          # create a car, first wheel centered at 30,30, 2nd wheel
+
    waitForClick( win, "click to end" )
          # at 90,30, both wheels with a radius of 20, and the
+
    win.close()
          # rectangle with a height of 40.
 
          car1 = Car( Point( 30, 30 ), 20, Point( 90,30 ), 20, 40 )
 
          car1.draw( win )
 
  
          # color the wheels grey with black tires, and the rectangle yellow
+
main()
          car1.setFill( "black", "grey", "yellow" )
 
  
          # make the car move on the screen   
+
          for i in range( 400 ):
+
.
              car1.move( 1, 0 )
 
             
 
 
</source>
 
</source>
  
==Random cars going in random directions==
+
* Add a for loop and make the object ''fish'' move by dx, dy some fixed number of steps...
 +
 
 +
* Create a an new class which is a fish, with its own file name, and its own dx and dy.
 +
 
 +
* Create an object issued from the class.  Verify that you can make the object move on the screen.
  
* Make your program create a list of 5 cars.
+
* Create a school of several fish that move around the screen. The fish may move in opposite directions, but we'll assume that all fish move in the direction of where their head points to!!!
  
* Each car has a random horizontal velocity, making it go left, or right.
+
* Make the fish go up or down, slightly, randomly, as it moves forward...
  
* Make your program move all 5 cars at the same time, until all the cars have exited the window.  As soon as the cars all disappear your program will stop.
+
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
[[Category:CSC111]][[Category:Labs]][[Category:Python]]

Latest revision as of 05:53, 29 March 2015

This lab deals with classes, objects, and graphics. It builds on the examples we saw in class on Monday and Wednesday.


Fileicon-pdf.png
You may find the following document describing the different graphic objects introduce in the Zelle's textbook useful.


Classes for a wheel and a Car

Below is the code we wrote in class yesterday:

# carNew.py
# D. Thiebaut
# first program using a class to define                                                                               
# a new graphic object: a wheel, which                                                                
# is made of 2 concentric circles.  The class
# Wheel supports methods to initialize the
# graphics object, draw it on the window,
# and move it.

from graphics import *
W = 400
H = 400

#----------------------------------------------------------------
class Wheel:
    """A class with two concentric circles"""

    def __init__( self, center, r1, r2 ):
        """constructor"""
        self.radius1 = min( r1, r2 )
        self.radius2 = max( r1, r2 )
        self.circ1 = Circle( center, self.radius1 )
        self.circ2 = Circle( center, self.radius2 )
        
    def draw( self, win ):
        """draws the wheel on the graphics window win"""
        self.circ2.draw( win )
        self.circ1.draw( win )

    def move( self, dx, dy ):
        self.circ1.move( dx, dy )
        self.circ2.move( dx, dy )

    def setFill( self, color1, color2 ):
        self.circ1.setFill( color1 )
        self.circ2.setFill( color2 )

    def getRadius1( self ):
        """returns the smallest radius"""
        return self.radius1

    def getRadius2( self ):
        """returns the largest radius"""
        return self.radius2

class Car:
    def __init__( self, P1, P2 ):
        self.body = Rectangle( P1, P2 )
        w =abs( P2.getX()-P1.getX() )
        h =abs( P2.getY()-P1.getY() )
        center1 = Point( w/4+P1.getX(), P2.getY() )
        center2 = Point( P2.getX()-w/4, P2.getY() )
        r2      = w/8
        r1      = r2/2
        self.w1 = Wheel( center1, r1, r2 )
        self.w2 = Wheel( center2, r1, r2 )

    def setFill( self, bodyc, tirec, insidec ):
        self.body.setFill( bodyc )
        self.w1.setFill( tirec, insidec )
        self.w2.setFill( tirec, insidec )

    def draw( self, win ):
        self.body.draw( win )
        self.w1.draw( win )
        self.w2.draw( win )

    def move( self, dx, dy):
        self.body.move( dx, dy )
        self.w1.move( dx, dy )
        self.w2.move( dx, dy )

#----------------------------------------------------------------
def waitForClick( win, message ):
    """ waitForClick: stops the GUI and displays a message.  
    Returns when the user clicks the window. The message is erased."""

    # wait for user to click mouse to start
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
    startMsg.draw( win )    # display message
    win.getMouse()          # wait
    startMsg.undraw()       # erase


def main():
    """demo program for wheel: draws wheel on screen"""
    global W, H
    win = GraphWin( "wheel demo", W, H )
    waitForClick( win, "click to start" )

    #--- create new wheel object ---
    #w = Wheel( Point( W/2, H/2 ), 20, 40 )
    #w.setFill( "black", "yellow" )
    #w.draw( win )

    car = Car( Point( 20, 20 ), Point( 120, 60 ) )
    car.setFill( "red", "yellow", "black" )
    car.draw( win )
    waitForClick( win, "click to move" )


    #--- move the wheel ---
    for i in range( 100 ):
        car.move( 3, 0 )

    waitForClick( win, "click to end" )

main()


  • Run the program a few times to make sure you understand how it works.
  • Assume that the programmer writing the main program (we always assume that the programmer writing the main program is different from the programmer writing the classes, as is most often the case in real life) forgot the rule that when building a car, the first point passed to the constructor is the top left point of the rectangle defining the body, and that the second point is the bottom right point of the body.
Instead the programmer creates the object car as follows:
   car = Car( Point( 120, 60 ), Point( 20, 20 ) )


Make this modification and run your program. What happens?
  • Fix the class Car so that the user can specify any point in any order (top-left, bottom-right), or (top-right, bottom-left), or (bottom-left, top-right), and constructor will correctly define the body and the wheels to fit the shape defined by the two points.
  • Oh, by the way, the car is a two-door convertible. Add a door to the car. The door should be a simple rectangle in the middle of the body of the car, between the two wheels. (You may want to sketch the shape of the car on paper and figure out what proportions to use to position the door.)

Random cars going in random directions

  • Make your program create a list of 5 cars.
  • Each car has a random horizontal velocity (dy=0), making it go left, or right. Make dx and dy part of the class, i.e. make these variables member variables of the class Car.
  • Make your program move all 5 cars at the same time, until all the cars have exited the window. As soon as the cars all disappear your program will stop. Think of an efficient way to do this... This is a bit tricky... (But we are at a time in the semester where you can deal with tricky questions... :-)

Fish

This section is reported to Lab 11...

  • See all the fish? Make a note of one of the fish, and get a copy of its file as follows
  getcopy fishxx.gif            (replace xx by the actual number of the fish you want)
  • Write a new graphics program and copy/paste the following code in it:


.

from graphics import *
H = 400
W = 400

def waitForClick( win, message ):
    """ waitForClick: stops the GUI and displays a message.  
    Returns when the user clicks the window. The message is erased."""

    # wait for user to click mouse to start
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
    startMsg.draw( win )    # display message
    win.getMouse()          # wait
    startMsg.undraw()       # erase


def main():
    global H, W
    win = GraphWin( "Fish Tank", W, H )
    waitForClick( win, "click to start" )

    fish = Image( Point( W/2, H/2 ), "fish15.gif" )  # replace 15 by the number of your fish
    fish.draw( win )

    waitForClick( win, "click to end" )
    win.close()

main()

 
.
  • Add a for loop and make the object fish move by dx, dy some fixed number of steps...
  • Create a an new class which is a fish, with its own file name, and its own dx and dy.
  • Create an object issued from the class. Verify that you can make the object move on the screen.
  • Create a school of several fish that move around the screen. The fish may move in opposite directions, but we'll assume that all fish move in the direction of where their head points to!!!
  • Make the fish go up or down, slightly, randomly, as it moves forward...