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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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)
def SnowmanGame(): def clickAction(e): """ Checks if there is a letter where was clicked and identifies the letter. Counts incorrect guesses and implements game over and resets the screen. """ nonlocal incorrect_guesses, snowman, mystery_word, full_word, word_display, game_over, letters_chosen, timer if e.getY() > GWINDOW_HEIGHT - WORD_BASE and not game_over: pick = gw.getElementAt(e.getX(), e.getY()) if pick is not None: letter = pick.getLabel() if letter in letters_chosen: gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('You already picked that letter!') message.setFont(MESSAGE_FONT) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) else: letters_chosen.append(letter) gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) if letterFound(letter): pick.setColor(CORRECT_COLOR) else: pick.setColor(INCORRECT_COLOR) incorrect_guesses += 1 addSnowmanPart(snowman, incorrect_guesses) else: gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('Click a letter!') message.setFont(MESSAGE_FONT) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) if incorrect_guesses == 8: game_over = True gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('YOU LOSE!') message.setFont(MESSAGE_FONT) message.setColor(INCORRECT_COLOR) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) animateSnowman() elif not game_over: gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('Click a letter!') message.setFont(MESSAGE_FONT) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) elif game_over: timer.stop() gw.clear() full_word = random.choice(SNOWMAN_WORDS) mystery_word = '-' * len(full_word) word_display = GLabel(mystery_word) word_display.setFont(WORD_FONT) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for i in range(len(alphabet)): letter = GLabel(alphabet[i]) letter.setFont(LETTER_FONT) x = ((GWINDOW_WIDTH - len(alphabet) * letter.getWidth()) / (len(alphabet) + 1)) * (1 + i) + i * letter.getWidth() gw.add(letter, x, GWINDOW_HEIGHT - LETTER_BASE) incorrect_guesses = 0 snowman = createEmptySnowman(gw) game_over = False letters_chosen = [] def letterFound(ch): """ Checks if the letter clicked is in the word and replaces dashes with the letter everywhere it appears """ nonlocal full_word, mystery_word, word_display, game_over s = 0 if full_word.find(ch) != -1: while s <= len(full_word): if full_word.find(ch, s) != -1: letter = full_word.find(ch, s) mystery_word = mystery_word[:letter] + ch + mystery_word[ letter + 1:] s += letter + 1 else: s = len(full_word) + 1 gw.remove(word_display) word_display = GLabel(mystery_word) word_display.setFont(WORD_FONT) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) if mystery_word == full_word: message = gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE) gw.remove(message) message = GLabel('YOU WIN!') message.setFont(MESSAGE_FONT) message.setColor(CORRECT_COLOR) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) game_over = True animateMelting() return True def animateSnowman(): """ Moves the snowman menacingly if the game is lost. """ nonlocal timer def step(): nonlocal snowman, dx, dy, full_word if snowman.getX() > (GWINDOW_WIDTH - BASE_SIZE) or snowman.getX() < BASE_SIZE: dx *= -1 gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - WORD_BASE)) word_display = GLabel(full_word) word_display.setFont(WORD_FONT) word_display.setColor(INCORRECT_COLOR) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) elif snowman.getY() < (GWINDOW_HEIGHT - BASE_SIZE - BODY_SIZE - HEAD_SIZE) or snowman.getY() > SNOWMAN_BASE: dy *= -1 snowman.move(dx, dy) x_1 = .5 * EYE_SEP + (1 + .1) * EYE_SIZE y_1 = -BASE_SIZE - BODY_SIZE - HEAD_SIZE + .17 * HEAD_SIZE x_2 = .5 * EYE_SEP y_2 = -BASE_SIZE - BODY_SIZE - HEAD_SIZE + .255 * HEAD_SIZE brow_1 = GLine(-x_1, y_1, -x_2, y_2) brow_2 = GLine(x_1, y_1, x_2, y_2) snowman.add(brow_1) snowman.add(brow_2) TIME_STEP = 70 dx = (GWINDOW_WIDTH - BASE_SIZE) / TIME_STEP dy = (GWINDOW_HEIGHT - BASE_SIZE - BODY_SIZE - HEAD_SIZE) / (TIME_STEP) timer = gw.createTimer(step, TIME_STEP) timer.setRepeats(True) timer.start() def animateMelting(): """ Moves the snowman off-screen if the game is won. """ nonlocal timer def step(): nonlocal snowman, dy snowman.move(0, dy) TIME_STEP = 70 dy = (GWINDOW_HEIGHT + BASE_SIZE + BODY_SIZE + HEAD_SIZE) / TIME_STEP timer = gw.createTimer(step, TIME_STEP) timer.setRepeats(True) timer.start() random.seed() gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) full_word = random.choice(SNOWMAN_WORDS) mystery_word = '-' * len(full_word) word_display = GLabel(mystery_word) word_display.setFont(WORD_FONT) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for i in range(len(alphabet)): letter = GLabel(alphabet[i]) letter.setFont(LETTER_FONT) x = ((GWINDOW_WIDTH - len(alphabet) * letter.getWidth()) / (len(alphabet) + 1)) * (1 + i) + i * letter.getWidth() gw.add(letter, x, GWINDOW_HEIGHT - LETTER_BASE) gw.addEventListener('click', clickAction) incorrect_guesses = 0 snowman = createEmptySnowman(gw) game_over = False letters_chosen = [] timer = None
def Breakout(): """ The main program for the Breakout game. """ def mousemoveAction(e): paddle_X = paddle.getX() dx = e.getX() - paddle_X if 0 <= dx + paddle_X <= GWINDOW_WIDTH - PADDLE_WIDTH: paddle.move(dx, 0) elif 0 > dx + paddle_X: paddle.setLocation(0, PADDLE_Y) else: paddle.setLocation(GWINDOW_WIDTH - PADDLE_WIDTH, PADDLE_Y) def AnimatedBall(): def step(): nonlocal vx, vy, ball, bricks_hit, balls_left, x_text, y_text collider = getCollidingObject() if ball.getX() < 0 or ball.getX() > GWINDOW_WIDTH - BALL_SIZE: vx *= -1 elif ball.getY() < 0: vy *= -1 elif ball.getY() > GWINDOW_HEIGHT - BALL_SIZE: timer.stop() gw.remove(ball) balls_left -= 1 if balls_left > 0: ball = GOval((GWINDOW_WIDTH - BALL_SIZE) / 2, (GWINDOW_HEIGHT - BALL_SIZE) / 2, BALL_SIZE, BALL_SIZE) ball.setFilled(True) gw.add(ball) gw.add(instruct) else: msg = GLabel('You Lose.') msg.setColor('red') msg.setFont('bold 36px sans-serif') x = (GWINDOW_WIDTH - msg.getWidth()) / 2 y = (GWINDOW_HEIGHT - msg.getHeight()) / 2 gw.add(msg, x, y) if collider == paddle: vy *= -1 elif not (collider == paddle or collider == gw.getElementAt( x_text, y_text)) and collider is not None: vy *= -1 gw.remove(collider) bricks_hit += 1 if bricks_hit == N_COLS * N_ROWS: timer.stop() msg = GLabel('You Win!') msg.setColor('green') msg.setFont('bold 36px sans-serif') x = (GWINDOW_WIDTH - msg.getWidth()) / 2 y = (GWINDOW_HEIGHT - msg.getHeight()) / 2 gw.add(msg, x, y) ball.move(vx, vy) gw.remove(gw.getElementAt(x_text, y_text)) lives = GLabel('Lives: ' + str(balls_left)) gw.add(lives, x_text, y_text) vx = random.choice([-1, 1]) * random.uniform(MIN_X_VELOCITY, MAX_X_VELOCITY) vy = INITIAL_Y_VELOCITY x_text = 20 y_text = GWINDOW_HEIGHT - 10 timer = gw.createTimer(step, TIME_STEP) timer.setRepeats(True) timer.start() def clickAction(e): gw.remove(instruct) AnimatedBall() def getCollidingObject(): loc = gw.getElementAt(ball.getX(), ball.getY()) if loc is not None: return loc else: loc = gw.getElementAt(ball.getX() + BALL_SIZE, ball.getY()) if loc is not None: return loc else: loc = gw.getElementAt(ball.getX(), ball.getY() + BALL_SIZE) if loc is not None: return loc else: loc = gw.getElementAt(ball.getX() + BALL_SIZE, ball.getY() + BALL_SIZE) return loc random.seed() gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) colors = [ 'red', 'red', 'orange', 'orange', 'green', 'green', 'cyan', 'cyan', 'blue', 'blue' ] for row in range(N_ROWS): for col in range(N_COLS): rect = GRect( ((GWINDOW_WIDTH - ((N_COLS * (BRICK_WIDTH + BRICK_SEP)) - BRICK_SEP)) / 2) + (row * (BRICK_WIDTH + BRICK_SEP)), (TOP_FRACTION * GWINDOW_HEIGHT) + (col * (BRICK_HEIGHT + BRICK_SEP)), BRICK_WIDTH, BRICK_HEIGHT) rect.setFilled(True) rect.setColor(colors[col]) gw.add(rect) paddle = GRect((GWINDOW_WIDTH - PADDLE_WIDTH) / 2, PADDLE_Y, PADDLE_WIDTH, PADDLE_HEIGHT) paddle.setFilled(True) gw.add(paddle) gw.addEventListener('mousemove', mousemoveAction) ball = GOval((GWINDOW_WIDTH - BALL_SIZE) / 2, (GWINDOW_HEIGHT - BALL_SIZE) / 2, BALL_SIZE, BALL_SIZE) ball.setFilled(True) gw.add(ball) gw.addEventListener('click', clickAction) instruct = GLabel('Click to Start!') instruct.setFont('bold 24px sans-serif') x_inst = (GWINDOW_WIDTH - instruct.getWidth()) / 2 y_inst = ((GWINDOW_HEIGHT - instruct.getHeight()) / 2) + (3 * BALL_SIZE) gw.add(instruct, x_inst, y_inst) balls_left = N_BALLS bricks_hit = 0
def game(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) game_state = GameState() apples_collected = [] objects_lost = [] background = GImage("background.png", 0, 0) gw.add(background) scoreboard = GRect(GWINDOW_WIDTH - SB_WIDTH, 550, SB_WIDTH, SB_HEIGHT) scoreboard.setFilled(True) scoreboard.setColor("White") gw.add(scoreboard) collected_label = create_centered_label("Apples collected: ", GWINDOW_WIDTH - 160, 590, SB_FONT) gw.add(collected_label) collected_num_label = create_centered_label(str(len(apples_collected)), GWINDOW_WIDTH - 30, 590, SB_FONT) gw.add(collected_num_label) lost_label = create_centered_label("Apples lost: ", GWINDOW_WIDTH - 195, 650, SB_FONT) gw.add(lost_label) lost_num_label = create_centered_label(str(len(objects_lost)), GWINDOW_WIDTH - 30, 650, SB_FONT) gw.add(lost_num_label) c = Character() isaac_newton = c.character gw.add(isaac_newton) # This function adds the apples to the game, according to the timestep provided in the list of constants. Apples # added to a list and removed when they are either collected or they hit the ground. apples = [] def add_apples(): xpos = random.randint(0 + APPLE_WIDTH, GWINDOW_WIDTH - APPLE_WIDTH) f = Falling_Object(xpos) apple = f.apple gw.add(apple) apples.append(apple) # This function adds worms to the window. Worms will appear after some duration of the game (i.e. 5 apples # have been collected). They appear according to the third timestep provided in constants.py. worms = [] def add_worms(): if len(apples_collected) > 5: xpos = random.randint(0 + WORM_WIDTH, GWINDOW_WIDTH - WORM_WIDTH) w = Worm(xpos) worm = w.worm gw.add(worm) worms.append(worm) # This function increases the apples' y velocity every time 3 apples are collected so that the game becomes harder # as the player progresses. def change_yvel(): if len(apples_collected) % 3 == 0 and len(apples_collected) != 0: game_state.apple_yvel += 0.005 return game_state.apple_yvel # This is the most important function. It makes both the apple and the worm objects move. It handles collisions # between isaac_newton and objects, and deals with them accordingly. This function is called every timestep (constants) # If you lose < 3 apples and collect 25 without collecting a worm, you win the game! def update_objects(): collected_num_label.setLabel(len(apples_collected)) for apple in apples: apple_x_now = apple.getX() apple_y_now = apple.getY() + APPLE_HEIGHT isaac_x = isaac_newton.getX() isaac_y = isaac_newton.getY() if isaac_x <= apple_x_now <= ( isaac_x + ISAAC_WIDTH) and isaac_y <= apple_y_now <= ( isaac_y + ISAAC_HEIGHT): gw.remove(apple) apples.remove(apple) apples_collected.append(apple) if apple_y_now >= GWINDOW_HEIGHT: objects_lost.append(apple) lost_num_label.setLabel(len(objects_lost)) gw.remove(apple) apples.remove(apple) if len(objects_lost) >= 3: end_game(game_state) add_loser(gw) if len(apples_collected) == 25: collected_num_label.setLabel(len(apples_collected)) end_game(game_state) add_winner(gw) game_state.apple_yvel = change_yvel() apple.move(game_state.xvel, game_state.apple_yvel) for worm in worms: worm_x_now = worm.getX() worm_y_now = worm.getY() + WORM_HEIGHT isaac_x = isaac_newton.getX() isaac_y = isaac_newton.getY() if isaac_x <= worm_x_now <= ( isaac_x + ISAAC_WIDTH) and isaac_y <= worm_y_now <= ( isaac_y + ISAAC_HEIGHT): gw.remove(worm) worms.remove(worm) end_game(game_state) add_loser(gw) if worm_y_now >= GWINDOW_HEIGHT: gw.remove(worm) worms.remove(worm) worm.move(game_state.xvel, game_state.worm_yvel) # This function handles the key movement for isaac_newton. If the player touches the left arrow, isaac will move left. # This is the same for the right arrow. def key_action(event): if event.key == "<LEFT>": isaac_newton.move(-ISAAC_XVEL, ISAAC_YVEL) elif event.key == "<RIGHT>": isaac_newton.move(ISAAC_XVEL, ISAAC_YVEL) if isaac_newton.getX() >= (GWINDOW_WIDTH - ISAAC_WIDTH): isaac_newton.setLocation(GWINDOW_WIDTH - ISAAC_WIDTH, Character().ypos) gw.addEventListener("key", key_action) if isaac_newton.getX() <= 0: isaac_newton.setLocation(0, Character().ypos) gw.addEventListener("key", key_action) # Adds key event listener for the arrows and starts the round calling the appropriate functions with the right # timesteps. gw.addEventListener("key", key_action) start_round(gw, game_state, update_objects, add_apples, add_worms)
def DrawHexagon(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) hexagon = createHexagon(HEXAGON_SIDE) gw.add(hexagon, gw.getWidth() / 2, gw.getHeight() / 2)
def TestSierpinskiTriangle(): gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) triangle = GSierpinskiTriangle(100, 1) gw.add(triangle, gw.getWidth() / 2, gw.getHeight() / 2)
def drawPolygon(sides, size): gw = GWindow(500, 500) regualrPolygon = GRegularPolygon(sides, size) gw.add(regualrPolygon, 250, 250)