2017-10-16 227 views
-1

對於我的任務,我試圖在用戶選擇顏色和方形尺寸時製作5 x 5棋盤格。我知道如何根據用戶輸入製作方形尺寸和顏色,並且在如何啓動循環或如何創建5 x 5棋盤格時遇到了一些問題。我只是不確定我能做些什麼來移動烏龜來製作5x5的紙板。到目前爲止,我已經做了很多工作,如果有人能夠幫助我開始,我會非常感激!Python用戶輸入棋盤

import turtle 

def main(): 
    length = int(input("Enter a desired length (from 1-150.)")) 
    keepGoing = 'y' 

    while keepGoing == 'y': 
     print("What color would you like to draw?") 
     print(" Enter 1 for Black") 
     print("   2 for Blue") 
     print("   3 for Red") 
     print("   4 for Green") 
     choice = int(input("   Your choice?")) 

     if choice == 1: 
      square(0,0,length,'black') 
     elif choice == 2: 
      square(0,0,length,'blue') 
     elif choice == 3: 
      square(0,0,length,'red') 
     elif choice == 4: 
      square(0,0,length,'green') 
     else: 
      print("ERROR: only enter 1-4.") 

def square(x, y, width, color): 
    turtle.clear() 
    turtle.penup()   # Raise the pen 
    turtle.goto(x, y)   # Move to (X,Y) 
    turtle.fillcolor(color) # Set the fill color 
    turtle.pendown()   # Lower the pen 
    turtle.begin_fill()  # Start filling 
    for count in range(4): # Draw a square 
     turtle.forward(width) 
     turtle.left(90) 
    turtle.end_fill() 
#calling main function 
main() 
+0

只需繪製並填充每個方塊。循環所有的方塊,確定它們的位置。然後在每個位置繪製適當顏色的方形。 –

回答

0

首先,您開發的用戶界面沒有任何接口 - 您可能會在下次開始時採用其他方式。其次,不要改造布爾值(例如while keepGoing == 'y')。第三,代碼量就帶你到一平方,我們可以郵票整個網格:

from turtle import Turtle, Screen 

COLORS = ["Black", "Blue", "Red", "Green"] 
GRID = 5 
STAMP_UNIT = 20 

def main(): 
    length = int(input("Enter a desired length (from 1-150): ")) 
    keepGoing = True 

    while keepGoing: 
     print("What color would you like to draw?") 
     for i, color in enumerate(COLORS, start=1): 
      print(" Enter {} for {}".format(i, color)) 
     choice = int(input("   Your choice? ")) 

     if 1 <= choice <= len(COLORS): 
      grid(-length * GRID // 2, -length * GRID // 2, length, COLORS[choice - 1]) 
      keepGoing = False 
     else: 
      print("ERROR: only enter 1-{}.".format(len(COLORS))) 

def grid(x, y, width, color): 
    tortoise = Turtle('square', visible=False) 
    tortoise.shapesize(width/STAMP_UNIT) 
    tortoise.color(color) 
    tortoise.penup() 

    for dy in range(0, GRID): 
     tortoise.goto(x, y + width * dy) 

     for dx in range(dy % 2, GRID, 2): 
      tortoise.setx(x + width * dx) 

      tortoise.stamp() 

screen = Screen() 

main() 

screen.exitonclick() 

用法

> python3 test.py 
Enter a desired length (from 1-150): 30 
What color would you like to draw? 
    Enter 1 for Black 
    Enter 2 for Blue 
    Enter 3 for Red 
    Enter 4 for Green 
      Your choice? 2 

輸出

enter image description here

這是一個完美的例子,衝壓可以使事情變得比繪圖更簡單快速。