def Pacman(): def bodyAnimation(): def step(): nonlocal d_ang arc.move(dx, 0) START = arc.getStartAngle() SWEEP = arc.getSweepAngle() if START == abs(d_ang): d_ang *= -1 if SWEEP == SWEEP_ANGLE: d_ang *= -1 arc.setStartAngle(START + d_ang) arc.setSweepAngle(SWEEP - 2 * d_ang) if arc.getX() > gw.getWidth() - d: timer.stop() d_ang = (360 - (SWEEP_ANGLE + START_ANGLE)) / M_STEPS timer = gw.createTimer(step, TIME_STEP) timer.setRepeats(True) timer.start() gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) dx = (gw.getWidth() - d) / N_STEPS arc = GArc(0, 0, d, d, START_ANGLE, SWEEP_ANGLE) arc.setFilled(True) arc.setFillColor('yellow') gw.add(arc, 5, (GWINDOW_HEIGHT / 2) - (d / 2)) bodyAnimation()
def GrayscaleImage(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) image = GImage(IMAGE_FILENAME) gw.add(image, (gw.getWidth() - IMAGE_SEP) / 2 - image.getWidth(), (gw.getHeight() - image.getHeight()) / 2) grayscale = createGrayscaleImage(image) gw.add(grayscale, (gw.getWidth() + IMAGE_SEP) / 2, (gw.getHeight() - image.getHeight()) / 2)
def launch_rocket(): """ Creates an animation of a rocket lifting off into the sky. """ def lift(): """ Timer callback to animate rocket liftoff. """ gs.v -= 0.25 rocket.move(0, gs.v) if rocket.get_y() < -ROCKET_HEIGHT: timer.stop() def create_rocket(): """ Function to create the compound rocket object. Including the core, 1 fin on each side, and a nose cap. Should return the compound object. """ rocket = GCompound() core = create_filled_rect(0, 0, ROCKET_WIDTH, ROCKET_HEIGHT, "oldlace") rocket.add(core, -ROCKET_WIDTH / 2, -ROCKET_HEIGHT) # Add your code below to add more pieces to the rocket! return rocket gw = GWindow(WIDTH, HEIGHT) gs = GState() gs.v = 0 gw.add(create_filled_rect(0, 0, WIDTH, HEIGHT, "dodgerblue")) # sky gw.add( create_filled_rect(0, HEIGHT - GROUND_HEIGHT, WIDTH, GROUND_HEIGHT, "darkgreen")) # ground rocket = create_rocket() gw.add(rocket, WIDTH / 2, HEIGHT - GROUND_HEIGHT) timer = gw.set_interval(lift, 30)
def __init__(self, n): """Creates and displays a Panex puzzle with n levels.""" self._nLevels = n self._frameWidth = 2 * SIDE_MARGIN + 3 * PIECE_WIDTH + 2 * COLUMN_SEP self._frameHeight = (TOP_MARGIN + BOTTOM_MARGIN + (n + 1) * PIECE_HEIGHT + n * PIECE_SEP) GWindow.__init__(self, self._frameWidth, self._frameHeight) self._tk = tkinter._default_root self._tk.protocol("WM_DELETE_WINDOW", self._quitOnClose) self._tk.createcommand("exit", self._quitOnClose) self._initPuzzle() self.reset()
def pyramid(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) for i in range(1, BRICKS_IN_BASE + 1): if i % 2 != 0: n = 0 while i > n: X_1 = ((GWINDOW_WIDTH / 2) - (BRICK_WIDTH / 2)) + ((n / 2) * BRICK_WIDTH) X_2 = ((GWINDOW_WIDTH / 2) - (BRICK_WIDTH / 2)) - ((n / 2) * BRICK_WIDTH) Y = 30 + (i * 10) rect_1 = GRect(X_1, Y, BRICK_WIDTH, BRICK_HEIGHT) rect_2 = GRect(X_2, Y, BRICK_WIDTH, BRICK_HEIGHT) gw.add(rect_1) gw.add(rect_2) n += 2 else: n = 0 while i > n: X_1_1 = ((GWINDOW_WIDTH / 2) - BRICK_WIDTH) + ( (n / 2) * BRICK_WIDTH) X_1_2 = ((GWINDOW_WIDTH / 2) - BRICK_WIDTH) - ( (n / 2) * BRICK_WIDTH) X_2_1 = (GWINDOW_WIDTH / 2) + ((n / 2) * BRICK_WIDTH) X_2_2 = (GWINDOW_WIDTH / 2) - ((n / 2) * BRICK_WIDTH) Y = 30 + (i * 10) rect_1_1 = GRect(X_1_1, Y, BRICK_WIDTH, BRICK_HEIGHT) rect_1_2 = GRect(X_1_2, Y, BRICK_WIDTH, BRICK_HEIGHT) rect_2_1 = GRect(X_2_1, Y, BRICK_WIDTH, BRICK_HEIGHT) rect_2_2 = GRect(X_2_2, Y, BRICK_WIDTH, BRICK_HEIGHT) gw.add(rect_1_1) gw.add(rect_1_2) gw.add(rect_2_1) gw.add(rect_2_2) n += 2
def Enigma(): def mousedownAction(e): gobj = gw.getElementAt(e.getX(), e.getY()) if gobj is not None: if getattr(gobj, "mousedownAction", None) is not None: gobj.mousedownAction(enigma) def mouseupAction(e): gobj = gw.getElementAt(e.getX(), e.getY()) if gobj is not None: if getattr(gobj, "mouseupAction", None) is not None: gobj.mouseupAction(enigma) def clickAction(e): gobj = gw.getElementAt(e.getX(), e.getY()) if gobj is not None: if getattr(gobj, "clickAction", None) is not None: gobj.clickAction(enigma) gw = GWindow(ENIGMA_WIDTH, ENIGMA_HEIGHT) enigma = EnigmaMachine(gw) gw.addEventListener("mousedown", mousedownAction) gw.addEventListener("mouseup", mouseupAction) gw.addEventListener("click", clickAction)
def CreateMaze2(): g = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) maze = Maze(MAZE_ROWS, MAZE_COLS, SQUARE_SIZE) x = (g.getWidth() - maze.getWidth()) / 2 y = (g.getHeight() - maze.getHeight()) / 2 #createRandomMaze(maze) #g.add(maze, x, y) #g.setInterval(g.add(wall.setColor("Black")), 2000) walls = maze.getWalls() random.shuffle(walls) squares = maze.getSquares() for square in squares: square.setColor(randomColor()) for wall in walls: updateMaze(maze, wall, g)
def image_shop(): def add_button(label, action): """ Adds a button to the region on the left side of the window label is the text that will be displayed on the button and action is the callback function that will be run when the button is clicked. """ x = BUTTON_MARGIN y = gs.next_button_y button = GButton(label, action) button.set_size(BUTTON_WIDTH, BUTTON_HEIGHT) gw.add(button, x, y) gs.next_button_y += BUTTON_HEIGHT + BUTTON_MARGIN def set_image(image): """ Sets image as the current image after removing the old one. """ if gs.current_image is not None: gw.remove(gs.current_image) gs.current_image = image x = BUTTON_AREA_WIDTH + (IMAGE_AREA_WIDTH - image.get_width()) / 2 y = (gw.get_height() - image.get_height()) / 2 gw.add(image, x, y) def load_button_action(): """Callback function for the Load button""" filename = choose_input_file() if filename != "": set_image(GImage(filename)) def flip_vertical_action(): """Callback function for the Flip Vertical button""" if gs.current_image is not None: set_image(flip_vertical(gs.current_image)) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) gs = GState() button_area = GRect(0, 0, BUTTON_AREA_WIDTH, GWINDOW_HEIGHT) button_area.set_filled(True) button_area.set_color(BUTTON_BACKGROUND) gw.add(button_area) gs.next_button_y = BUTTON_MARGIN gs.current_image = None add_button("Load", load_button_action) add_button("Flip Vertical", flip_vertical_action)
def DrawArtsakhFlag(): gw = GWindow(WINDOW_WIDTH, WINDOW_HEIGHT) gw.add(createRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT//3, "red")) gw.add(createRect(0, WINDOW_HEIGHT//3, WINDOW_WIDTH, WINDOW_HEIGHT//3, "blue")) gw.add(createRect(0, 2*WINDOW_HEIGHT//3, WINDOW_WIDTH, WINDOW_HEIGHT//3, "yellow")) for i in range(5): gw.add(createRect(, 0, WINDOW_WIDTH, WINDOW_HEIGHT//3, "red"))
def redCross(): def createRedCross(w, h): cross = GCompound() rect_1 = GRect(-w / 2, -h / 2, LONG_SIDE, SHORT_SIDE) rect_1.setFilled(True) rect_1.setColor('red') cross.add(rect_1) rect_2 = GRect(-h / 2, -w / 2, SHORT_SIDE, LONG_SIDE) rect_2.setFilled(True) rect_2.setColor('red') cross.add(rect_2) return cross def step(): nonlocal cross, theta cross.movePolar(VELOCITY, theta) def clickAction(e): nonlocal theta if cross.contains(e.getX(), e.getY()): theta = random.uniform(0,360) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) theta = random.uniform(0,360) cross = createRedCross(LONG_SIDE, SHORT_SIDE) gw.add(cross, GWINDOW_WIDTH / 2, GWINDOW_HEIGHT / 2) gw.addEventListener('click', clickAction) timer = gw.createTimer(step, TIME_STEP) timer.setRepeats(True) timer.start()
def create_picture(): """ Add your code to replicate the desired image in the space below. I've started you off with a window. """ GW_WIDTH = 400 GW_HEIGHT = 600 gw = GWindow(GW_WIDTH, GW_HEIGHT)
def DrawMaldivesFlag(): sun_radius = WINDOW_HEIGHT//5 gw = GWindow(WINDOW_WIDTH, WINDOW_HEIGHT) gw.add(createBackground("Crimson")) rect = GRect(WINDOW_WIDTH//8, WINDOW_HEIGHT//8, 3*WINDOW_WIDTH//4, 3*WINDOW_HEIGHT//4) rect.setColor("darkgreen") rect.setFilled(True) gw.add(rect) gw.add(createSun("white")) circ=GOval(WINDOW_WIDTH//2 - (sun_radius-20), WINDOW_HEIGHT//2-(sun_radius), sun_radius*2, sun_radius*2) circ.setColor("darkgreen") circ.setFilled(True) gw.add(circ)
def CreateMaze(): g = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) maze = Maze(MAZE_ROWS, MAZE_COLS, SQUARE_SIZE) x = (g.getWidth() - maze.getWidth()) / 2 y = (g.getHeight() - maze.getHeight()) / 2 createRandomMaze(maze) g.add(maze, x, y)
def sudoku_builder(): def mousedown_action(e): element = gw.getElementAt(e.getX(), e.getY()) element.mousedown(e.getX(), e.getY()) def mouseup_action(e): element = gw.getElementAt(e.getX(), e.getY()) element.mouseup(e.getX(), e.getY()) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) gw.addEventListener("mousedown", mousedown_action) gw.addEventListener("mouseup", mouseup_action) board = YoudokuBoard() gw.add(board, 0, 0)
def draw_hexagon(): """ Draws a hexagon at the center of the graphics window. """ gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) gw.add(create_hexagon(HEXAGON_SIDE), gw.get_width() / 2, gw.get_height() / 2)
def tester(): sideLen = 100 print( "How many sides do you want your regular polygon to have? Enter a positive integer." ) iPut = int(input()) gw = GWindow(sideLen * 3, sideLen * 3) gr = GRegularPolygon(iPut, 30) gw.add(gr, gw.getWidth() / 2, gw.getHeight() / 2)
def background(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) rect = GRect(-10, -10, 720, 520) rect.setColor("cyan") rect.setFilled(True) gw.add(rect) for i in range(8): arc = GOval(-100, 100 + 30 * i, 900, 500) arc.setFilled(True) arc.setColor(colors[i]) gw.add(arc)
def DrawLines(): def mousedownAction(e): nonlocal line line = GLine(e.getX(), e.getY(), e.getX(), e.getY()) gw.add(line) def dragAction(e): line.setEndPoint(e.getX(), e.getY()) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) line = None gw.addEventListener('mousedown', mousedownAction) gw.addEventListener('drag', dragAction)
def DrawBangladeshFlag(): gw = GWindow(WINDOW_WIDTH, WINDOW_HEIGHT) rect = GRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) rect.setFilled(True) rect.setColor("ForestGreen") gw.add(rect) circ = GOval(200, 100, 200, 200) circ.setFilled(True) circ.setColor("DarkRed") gw.add(circ)
def ArpanetSimulation(): def clickAction(e): nodeList = [] obj = gw.getElementAt(e.getX(), e.getY()) if isinstance(obj, ArpanetNode): nodeList = [obj] elif isinstance(obj, GLine): active = obj.getColor() == "Black" start = obj.getStartPoint() end = obj.getEndPoint() n1 = gw.getElementAt(start.getX(), start.getY()) n2 = gw.getElementAt(end.getX(), end.getY()) if active: obj.setColor("LightGray") n1.removeNeighbor(n2) n2.removeNeighbor(n1) else: obj.setColor("Black") n1.addNeighbor(n2) n2.addNeighbor(n1) elif obj == allButton: nodeList = arpanet.getNodes() elif isinstance(obj, GLabel): node = arpanet.findNode(obj.getLabel()) name = node.getName() if node.isActive(): node.setActive(False) obj.setColor("LightGray") node.setRoutingTable(RoutingTable(name)) monitors[name].update() else: node.setActive(True) obj.setColor("Black") monitors[name].update() for node in nodeList: name = node.getName() myTable = node.getRoutingTable() if node.isActive(): for neighbor in node.getNeighbors(): if neighbor.isActive(): neighbor.getRoutingTable().update(name, myTable) for name in monitors: monitors[name].update() gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) arpanet = createArpanetGraph(gw) monitors = createArpanetMonitors(gw, arpanet) allButton = GLabel("Update All") allButton.setFont(ALL_BUTTON_FONT) gw.add(allButton, ALL_BUTTON_X, ALL_BUTTON_Y) gw.addEventListener("click", clickAction)
def clickAction(e): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) x0 = (GWINDOW_WIDTH - N_COL * BOX_SIZE) / 2 y0 = (GWINDOW_HEIGHT - N_ROW * BOX_SIZE) / 2 for row in range(N_ROW): for col in range(N_COL): x = x0 + col * BOX_SIZE y = y0 + row * BOX_SIZE box = GRect(x, y, BOX_SIZE, BOX_SIZE) gw.add(box) gw.addEventListener('click', clickAction)
def play_game(): """Plays the clicky box game.""" def click_callback(event): """Callback on mouse click event.""" x = event.get_x() y = event.get_y() if target.contains(x, y): target.set_location(randint(0, WIDTH - BOX_SIZE), randint(0, HEIGHT - BOX_SIZE)) target.set_color(rand_color()) gw = GWindow(WIDTH, HEIGHT) target = create_filled_rect(WIDTH / 2 - BOX_SIZE / 2, HEIGHT / 2 - BOX_SIZE / 2, BOX_SIZE, BOX_SIZE) gw.add(target) gw.add_event_listener("mousedown", click_callback)
def estimate_pi(tries): """ Uses random dart throws at a circular target to approximate the value of pi. As the number of throws gets large, pi should be approximately 4 times the fraction of throws that hit the circle. """ def take_shot(): """ Simulates a random "throw" toward the target, and draws a circle of the correct color depending on if the throw struck the target or not. """ x = random.random() * size y = random.random() * size is_hit = (x - radius)**2 + (y - radius)**2 < radius if is_hit: color = "red" n_hits += 1 else: color = "black" gw.add(create_filled_circle(x, y, 1, color)) size = 500 radius = size / 2 # Creates the window and adds the circular target gw = GWindow(size, size) gw.add(create_filled_circle(radius, radius, radius, "blue")) # Simulate tries number of throws num_hits = 0 for i in range(tries): take_shot() # Compute pi pi = num_hits / tries * 4 # Display the rounded value of pi centered pretty in window lab = GLabel(str(round(pi, 2))) lab.set_font("bold 100px 'serif'") lab.set_color("white") x = size / 2 - lab.get_width() / 2 y = size / 2 - lab.get_ascent() / 2 gw.add(lab, x, y)
def DrawRectangles(): def mousedownAction(e): nonlocal rect, x0, y0 x0 = e.getX() y0 = e.getY() rect = GRect(x0, y0, 0, 0) rect.setFilled(True) gw.add(rect) def dragAction(e): x = min(e.getX(), x0) y = min(e.getY(), y0) rect.setBounds(x, y, abs(e.getX() - x0), abs(e.getY() - y0)) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) rect = None x0 = None y0 = None gw.addEventListener('mousedown', mousedownAction) gw.addEventListener('drag', dragAction)
def SpellingBee(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) puzzle = choice( ) #choice() is the function that checks whether you want to input the puzzle or generate it beehive = createBeehive(puzzle) gw.add( beehive, BEEHIVE_X, BEEHIVE_Y) #adding the puzzle in beehive form on the graphics window displayPuzzleWordList( gw, createWordList(puzzle), puzzle ) #I created a bigger function than displayWordList to use puzzle without nonlocal declaration shuffler = input("Type Shuffle to shuffle the outer hexes: " ) #Code to initiate shuffler starts while shuffler == "Shuffle": puzzle = Shuffle(puzzle) beehive = createBeehive(puzzle) gw.add(beehive, BEEHIVE_X, BEEHIVE_Y) print("Type anything other than Shuffle to stop") shuffler = input("Type Shuffle to shuffle the outer hexes: ")
def fireworks(): def step(): nonlocal dx, dy, dot, x, y, timer_2 if dot.getY() < y: timer.stop() timer_2.start() dot.move(dx, dy) def animateDot(): nonlocal current_size, desired_size if current_size < desired_size: current_size += DELTA_RADIUS x = dot.getX() - DELTA_RADIUS / 2 y = dot.getY() - DELTA_RADIUS / 2 dot.setBounds(x, y, current_size, current_size) random.seed() colors = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet'] gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) dot = GOval((GWINDOW_WIDTH - START_SIZE) / 2, GWINDOW_HEIGHT, START_SIZE, START_SIZE) dot.setColor(random.choice(colors)) gw.add(dot) y = random.uniform(0, GWINDOW_HEIGHT / 2) x = random.uniform(0, GWINDOW_WIDTH) dy = (y - dot.getY()) / FLIGHT_TIME dx = (x - dot.getX()) / FLIGHT_TIME current_size = START_SIZE desired_size = DELTA_RADIUS * EXPANSION_TIME timer = gw.createTimer(step, FLIGHT_TIME) timer.setRepeats(True) timer.start() timer_2 = gw.createTimer(animateDot, EXPANSION_TIME) timer_2.setRepeats(True)
def ImageShop(classifier_file): def addButton(label, action): """ Adds a button to the region on the left side of the window """ nonlocal nextButtonY x = BUTTON_MARGIN y = nextButtonY button = GButton(label, action) button.setSize(BUTTON_WIDTH, BUTTON_HEIGHT) gw.add(button, x, y) nextButtonY += BUTTON_HEIGHT + BUTTON_MARGIN def setImage(image): """ Sets image as the current image after removing the old one. """ nonlocal currentImage if currentImage is not None: gw.remove(currentImage) currentImage = image x = BUTTON_AREA_WIDTH + (IMAGE_AREA_WIDTH - image.getWidth() * image.sf) / 2 y = (gw.getHeight() - image.getHeight() * image.sf) / 2 gw.add(image, x, y) def setThermometer(percentage): if percentage > 0.50: showYes() else: showNo() likelihood.setSize(BUTTON_AREA_WIDTH-10, percentage * (GWINDOW_HEIGHT-nextButtonY-5)) def loadButtonAction(): """Callback function for the Load button""" nonlocal currentFile filename = chooseInputFile() currentFile = filename if filename != "": img = GImage(filename) width = len(img.getPixelArray()) height = len(img.getPixelArray()[0]) max_dim = max(width, height) sf = 750 / max_dim if max_dim > 750: img.scale(sf) setImage(img) clearMessage() def flipVerticalAction(): """Callback function for the FlipVertical button""" if currentImage is not None: setImage(flipVertical(currentImage)) def flipHorizontalAction(): """Callback function for the FlipHorizontal button""" if currentImage is not None: setImage(flipHorizontal(currentImage)) def rotateLeftAction(): """Callback function for the RotateLeft button""" if currentImage is not None: setImage(rotateLeft(currentImage)) def rotateRightAction(): """Callback function for the RotateRight button""" if currentImage is not None: setImage(rotateRight(currentImage)) def isZebraAction(): """Callback function for the Is It a Zebra? button""" if currentFile is not None: zebra_prob = classifier(currentFile)['zebra'] setThermometer(zebra_prob) def showYes(): clearMessage() gw.add(yes, BUTTON_AREA_WIDTH//2-30, GWINDOW_HEIGHT-nextButtonY//2-150) def showNo(): clearMessage() gw.add(no, BUTTON_AREA_WIDTH//2-20, GWINDOW_HEIGHT-nextButtonY//2-150) def clearMessage(): gw.remove(yes) gw.remove(no) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) buttonArea = GRect(0, 0, BUTTON_AREA_WIDTH, GWINDOW_HEIGHT) buttonArea.setFilled(True) buttonArea.setColor(BUTTON_BACKGROUND) gw.add(buttonArea) nextButtonY = BUTTON_MARGIN currentImage = None currentFile = None addButton("Load", loadButtonAction) addButton("Flip Vertical", flipVerticalAction) addButton("Flip Horizontal", flipHorizontalAction) addButton("Rotate Left", rotateLeftAction) addButton("Rotate Right", rotateRightAction) addButton("Is It a Zebra?", isZebraAction) thermometer = GRect(5, nextButtonY, BUTTON_AREA_WIDTH-10, GWINDOW_HEIGHT-nextButtonY-5) thermometer.setFilled(True) thermometer.setColor("red") likelihood = GRect(5, nextButtonY, BUTTON_AREA_WIDTH-10, 0) likelihood.setFilled(True) likelihood.setColor("green") gw.add(thermometer) gw.add(likelihood) yes = GLabel("YES") yes.setColor("white") yes.setFont("bold 36px 'Monaco','Monospaced'") no = GLabel("NO") no.setColor("white") no.setFont("bold 36px 'Monaco','Monospaced'") from cnn import Classifier classifier = Classifier.load(classifier_file)
def ImageShop(): def addButton(label, action): """ Adds a button to the region on the left side of the window """ nonlocal nextButtonY x = BUTTON_MARGIN y = nextButtonY button = GButton(label, action) button.setSize(BUTTON_WIDTH, BUTTON_HEIGHT) gw.add(button, x, y) nextButtonY += BUTTON_HEIGHT + BUTTON_MARGIN def setImage(image): """ Sets image as the current image after removing the old one. """ nonlocal currentImage if currentImage is not None: gw.remove(currentImage) currentImage = image x = BUTTON_AREA_WIDTH + (IMAGE_AREA_WIDTH - image.getWidth()) / 2 y = (gw.getHeight() - image.getHeight()) / 2 gw.add(image, x, y) def loadButtonAction(): """Callback function for the Load button""" filename = chooseInputFile() if filename != "": setImage(GImage(filename)) def flipVerticalAction(): """Callback function for the FlipVertical button""" if currentImage is not None: setImage(flipVertical(currentImage)) def flipHorizontalAction(): """Callback function for the FlipHorizontal button""" if currentImage is not None: setImage(flipHorizontal(currentImage)) def rotateRightAction(): """Callback function for the RotateRight button""" if currentImage is not None: setImage(rotateRight(currentImage)) def rotateLeftAction(): """Callback function for the RotateLeft button""" if currentImage is not None: setImage(rotateLeft(currentImage)) def grayscaleAction(): """Callback function for the grayscale button""" if currentImage is not None: setImage(createGrayscaleImage(currentImage)) def greenScreenAction(): """Callback function for the GreenScreen button""" if currentImage is not None: setImage(greenScreen(currentImage)) def equalizeAction(): """Callback function for the Equalize button""" if currentImage is not None: setImage(equalize(currentImage)) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) buttonArea = GRect(0, 0, BUTTON_AREA_WIDTH, GWINDOW_HEIGHT) buttonArea.setFilled(True) buttonArea.setColor(BUTTON_BACKGROUND) gw.add(buttonArea) nextButtonY = BUTTON_MARGIN currentImage = None #Add buttons addButton("Load", loadButtonAction) addButton("Flip Vertical", flipVerticalAction) addButton("Flip Horizontal", flipHorizontalAction) addButton("Rotate Right", rotateRightAction) addButton("Rotate Left", rotateLeftAction) addButton("Grayscale", grayscaleAction) addButton("Green Screen", greenScreenAction) addButton("Equalize", equalizeAction)
def Swirl(): gw = GWindow(GW_WIDTH,GW_HEIGHT) allFlowers=[] theta=0 steps=0 angleNumber=4 diamondAngle=THETA[3] limChanger=0 stepChanger=10 angularOffset=(.5*diamondAngle) aOchanger=0 def setUp():#sets up scene nonlocal allFlowers,theta,diamondAngle,angularOffset lim=GW_WIDTH*2 while(lim>=1): flower=drawFlowerz(lim,theta,diamondAngle) gw.add(flower,MIDX,MIDY) theta+= angularOffset lim= changeLim(lim) allFlowers.append(flower) def changeDiamondAngle():#changes the number of diamonds, or the number of colors nonlocal diamondAngle,angleNumber,angularOffset angleNumber+=1 if angleNumber>len(THETA)-1: angleNumber=0 diamondAngle=THETA[angleNumber] angularOffset=(.5*diamondAngle) def click(e): buttonPressed=gw2.getElementAt(e.getX(),e.getY()) if buttonPressed==changeAngleButton: changeDiamondAngle() if buttonPressed==changeSpaceOffsetButton: changeSpace() if buttonPressed==changeAngularOffsetButton: changeAngularOff() def changeAngularOff():#changes angular offset of each flower with respect to the previous nonlocal diamondAngle,angularOffset,aOchanger aOchanger+=1 if aOchanger>2: aOchanger=0 if aOchanger==0: angularOffset=(.5*diamondAngle) if aOchanger==1: angularOffset=(.75*diamondAngle) if aOchanger==2: angularOffset=(2*diamondAngle) def step(): nonlocal allFlowers,theta,steps,diamondAngle,stepChanger,angularOffset for i in allFlowers: gw.remove(i) allFlowers.clear() lim=GW_WIDTH*2 steps+=stepChanger theta=0+(steps) while(lim>=1): flower=drawFlowerz(lim,theta,diamondAngle) gw.add(flower,MIDX,MIDY) theta+= angularOffset lim= changeLim(lim) allFlowers.append(flower) def changeSpace(): nonlocal limChanger limChanger+=1 def changeLim(lim): #changes space offset between each flower nonlocal limChanger,stepChanger if limChanger>=4: limChanger=0 if limChanger==0: stepChanger=10 return ((.5* lim)/cos((radians(.5*diamondAngle)))) if limChanger==1: stepChanger=30 return lim-60 if limChanger==2: stepChanger=20 return lim-100 if limChanger==3: stepChanger=40 return lim-40 setUp() gw2=GWindow(GW_WIDTH,100) gw.setInterval(step,TIME_STEP) gw2.addEventListener("click",click) space=gw2.getWidth()//4 changeAngleButton=createButton("Change Number of Colors") #changes the number of diamonds changeSpaceOffsetButton=createButton("Change Space Offset")#changes the space between each flower changeAngularOffsetButton=createButton("Change Angular Offset")#changes offset of each flower with respect to the previous gw2.add(changeAngleButton,space,gw2.getHeight()//2) gw2.add(changeSpaceOffsetButton,space*2,gw2.getHeight()//2) gw2.add(changeAngularOffsetButton,space*3,gw2.getHeight()//2)
return drawTriangle(size) else: gc = GCompound() s = (size / (2 * sqrt(3))) sx = s * cos(radians(30)) sy = s * sin(radians(30)) gc.add(createSierpinskiTriangle(size / 2, order - 1), 0, -s) gc.add(createSierpinskiTriangle(size / 2, order - 1), sx, sy) gc.add(createSierpinskiTriangle(size / 2, order - 1), -sx, sy) return gc #draws a triangle of the given size def drawTriangle(size): t = GPolygon() t.addVertex(0, -(size / (2 * sqrt(3)))) t.addPolarEdge(size, 300) t.addPolarEdge(size, 180) return t #makes a sierpinski triangle to the order of the input of the user #Note that things get a bit dense for orders higher than 10, may want to adjust window size for higher orders to avoid window crashes if __name__ == "__main__": print( "What order sierpinski triangle would you like? Please enter a positive integer." ) order = int(input()) gw = GWindow(500, 500) gw.add(createSierpinskiTriangle(300, order), 250, 250)