2017-10-16 4 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() 

USAGE

> 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 

OUTPUT

enter image description here

이것은 스탬핑을 사용하여 그림보다 간단하고 빠르 게 만들 수있는 완벽한 예입니다.