Программа «Разноцветные квадраты Python» с использованием вложенных циклов с черепахой - PullRequest
0 голосов
/ 15 февраля 2020

Я пытаюсь создать программу на python, которая рисует столбцы и строки квадратов. Там может быть только 3 строки и 3-12 столбцов. Пользователь должен ввести, сколько столбцов он хочет и какие 3 цвета они хотят, чтобы были строки. Я борюсь с тем, как выровнять ряды друг под другом и как сделать так, чтобы это было в центре экрана. Я также борюсь с тем, как сделать каждый ряд разным цветом. Любые предложения помогут. Спасибо! Это то, что я до сих пор.

import turtle


ROWS = 3
OFFSET = 10
cols = int(input('How many columns to display (3-12)? '))

color1 = input('What is the first color? ')
color2 = input('What is the second color? ')
color3 = input('What is the third color? ')

if cols < 3 or cols > 12:
  print('Error! Number of columns must be in range of 3 to 12.')

elif color1 == color2 or color1 == color3:
  print('Error! All the colors must be different!')
elif color2 == color1 or color2 == color3:
  print('Error! All the colors must be different!')
elif color3 == color1 or color3 == color2:
  print('Error! All the colors must be different!')
else:
  for r in range(ROWS):
    y = turtle.ycor() - 115
    x = turtle.xcor() 
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()
    turtle.fillcolor(color1)
    turtle.begin_fill()
    for c in range(cols):
      x = turtle.xcor() + 95
      y = turtle.ycor()
      turtle.penup()
      turtle.goto(x,y)
      turtle.pendown()
      for side in range(4):
        turtle.forward(50)
        turtle.left(90)
    turtle.end_fill()

Пример того, как это должно выглядеть

1 Ответ

0 голосов
/ 16 февраля 2020

Ваша проверка входных данных нуждается в работе, и, надеюсь, пример ниже поможет с этим. Что касается центрирования на экране, вам нужно сделать код динамическим c, поэтому такие константы, как:

y = turtle.ycor() - 115
x = turtle.xcor() + 95
turtle.forward(50)

не приносят вам пользы. Вам необходимо вычислить эти значения на основе количества столбцов, ширины окна и размера ваших границ и пробелов.

Поскольку вы должны выполнить эту лабораторную работу самостоятельно, я собираюсь предоставить рабочий пример, который не будет вам непосредственно полезен, поскольку он использует штамповка , и ваша проблема, похоже, основана на чертеже . (Разница лишь в том, где находится черепаха, когда она начинает рисовать коробку.) Но вы сможете увидеть вычисления, необходимые для правильного центрирования и выравнивания ваших коробок:

from turtle import Screen, Turtle

ROWS = 3
CURSOR_SIZE = 20  # base unit for cursor resizing

columns = -1

while not 3 <= columns <= 12:
    columns = int(input('How many columns to display (3-12)? '))
    if not 3 <= columns <= 12:
        print('Error! Number of columns must be in range of 3 to 12.')

color = input('What is the first color? ')

colors = [color]

while color in colors:
    color = input('What is the second color? ')
    if color in colors:
        print('Error! All the colors must be different!')

colors.append(color)

while color in colors:
    color = input('What is the third color? ')
    if color in colors:
        print('Error! All the colors must be different!')

colors.append(color)

screen = Screen()

# assumptions: there is a one box size border on each side and
# the gap between boxes, vertical and horizontal, is 1/2 box

# dimensions are based on number of columns and window width
box_size = screen.window_width() / ((columns - 1) * 1.5 + 3)

turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(box_size / CURSOR_SIZE)  # make the turtle our standard box
turtle.penup()

y = box_size * 1.5  # y center of top-most boxes

for row in range(ROWS):
    turtle.fillcolor(colors[row])

    x = -box_size * (columns * 3/4 - 3/4)  # x center of left-most boxes

    turtle.goto(x, y)

    for column in range(columns):

        turtle.stamp()

        x += box_size * 1.5  # move by a box and a gap

        turtle.setx(x)

    y -= box_size * 1.5  # move by a box and a gap

screen.exitonclick()

Обратите внимание, как все пользователи входные данные были исправлены и / или проверены на избыточность до того, как код переместился на поля рисования:

enter image description here

Если вы еще не узнали о массивах, таких как colors тем не менее, вы все равно сможете выполнять проверки и назначения цветов, просто потребуется дополнительный код.

...