我目前正在完成大學作業。我們在第一學期一直在使用John Zelle的graphics.py
模塊。需要重構此功能的幫助
任務是構造兩種不同的圖案,然後將它們放置在特定設計中,根據窗口是否爲500 x 500, 700 x 700 or 900 x 900
像素自動調整。
我已經完成了任務,但是,我的代碼的一大部分效率很低,很長,因此這並不理想。
下面是長且效率低下的代碼:
def DrawPattern(width,size,win,colour):
if size == 5:
for x in range(0,width,100):
drawCircleExpanse(win,x,400,colour)
for j in range(100,400,100):
drawCircleExpanse(win,j,300,colour)
drawCircleExpanse(win,200,200,colour)
for j in range(100,400,100):
drawCircleExpanse(win,j,100,colour)
for x in range(0,width,100):
drawCircleExpanse(win,x,0,colour)
if size == 7:
for x in range(0,width,100):
drawCircleExpanse(win,x,width-100,colour)
for j in range(100,width-100,100):
drawCircleExpanse(win,j,width-200,colour)
for i in range(200,width-200,100):
drawCircleExpanse(win,i,width-300,colour)
drawCircleExpanse(win,300,300,colour)
for j in range(100,width-100,100):
drawCircleExpanse(win,j,100,colour)
for x in range(0,width,100):
drawCircleExpanse(win,x,0,colour)
for i in range(200,width-200,100):
drawCircleExpanse(win,i,width-500,colour)
if size == 9:
for x in range(0,width,100):
drawCircleExpanse(win,x,width-100,colour)
for j in range(100,width-100,100):
drawCircleExpanse(win,j,width-200,colour)
for i in range(200,width-200,100):
drawCircleExpanse(win,i,width-300,colour)
for y in range(300,width-300,100):
drawCircleExpanse(win,y,width-400,colour)
drawCircleExpanse(win,400,400,colour)
for j in range(100,width-100,100):
drawCircleExpanse(win,j,100,colour)
for x in range(0,width,100):
drawCircleExpanse(win,x,0,colour)
for i in range(200,width-200,100):
drawCircleExpanse(win,i,width-700,colour)
for y in range(300,width-300,100):
drawCircleExpanse(win,y,width-600,colour)
的size
變量取用戶的輸入;例如5, 7 or 9
。這轉換爲500 x 500, 700 x 700 or 900 x 900
。與colour
類似,它只會將顏色更改爲用戶選擇的顏色之一。
此代碼,將產生以下的圖案,與所述尺寸5
其轉換爲500 x 500
:
的drawCircleExpanse
功能,它構造圖案本身,包含以下代碼:
def drawCircleExpanse(win,x,y,colour):
rad = 50
for c in range(10):
circle = Circle(Point(50+x,(50+(c * 10)/2)+y), rad)
circle.setOutline(colour)
circle.draw(win)
rad -= 5
如果有人能夠幫助縮短我的大量代碼塊,我將不勝感激。
我不確定這種類型的問題是關於這裏的主題。我以前從來沒有問過這個SE,但是也許codereview SE是問這樣一個問題的好地方?在發佈之前,我會仔細檢查那裏的主題指南,但感覺這可能更適合那裏。 – Lexi