Запутанный Python нужны решения - PullRequest
0 голосов
/ 30 апреля 2020

Мне дали задание, которое гласит: Ваш код должен создать графическое окно Python черепаха и нарисовать в нем как минимум пять названных прямоугольников. Если щелкнуть мышью в прямоугольнике, ваш код должен напечатать имя прямоугольника с помощью функции Python print (). Если щелкнуть мышью, но не внутри какого-либо прямоугольника, ваш код должен напечатать строку «без нажатия».

Начните с указания ваших прямоугольников в качестве членов списка с именем прямоугольники. Данные для каждого прямоугольника будут представлять собой список, содержащий следующие данные:

[name, bottomLeftX, bottomLeftY, width, height, outlineWidth, color] Когда ваше окно откроется, оно должно go пройти через список прямоугольников и нарисуйте их все в окне.

Мой вопрос по этому поводу: как мне создать функцию, которая будет рисовать прямоугольники в функции черепахи из списка, который я создал? Вот где я сейчас нахожусь в своем назначении, и я совершенно тупик:

import sys, turtle as t

# window width and height
wnWidth = 800
wnHeight = 800


# code that sets up the turtle graphics window
def setup():
    t.title('CS 160 - Assignment 4 - I. Forgot')

    t.setup(wnWidth, wnHeight, 0, 0)  # window size, turtle initial position

    # set window coordinates of bottom-left corner to 0,0
    t.setworldcoordinates(0, 0, wnWidth, wnHeight)

    t.bgcolor('burlywood1')


# list of rectangles
# each rectangle: [name, bottomLeftX, bottomLeftY, width, height, penWidth, color]
class Rectangle:
    def __init__(self, name, botLeftX, botLeftY, width, height, penWidth, color):
        self.name =         name
        self.botLeftX =     botLeftX
        self.botLeftY =     botLeftY
        self.width =        width
        self.height =       height
        self.penWidth =     penWidth
        self.color =        color

rectangles = [Rectangle('Rect1', 150, 150, 75, 50, 4, 'red'),
              Rectangle('rect 2', 510, 650, 80, 55, 3, 'deep sky blue'),
              Rectangle('rect 3', 375, 95, 100, 75, 5, 'orange'),
              Rectangle('rect 4', 220, 460, 65, 50, 4, 'cyan'),
              Rectangle('rect 5', 310, 715, 75, 50, 4, 'gold')]





for rect in rectangles:
    print(rect.name, rect.botLeftX, rect.botLeftY, rect.width, rect.height, rect.penWidth, rect.color)



a = ["rect 1", 150, 150, 75, 50, 4, 'red']
b = ["rect 2", 510, 650, 80, 55, 3, 'deep sky blue']
c = ["rect 3", 375, 95, 100, 75, 5, 'orange']
d = ["rect 4", 220, 460, 65, 50, 4, 'cyan']
e = ["rect 5", 310, 715, 75, 50, 4, 'gold']
rectangles = [a, b, c, d, e]






def drawRects():
    pass


def drawRect():
    pass

# return True if x,y is within rectangle
def inside(x, y, rect):
    return False


# called when screen is clicked
def screenClickFn(x, y):
    # Replace this print statement with code that figures out whether
    # a rectangle was hit and if so, prints the name of that rectangle.
    # If no rectangle was hit, print "no hit".
    print(f'x = {int(x):3}, y = {int(y):3}')


# window closes and app exits when Escape is typed
def quitApp():
    sys.exit()


t.onscreenclick(screenClickFn)  # function to call when screen is clicked

t.listen()
t.onkey(quitApp, 'Escape')  # function to call when Escape is typed

setup()
drawRect()

t.mainloop()
...