Пример #1
0
def createBackground(color):
    
    background = GRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)
    background.setFilled(True)
    background.setColor(color)
    
    return background
Пример #2
0
	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)
Пример #3
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
Пример #4
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)
Пример #5
0
def createRect(x, y, w, h, color):
    
    rect = GRect(x, y, w, h)
    rect.setFilled(True)
    rect.setColor(color)
    
    return rect
Пример #6
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
Пример #7
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)
Пример #8
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
Пример #9
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)
Пример #10
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
Пример #11
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)
Пример #12
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)
Пример #13
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)
Пример #14
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
Пример #16
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)
Пример #17
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)
Пример #18
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)
Пример #19
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)
Пример #20
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)
Пример #21
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)
Пример #22
0
class SudokuCell(GCompound):
    
    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
        
    def get_digit(self):
        if self.digit == None or self.digit == '' or self.only_a_suggestion:
            return 0
        else:
            return int(self.digit)

    def set_background_color(self, color):
        self.cell.setFillColor(color)

    def suggest_solution(self, digit):        
        if self.only_a_suggestion:
            self.digit = str(digit)
            self.render_label()

    def render_label(self):
        if self.label is not None:
            self.remove(self.label)
        if self.digit is not None and self.digit != "0":
            self.label = GLabel(self.digit)
        else:
            self.label = GLabel("")
        self.label.setFont(CELL_FONT)
        if self.only_a_suggestion:
            self.label.setColor(SUGGESTION_TEXT_COLOR)
        else:            
            self.label.setColor(CELL_TEXT_COLOR)
        self.add(self.label, 
                 CELL_WIDTH//2 - self.label.getWidth()//2, 
                 CELL_WIDTH//2 + self.label.getAscent()//2 - 7)

        
    def mousedown(self):
        self.selector = SudokuDigitSelector()
        self.add(self.selector, 0, 0)        

    def mouseup(self, x, y):
        if self.selector is not None:
            digit = self.selector.mouseup(x, y)            
            if digit is not None:
                self.digit = digit
                if str(self.digit) == "0" or self.digit == "":
                    self.digit = ""
                    self.only_a_suggestion = True
                elif self.digit != "":
                    self.only_a_suggestion = False    
                self.render_label()
            self.remove(self.selector)
            self.selector = None
Пример #23
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