我想使用cs1graphics递归地创建一个金字塔类。该类允许用户指定金字塔的层数和总宽度
cs1graphics模块:https://github.com/otfried/cs101/blob/master/modules/cs1graphics.py
我可以使用for循环来实现这一点,但我不知道如何使用递归来实现同样的事情
以下是我正在使用的代码:
from cs1graphics import *
numLevels = 8
unitSize = 12
screenSize = unitSize * (numLevels + 1)
paper = Canvas(screenSize, screenSize)
centerX = screenSize / 2.0
for level in range(numLevels):
centerY = (level + 1) * unitSize
leftmostX = centerX - unitSize * level / 2.0
for blockCount in range(level + 1):
block = Square(unitSize)
block.move(leftmostX + unitSize * blockCount, centerY)
block.setFillColor('gray')
paper.add(block)
这是我的尝试:
class Pyramid(Drawable):
def __init__(self, numLevels, unitSize):
screenSize = self.unitSize * (self.numLevels + 1)
paper = Canvas(screenSize, screenSize)
centerX = screenSize / 2.0
我不知道如何完成剩下的课程
像这样的方法应该会奏效: 在init中,将所有信息存储为类变量,并调用更新当前级别的递归函数。当级别达到一个基本情况时(例如,如果你正在倒计时,则达到0;如果你正在倒计时,则达到numLevels),则停止递归
相关问题 更多 >
编程相关推荐