CSC111 Lab 11 2014

From dftwiki3
Revision as of 14:49, 15 April 2014 by Thiebaut (talk | contribs)
Jump to: navigation, search

--D. Thiebaut (talk) 17:42, 13 April 2014 (EDT)


Download

Simple Test

from graphicsH import GraphicsWindow

MAXWIDTH = 800
MAXHEIGHT = 600


def main():
    win = GraphicsWindow(MAXWIDTH, MAXHEIGHT)
    canvas = win.canvas()

    canvas.setFill( 255, 0, 0  )    # full red
    canvas.drawRect( 100, 100, 300, 200 )

    win.wait()

main()

Improve on it

  • Try with different colors by picking a different combination of the three ints in setFill()
  • Try a random color. Hints: to generate a random number between 0 and 255, you can do this:
# at the top of the program
from random import seed
from random import randrange

def main():
    seed()
    ...
    x = randrange( 256 ):

Challenge

Generate 500 random rects of random colors at random locations

Draw circles

Create a Rectangle Class

from graphics import GraphicsWindow
from random   import randrange
from random   import seed
from time     import sleep

MAXWIDTH = 800
MAXHEIGHT= 600


class Rectangle:
    def __init__( self, x, y, width, height, color ):
        self._x      = x
        self._y      = y
        self._width  = width
        self._height = height
        self._color  = color   # list of 3 ints between 0 and 255

    def draw( self, canvas ):
        canvas.setFill( self._color[0], self._color[1], self._color[2] )            
        canvas.drawRect( self._x, self._y, self._width, self._height )

def twoRects( canvas ):
    rect1 = Rectangle( 100, 100, 500, 20, (255, 0, 0 ) )
    rect1.draw( canvas )
    
    rect2 = Rectangle( 200, 200, 50, 200, (165, 76, 89 ) )
    rect2.draw( canvas )

def fiveHundredRects( canvas ):
    for i in range( 500 ):
        x = randrange( MAXWIDTH*3//4 )
        y = randrange( MAXHEIGHT *3//4 )
        w = randrange( MAXWIDTH // 2 )
        h = randrange( MAXHEIGHT // 2 )
        red   = randrange( 256 )
        green = randrange( 256 )
        blue  = randrange( 256 )
        rect = Rectangle( x, y, w, h, (red, green, blue ) )
        rect.draw( canvas )
        
            
def main():
    seed()
    win = GraphicsWindow(MAXWIDTH, MAXHEIGHT)
    canvas = win.canvas()

    #twoRects( canvas )

    fiveHundredRects( canvas )

    win.wait()
    win.close()    
    
        
main()