OOP Workshop
Version1: Single Shape
The first version of the example can be brought together from the previous examples as follows:
import turtle
import random
import math
turtle.setup(500, 500)
screen = turtle.Screen()
turtle.title("Turtle Keys")
turtle.pensize(3)
colors = ("orange", "pink", "yellow", "green", "blue", "purple", "magenta", "cyan")
class Button:
buttonShape = "Line"
buttonColor = "Orange"
buttonX = 0
buttonY = 0
width = 100
height = 50
def __init__(self, buttonShape, buttonColor, buttonX, buttonY, width, height):
self.buttonShape = buttonShape
self.buttonColor = buttonColor
self.buttonX = buttonX
self.buttonY = buttonY
self.width = width
self.height = height
def drawButtonShape(self, aTurtle):
aTurtle.pensize(20)
aTurtle.penup()
aTurtle.goto(self.buttonX, self.buttonY + 10)
aTurtle.pendown()
aTurtle.forward(self.width)
def drawTheButton(self, aTurtle):
global selectedButton
if (self is selectedButton):
aTurtle.color("Red")
else:
aTurtle.color("Black")
aTurtle.setheading(0)
aTurtle.fillcolor(self.buttonColor)
aTurtle.penup()
aTurtle.goto(self.buttonX, self.buttonY)
aTurtle.pendown()
aTurtle.begin_fill()
self.drawButtonShape(aTurtle) # Potential Polymorphic call to child class
aTurtle.end_fill()
def drawShape(self, x, y, aTurtle):
aTurtle.goto(x, y)
def isClicked(self, x, y):
return self.buttonX < x < self.buttonX + self.width and \
self.buttonY < y < self.buttonY + self.height
def getColor(self):
return self.buttonColor
buttonTurtle = turtle.Turtle()
selectedButton = Button("Line", "Orange", -130, 220, 40, 20)
shapeButtons = []
shapeButtons.append(selectedButton)
def updateButtons():
for i in range(len(shapeButtons)):
shapeButtons[i].drawTheButton(buttonTurtle)
def anyShapeSelected(x, y):
global selectedButton
for i in range(len(shapeButtons)):
shapeB = shapeButtons[i]
if (shapeB.isClicked(x, y)):
print(shapeB.buttonShape, "was clicked")
if (shapeB is selectedButton):
return False
selectedButton = shapeB
return True
return False
drawing = False
def goto_and_do_whatever_required(x, y):
global drawing
if (drawing):
return
if (y > 170):
if (anyShapeSelected(x, y)):
updateButtons()
return
drawing = True
turtle.color(colors[random.randint(0, len(colors) - 1)])
selectedButton.drawShape(x, y, turtle)
drawing = False
screen.onscreenclick(goto_and_do_whatever_required)
updateButtons()
turtle.done()