[英]Drawing pyramid using recursion
我想使用 cs1graphics 遞歸地創建一個金字塔 class。 這個 class 將允許用戶指定金字塔的層數和總寬度。
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
我不知道如何完成class的rest。
像這樣的東西應該可以工作:在您的初始化中,將所有信息存儲為 class 變量,並調用遞歸 function 來更新當前級別。 當級別達到基本情況時(例如,如果您正在倒計時,則達到 0,或者如果您在此處向上計數,則達到 numLevels)然后停止遞歸。
from cs1graphics import *
class Pyramid(Drawable):
def __init__(self, numLevels, unitSize):
self.numLevels = numLevels
self.currentlevel = 0
self.unitSize = unitSize
self.screenSize = unitSize * (numLevels + 1)
self.paper = Canvas(screenSize, screenSize)
self.centerX = screenSize / 2.0
self.draw_pyramid()
def draw_pyramid(self):
centerY = (self.currentlevel + 1) * self.unitSize
leftmostX = self.centerX - self.unitSize * self.currentlevel / 2.0
for blockCount in range(self.currentlevel + 1):
block = Square(self.unitSize)
block.move(leftmostX + self.unitSize * blockCount, centerY)
block.setFillColor('gray')
self.paper.add(block)
self.currentlevel += 1
if self.currentlevel == self.numLevels:
return
self.draw_pyramid()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.