示例#1
0
	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 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 create_object():
    """
    Creates the original DVD Logo. Code from here will be moved into
    the new class that you are creating.
    """

    width = 200
    height = 200

    obj = GCompound()

    cube = GRect(0, 0, width, height)
    cube.set_filled(True)
    cube.set_color(random_color())
    obj.add(cube)

    dvdtext = GLabel("DVD")
    dvdtext.set_font("bold 60px 'serif'")
    obj.add(dvdtext, width / 2 - dvdtext.get_width() / 2, height / 2 - 10)

    vidtext = GLabel("video")
    vidtext.set_font("bold 50px 'serif'")
    vidtext.set_color("white")
    obj.add(vidtext, width / 2 - vidtext.get_width() / 2,
            height / 2 + vidtext.get_ascent())

    return obj
示例#4
0
def createRect(x, y, w, h, color):
    
    rect = GRect(x, y, w, h)
    rect.setFilled(True)
    rect.setColor(color)
    
    return rect
示例#5
0
    def makeDisplay(alphabetLabels, upCardLabels):
        decisionIndicators = dict()
        letterWidth = alphabetLabels[0].getWidth()
        letterHeight = alphabetLabels[0].getHeight()
        XMARGIN = 50
        offset = (GWINDOW_WIDTH - XMARGIN -
                  (len(alphabetLabels) * letterWidth)) / (len(alphabetLabels) + 1)
        for (i, label) in enumerate(alphabetLabels):
            x = XMARGIN + (offset + letterWidth) * i + offset
            gw.add(label, x, GWINDOW_HEIGHT - LETTER_BASE)
            
        YMARGIN = 100        
        upCardOffset = (GWINDOW_HEIGHT - YMARGIN - 
                  (len(upCardLabels) * letterHeight)) / (len(upCardLabels) + 1)
        for (i, label) in enumerate(upCardLabels):
            y = YMARGIN + (upCardOffset + letterHeight) * i + upCardOffset
            gw.add(label, LETTER_BASE, y)

        for (i, upCardLabel) in enumerate(upCardLabels):
            y = YMARGIN + (upCardOffset + letterHeight) * i + upCardOffset - letterHeight
         
            for (j, totalLabel) in enumerate(alphabetLabels):
                x = XMARGIN + (offset + letterWidth) * j + offset
        
                decisionIndicator = GRect(x, y, letterHeight, letterWidth)
                decisionIndicator.setFillColor("black")
                decisionIndicator.setFilled(True)
                gw.add(decisionIndicator)
                decisionIndicators[(str(int(totalLabel.getLabel())), 
                                    str(int(upCardLabel.getLabel())))] = decisionIndicator
        return decisionIndicators
示例#6
0
 def _createBackground(self):
     frame = GRect(0, 0, self._frameWidth, self._frameHeight)
     frame.setFilled(True)
     frame.setColor(FRAME_COLOR)
     self.add(frame)
     x1 = self._frameWidth / 2
     x0 = x1 - PIECE_WIDTH - COLUMN_SEP
     x2 = x1 + PIECE_WIDTH + COLUMN_SEP
     y0 = TOP_MARGIN + PIECE_HEIGHT / 2
     y1 = self._frameHeight - BOTTOM_MARGIN - PIECE_HEIGHT / 2
     h = CHANNEL_WIDTH / 2
     poly = GPolygon()
     poly.addVertex(x0 - h, y1 + h)
     poly.addVertex(x0 - h, y0 - h)
     poly.addVertex(x2 + h, y0 - h)
     poly.addVertex(x2 + h, y1 + h)
     poly.addVertex(x2 - h, y1 + h)
     poly.addVertex(x2 - h, y0 + h)
     poly.addVertex(x1 + h, y0 + h)
     poly.addVertex(x1 + h, y1 + h)
     poly.addVertex(x1 - h, y1 + h)
     poly.addVertex(x1 - h, y0 + h)
     poly.addVertex(x0 + h, y0 + h)
     poly.addVertex(x0 + h, y1 + h)
     poly.addVertex(x0 - h, y1 + h)
     poly.setFilled(True)
     poly.setColor(CHANNEL_COLOR)
     self.add(poly)
示例#7
0
def createBackground(color):
    
    background = GRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)
    background.setFilled(True)
    background.setColor(color)
    
    return background
示例#8
0
def createFilledRect(x, y, width, height, fill='black', border=None):
    rect = GRect(x, y, width, height)
    rect.setFilled(True)
    if border is None:
        rect.setColor(fill)
    else:
        rect.setColor(border)
        rect.setFillColor(fill)
    return rect
示例#9
0
def makePaddle():  #Create paddle
    global paddle

    paddle = GRect((GWINDOW_WIDTH - PADDLE_WIDTH) / 2, PADDLE_Y, PADDLE_WIDTH,
                   PADDLE_HEIGHT)
    paddle.setFilled(True)
    paddle.setColor("black")

    gw.add(paddle)
示例#10
0
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
示例#11
0
def Kindergarten():
	gw = GWindow(GWINDOW_WIDTH,GWINDOW_HEIGHT)
	x0 = (gw.getWidth() - N_COLUMNS * SQUARE_SIZE) / 2
	y0 = (gw.getHeight()- N_ROWS * SQUARE_SIZE) / 2
	for row in range(N_ROWS):
		for col in range(N_COLUMNS):
			x = x0 + col * SQUARE_SIZE
			y = y0 + row * SQUARE_SIZE
			if row % 4 == 0:
				sq = GRect(x, y, SQUARE_SIZE, SQUARE_SIZE)
				sq.setFilled((row + col) % 2 != 0)
				gw.add(sq)
			elif row % 2 != 0:
				sq = GRect(x + ((1/3) * SQUARE_SIZE), y, SQUARE_SIZE, SQUARE_SIZE)
				sq.setFilled((row + col) % 2 != 0)
				gw.add(sq)
			else:
				sq = GRect(x + ((1/2) * SQUARE_SIZE), y, SQUARE_SIZE, SQUARE_SIZE)
				sq.setFilled((row + col) % 2 != 0)
				gw.add(sq)
				end_sq = GRect(x0, y0 + row * SQUARE_SIZE, SQUARE_SIZE * (1/2), SQUARE_SIZE)
				end_sq.setFilled(True)
				gw.add(end_sq)
			line = GLine(x0, y, x0 + N_COLUMNS * SQUARE_SIZE, y)
			line.setColor('darkgrey')
			width = line.getWidth()
			line.setLineWidth(width * 2)
			gw.add(line)
	rect = GRect(x0 + SQUARE_SIZE * N_COLUMNS, y0, SQUARE_SIZE * .5, y0 + SQUARE_SIZE * N_ROWS)
	rect.setFilled(True)
	rect.setColor('white')
	gw.add(rect)
	for i in range(2):
		line = GLine(x0 + (i * SQUARE_SIZE * N_COLUMNS), y0, x0 + (i * SQUARE_SIZE * N_COLUMNS), y0 + (SQUARE_SIZE * N_ROWS))
		line.setColor('darkgrey')
		gw.add(line)
	end = GLine(x0, y0 + N_ROWS * SQUARE_SIZE, x0 + N_COLUMNS * SQUARE_SIZE, y0 + N_ROWS * SQUARE_SIZE)
	end.setColor('darkgrey')
	gw.add(end)
示例#12
0
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)
示例#13
0
def create_filled_rect(x, y, width, height, fill="Black", border=None):
    """
    Creates a GRect filled with the specified fill color.  If border is
    specified, the border appears in that color.
    """
    rect = GRect(x - width / 2, y - height / 2, width, height)
    rect.setFilled(True)
    if border is None:
        rect.setColor(fill)
    else:
        rect.setColor(border)
        rect.setFillColor(fill)
    return rect
示例#14
0
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)
示例#15
0
 def __init__(self):
     GCompound.__init__(self)
     bar = GRect(GWINDOW_WIDTH, MENU_BAR_HEIGHT)
     bar.setFilled(True)
     bar.setColor(CELL_BORDER_COLOR)
     bar.setFillColor(MENU_BAR_BGCOLOR)
     self.add(bar, 0, 0)
     self.label = GLabel("Y O U D O K U")
     self.label.setFont(MENU_TITLE_FONT)
     self.label.setColor(MENU_TITLE_COLOR)
     self.add(self.label, 
              GWINDOW_WIDTH//2 - self.label.getWidth()//2, 
              MENU_BAR_HEIGHT//2 + self.label.getAscent()//2 - 5)
示例#16
0
	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)
示例#17
0
 def __init__(self, digit):
     GCompound.__init__(self)
     self.digit = str(digit)
     cell = GRect(0, 0, SUBCELL_WIDTH, SUBCELL_WIDTH)
     cell.setColor(CELL_BORDER_COLOR)
     cell.setFillColor(SUBCELL_FILL_COLOR)
     cell.setFilled(True)
     self.add(cell, 0, 0)
     self.label = GLabel(digit)
     self.label.setFont(SUBCELL_FONT)
     self.label.setColor(SUBCELL_TEXT_COLOR)
     self.add(self.label, 
              SUBCELL_WIDTH//2 - self.label.getWidth()//2, 
              SUBCELL_WIDTH//2 + self.label.getAscent()//2 - 3)
示例#18
0
 def __init__(self, digit):
     GCompound.__init__(self)
     if digit != 0:
         self.digit = str(digit)
     else:
         self.digit = None
     self.cell = GRect(0, 0, CELL_WIDTH, CELL_WIDTH)
     self.cell.setColor(CELL_BORDER_COLOR)
     self.cell.setFillColor(CELL_GOOD_COLOR)
     self.cell.setFilled(True)        
     self.add(self.cell, 0, 0)  
     self.label = None
     self.only_a_suggestion = True
     self.render_label()
     self.selector = None
示例#19
0
 def __init__(self, color, level, puzzle):
     """Creates a piece with the indicated color and initial level"""
     GCompound.__init__(self)
     self._level = level
     self._puzzle = puzzle
     self.setColor(color)
     frame = GRect(PIECE_WIDTH, PIECE_HEIGHT)
     frame.setFilled(True)
     frame.setColor(PIECE_COLOR)
     self.add(frame, -PIECE_WIDTH / 2, 0)
     poly = GPolygon()
     dw = PIECE_WIDTH / puzzle.getNLevels()
     w0 = (level - 1) * dw
     w1 = level * dw
     poly.addVertex(-w0 / 2, 0)
     poly.addVertex(w0 / 2, 0)
     poly.addVertex(w1 / 2, PIECE_HEIGHT)
     poly.addVertex(-w1 / 2, PIECE_HEIGHT)
     poly.setFilled(True)
     poly.setColor(color)
     self.add(poly)
     border = GRect(PIECE_WIDTH, PIECE_HEIGHT)
     border.setColor(BORDER_COLOR)
     self.add(border, -PIECE_WIDTH / 2, 0)
示例#20
0
 def __init__(self, text, fn=None):
     GCompound.__init__(self)
     label = GLabel(text)
     label.set_font(self.BUTTON_FONT)
     width = max(self.BUTTON_MIN_WIDTH,
                 2 * self.BUTTON_MARGIN + label.get_width())
     frame = GRect(width, self.BUTTON_DEFAULT_HEIGHT)
     frame.set_filled(True)
     frame.set_fill_color("White")
     self.add(frame)
     self.add(label)
     self.text = text
     self.label = label
     self.frame = frame
     self.fn = fn
     self._recenter()
示例#21
0
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)
示例#22
0
def rainbow():
    gw = GWindow(500, 250)
    rect = GRect(0, 0, 500, 250)
    rect.setColor('cyan')
    rect.setFilled(True)
    gw.add(rect)

    red = GOval(X, Y, W, H)
    red.setColor('Red')
    red.setFilled(True)

    orange = GOval(X, 2 * Y, W, H)
    orange.setColor('Orange')
    orange.setFilled(True)

    yellow = GOval(X, 3 * Y, W, H)
    yellow.setColor('Yellow')
    yellow.setFilled(True)

    green = GOval(X, 4 * Y, W, H)
    green.setColor('Green')
    green.setFilled(True)

    blue = GOval(X, 5 * Y, W, H)
    blue.setColor('blue')
    blue.setFilled(True)

    indigo = GOval(X, 6 * Y, W, H)
    indigo.setColor('indigo')
    indigo.setFilled(True)

    violet = GOval(X, 7 * Y, W, H)
    violet.setColor('violet')
    violet.setFilled(True)

    end = GOval(X, 8 * Y, W, H)
    end.setColor('cyan')
    end.setFilled(True)

    gw.add(red)
    gw.add(orange)
    gw.add(yellow)
    gw.add(green)
    gw.add(blue)
    gw.add(indigo)
    gw.add(violet)
    gw.add(end)
    def __init__(self, letter, perm, inverse):
        GCompound.__init__(self)

        rotor = GRect(ROTOR_WIDTH, ROTOR_HEIGHT)
        rotor.setColor(ROTOR_BGCOLOR)
        rotor.setFilled(True)
        self.add(rotor, -ROTOR_WIDTH / 2,
                 -ROTOR_HEIGHT / 2)  # create design for rotors

        self.ch = GLabel(letter)
        self.ch.setColor(ROTOR_COLOR)
        self.ch.setFont(ROTOR_FONT)
        self.add(self.ch, -self.ch.getWidth() / 2, ROTOR_LABEL_DY)

        self.perm = perm
        self.inverse = inverse
        self.offset = 0
        self.rotor = rotor
示例#24
0
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)
示例#25
0
 def __init__(self, node):
     GCompound.__init__(self)
     self._node = node
     frame = GRect(ArpanetMonitor.WIDTH,
                   ArpanetMonitor.MAX_NODES * ArpanetMonitor.VSPACE)
     self.add(frame, 0, ArpanetMonitor.VSPACE)
     label = GLabel(node.getName())
     label.setFont(ArpanetMonitor.FONT)
     x = ArpanetMonitor.MARGIN
     y = label.getAscent()
     self.add(label, x, y)
     self._label = label
     self._lines = []
     for i in range(ArpanetMonitor.MAX_NODES):
         y += ArpanetMonitor.VSPACE
         label = GLabel("")
         label.setFont(ArpanetMonitor.FONT)
         self.add(label, x, y)
         self._lines.append(label)
     self.update()
示例#26
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)
示例#27
0
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)
示例#28
0
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)
示例#29
0
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
示例#30
0
def create_filled_rect(x, y, w, h, color):
    """ Creates a filled rectangle of the desired color. """
    r = GRect(x, y, w, h)
    r.set_filled(True)
    r.set_color(color)
    return r