Homework Assignment

For Loops and Graphics


Problems to be Submitted (20 points)

  1. (10 points)

    Write a program which generates the following pattern, assuming that numSquares defines the number of squares and unitSize represents the width of each square.

    Solution:

    from cs1graphics import *
    
    numBlocks = 8                         # number of levels
    size = 30                             # the height of one level
    screenSize = size * numBlocks
    paper = Canvas(screenSize, screenSize)
    centerX = screenSize - size/2
    centerY = size/2
    
    # create levels from top to bottom
    for level in range(numBlocks):
        block = Square(size, Point(centerX, centerY))
        block.setFillColor('gray')
        paper.add(block)
    
        centerX -= size
        centerY += size
    

  2. (10 points)

    Write a program which generates the following pattern, assuming that numLevels defines the number of levels and unitSize represents the width of each square.

    Solution:

    from cs1graphics import *
    
    numLevels = 8                             # number of levels
    unitSize = 30                             # the height of one level
    screenSize = unitSize * (1 + numLevels)
    paper = Canvas(screenSize, screenSize)
    
    # create levels from top to bottom
    for level in range(numLevels):
        # all blocks at this level have same y-coordinate
        centerY = unitSize * (numLevels - level)
        leftmostX = unitSize
        for blockCount in range(level + 1):
            block = Square(unitSize)
            block.move(leftmostX + unitSize * blockCount, centerY)
            block.setFillColor('gray')
            paper.add(block)
    


Last modified: Monday, 24 September 2018