2016-09-25 95 views
0

所以,首先,這裏的要求:從選項列表(Python Turtle Graphics)一次繪製多個形狀?

  1. 用戶選取從清單6 3點的形狀;
  2. 用戶選擇大小,填充顏色和線條顏色;
  3. 用戶不能選擇相同形狀的兩倍
  4. 形狀應繪製間隔均勻,佔用了屏幕的1/3每個

這裏是我到目前爲止的代碼:

import turtle 
turtle = turtle.Screen() 

def circle(): 
def triangle(): 
def square(): 
def pentagon(): 
def hexagon(): 
def heptagon(): 

for list in ["1.Circle","2.Triangle","3.Square","4.Pentagon","5.Hexagon","6.Heptagon"]: 
    print(list) 
shape1 = input("Choose one number from the following:") 

if shape1 == "1": 
    for list in ["2.Triangle","3.Square","4.Pentagon","5.Hexagon","6.Heptagon"]: 
     print(list) 
    shape2 = input("Choose one number from the following:") 
    if shape2 == "2": 
    elif shape2 == "3": 
    elif shape2 == "4": 
    elif shape2 == "5": 
    elif shape2 == "6": 
    else: 
     print("Incorrect input. Please try again.") 
if shape1 == "2": 
if shape1 == "3": 
if shape1 == "4": 
if shape1 == "5": 
if shape1 == "6": 
else: 
    print("Incorrect input. Please try again.") 

基本上,我非常困惑。我可以發現在用戶選擇的行中繪製三種形狀的唯一方法就是盡一切可能的結果 - 123,124,125,126,132,134等等,這將永遠消失,看起來很可怕,而且那麼我將不得不每次都編寫turtle命令。正如你所看到的,我嘗試過使用def,但是在我的小測試代碼中它根本不起作用,所以我也不確定我是否正確理解它。

除了所有這些,我將如何確保所有的形狀或他們應該在哪裏?我能看到的唯一方法是用不同的「goto」爲每個結果編寫單獨的代碼。

有沒有辦法讓用戶一次把所有三個選項(「123」,「231」等),然後讓程序遍歷每個數字並依次繪製它?有沒有辦法將每個數字分配給一組繪製形狀的代碼?所有這些我都很新。我很感激你能給我的任何幫助。謝謝!

回答

0

下面是一個示例框架,用於從(縮小)形狀列表中提示用戶,劃分畫布並繪製它們。它只實現的圈子,則需要填寫其他形狀,以及它與完成的代碼是遠,你需要添加錯誤檢查和其他收尾:

import turtle 

CANVAS_WIDTH = 900 
CANVAS_HEIGHT = 600 
CHROME_WIDTH = 30 # allow for window borders, title bar, etc. 
SHAPE_CHOICES = 3 

def circle(bounds): 
    turtle.penup() 
    center_x = bounds['x'] + bounds['width'] // 2 
    bottom_y = bounds['y'] 
    turtle.setposition(center_x, bottom_y) 
    turtle.pendown() 

    turtle.circle(min(bounds['width'], bounds['height']) // 2) 

def triangle(bounds): 
    circle(bounds) 

def square(bounds): 
    circle(bounds) 

def pentagon(bounds): 
    circle(bounds) 

def hexagon(bounds): 
    circle(bounds) 

def heptagon(bounds): 
    circle(bounds) 

DESCRIPTION, FUNCTION = 0, 1 

shapes = [("Circle", circle), ("Triangle", triangle), ("Square", square), ("Hexagon", hexagon), ("Heptagon", heptagon)] 

choices = [] 

turtle.setup(CANVAS_WIDTH + CHROME_WIDTH, CANVAS_HEIGHT + CHROME_WIDTH) 

for _ in range(SHAPE_CHOICES): 

    for i, (description, function) in enumerate(shapes): 
      print("{}. {}".format(i + 1, description)) 

    choice = int(input("Choose one number from the above: ")) - 1 

    choices.append(shapes[choice][FUNCTION]) 

    del shapes[choice] 

x, y = -CANVAS_WIDTH // 2, -CANVAS_HEIGHT // 2 

width, height = CANVAS_WIDTH // SHAPE_CHOICES, CANVAS_HEIGHT // SHAPE_CHOICES 

# I'm dividing the screen into thirds both horizontally and vertically 
bounds = dict(x=x, y=y, width=width, height=height) 

for choice in choices: 
    choice(bounds) 

    bounds['x'] += width 
    bounds['y'] += height 

turtle.done() 
+0

你的救星,謝謝。這有很大幫助。 – Seren