def __init__(self, scr):
        self.backGround = pygame.image.load(r"data\image\audiobg.png")
        self.backGround = pygame.transform.scale(
            self.backGround, (Screen.screen.W, Screen.screen.H))

        self.addIcon = pygame.image.load(r"data\image\add.png")
        self.addIcon = pygame.transform.scale(
            self.addIcon,
            (int(Screen.screen.W / 25), int(Screen.screen.W / 25)))

        self.buttons = [
            Button.PButton(Screen.screen.W / 3,
                           Screen.screen.H / 6.2 + (i * Screen.screen.H / 10),
                           Screen.screen.W / 25, "delete.png", "delete.png",
                           scr) for i in range(3)
        ]
        self.audioButtons = [
            Button.PButton(Screen.screen.W / 1.5,
                           Screen.screen.H / 6.2 + (i * Screen.screen.H / 10),
                           Screen.screen.W / 25, "pauseIcon.png",
                           "playIcon.png", scr) for i in range(3)
        ]
        self.font = pygame.font.Font('freesansbold.ttf', Screen.screen.W // 52)
        self.scr = scr

        self.audioSamples = []
        self.audioSamples.append(r"data\audio\twinkle.wav")
        self.audioSamples.append(r"data\audio\ant.wav")
        self.audioSamples.append(r"data\audio\asked.wav")
Exemple #2
0
def menu():
    size = width, height = 250, 290
    screen = pygame.display.set_mode(size)
    testquit = Button.button()
    testquit.setPicture("Pictures/QUIT.png")
    testquit.setCords(0, 0, 250, 70)
    testquit.setEvent(quit)
    testplay = Button.button()
    testplay.setPicture("Pictures/PLAY.png")
    testplay.setCords(0, 110, 250, 70)
    testplay.setEvent(play)
    teststats = Button.button()
    teststats.setPicture("Pictures/STAT.png")
    teststats.setCords(0, 220, 250, 70)
    teststats.setEvent(stats)
    screen.blit(testplay.setPicture("Pictures/PLAY.png"),
                pygame.Rect(0, 110, 250, 70))
    screen.blit(testquit.setPicture("Pictures/QUIT.png"),
                pygame.Rect(0, 0, 250, 70))
    screen.blit(teststats.setPicture("Pictures/STATS.png"),
                pygame.Rect(0, 220, 250, 70))
    pygame.display.update()

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if testquit.in_button(event.pos):
                    testquit.bEvent()
                if testplay.in_button(event.pos):
                    testplay.bEvent()
                if teststats.in_button(event.pos):
                    teststats.bEvent()
Exemple #3
0
 def rulesScreen(self):
     '''shows the rules of the game, returns True if the "back" button was hit'''
     start = True
     # initializing buttons
     back = Button((30, 30), 50, img=self.back_img)
     buttons = [back]
     while start:
         # sticking to fps
         self.clock.tick(FPS)
         # --------------------EVENTS---------------------
         for event in pg.event.get():
             if event.type == pg.QUIT:
                 # if exit button is pressed
                 return False
             elif event.type == pg.MOUSEBUTTONDOWN:
                 # if mouse is pressed check button overlapping
                 if back.triggered(channel=self.click_sound_channel,
                                   sound=self.click_sound,
                                   playing=self.sound_state):
                     return True
         # highlight buttons
         for button in buttons:
             button.highlighted()
         # --------------------STUFF-----------------------
         self.screen.blit(self.bg_img, (0, 0))
         textOut(self.screen, 'Rules', 100, ORANGE, (W / 2, H / 3))
         textOutMultiline(self.screen, self.rules_text, 30, BLACK,
                          (W / 2, H / 3))
         # show buttons
         for button in buttons:
             button.show(self.screen)
         # double processing
         pg.display.flip()
Exemple #4
0
    def setupToolButtons(self):
        """Initializes all the tool buttons"""
        toolSpec = (
            ("ClearButton.png", self.clearStrokes, None, QColor.White),
            (),
            # ("SelectTool.png", self.activateSelect, None, QColor.White),
            # ("TextTool.png", self.activateText, None, QColor.White),
            ("SmallBrush.png", self.activateBrush, 2, QColor.White),
            ("MidBrush.png", self.activateBrush, 5, QColor.White),
            ("LargeBrush.png", self.activateBrush, 10, QColor.White),
            (),
            ("DebugButton.png", self.toggleDebug, None, QColor.White),
        )
        px = 4
        py = (self.extent[1] - len(toolSpec) * 32) // 2

        for spec in toolSpec:
            if (len(spec) > 0):
                pic = spec[0]
                image = self.canvas.loadImage(pic)
                if (image is None):
                    self.println("[Scribbler]: Failed to load " + pic)
                box = QRect(px, py, 32, 32)
                button = Button(box, image, spec[3], False)
                button.action = spec[1]
                button.argument = spec[2]
                self.buttons.append(button)
            py = py + 31
def exitbutton(win):
    #creates the button which closes the program (to be placed on every page)
    centre = Point(387, 393)
    exitbut = Button(win, centre, 15, 25, "x")
    exitbut.activate("red")
    #places the button in top right and returns the button to user
    return exitbut
def initWeaponTiles():
    global buttons

    buttons['weapons'] = []
    buttons['smoke'] = {}
    buttons['armor'] = []

    for i in range(0, 2):
        buttons['weapons'].append({})
        buttons['armor'].append({})

        for y in range(0, 3):
            for x in range(0, 3):
                if y != 2 or x != 2:
                    id = y * 3 + x
                    buttons['weapons'][i][id] = Button(
                        '/img/' + weapons[id]['src'], [
                            center[0] - 450 + 150 * x + 575 * i,
                            center[1] - 150 + (y * 150)
                        ], [125, 125])

            buttons['armor'][i][y] = Button(
                '/img/armor_' + str(y + 1) + '.jpeg',
                [center[0] - 650 + 1275 * i, center[1] - 150 + (y * 150)],
                [125, 125])

        buttons['smoke'][i] = Button(
            '/img/smoke_grenade.png',
            [center[0] - 150 + 575 * i, center[1] + 150], [125, 125])
class StartSurface():
    def __init__(self):
        self.button_play = Button(BUTTON_PLAY, 230, 120, 140, button_size_x,
                                  button_size_y)
        self.button_info = Button(BUTTON_INFO, 230, 120, 240,
                                  2 * button_size_x, button_size_y)

    def create_surface(self):
        surface = pygame.Surface([800, 600], pygame.SRCALPHA, 32)

        image = pygame.image.load(TITLE_PATH).convert()
        image_surface = pygame.transform.scale(image, (750, 300))
        button_play_surf = self.button_play.create_surface()
        button_info_surf = self.button_info.create_surface()

        surface.blit(button_play_surf, [button_play_pos_x, button_play_pos_y])
        surface.blit(button_info_surf, [button_info_pos_x, button_info_pos_y])
        surface.blit(image_surface, [title_pos_x, title_pos_y])

        return surface

    def button_clicked(self, mouse):
        if button_play_pos_x + button_size_x > mouse[
                0] > button_play_pos_x and button_play_pos_y + button_size_y > mouse[
                    1] > button_play_pos_y:
            return True
        if button_info_pos_x + button_size_x > mouse[
                0] > button_info_pos_x and button_info_pos_y + button_size_y > mouse[
                    1] > button_info_pos_y:
            Tk().wm_withdraw()
            messagebox.showinfo(
                'Instructions',
                'Make the basketball fall into the basket, using given objects!'
            )
Exemple #8
0
def run(notefiles, display):

    font = pygame.font.SysFont("genevattf", 100)
    diff = 3
    melody = n.getNote(diff, notefiles)

    mainM = b.button((0, 162, 199), 50, 100, 90, 40, "Main Menu")
    playMel = b.button((0, 162, 199), 50, 300, 90, 40, "Play Mel")
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.QUIT
                running = False
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()

                if playMel.isOver(pos):
                    n.playNotes(melody, notefiles)

                if(mainM.isOver(pos)):
                    EarApp.main()

        display.fill((255, 255, 255))
        text = font.render("Melody Matcher", 1, (0, 0, 0))
        display.blit(text, (80, 30))
        mainM.draw(display)
        playMel.draw(display)
        pygame.display.update()
Exemple #9
0
def main() :
	global board
	global rack
	global checkButton
	global nextTurnButton
	global getHintButton
	#global switch
	global checkButtonFunction
	global nextTurnButtonFunction
	global scoreLabel
	
	checkButtonFunction = checkBoard
	nextTurnButtonFunction = doNothing
	
	loadWordList()
	board = ScrabbleBoard()
	#placeTileOnBoard(board, 1, 1, "A")
	rack = ScrabbleRack()
	checkButton = Button((WIDTH - 285), RACK_Y, 100, 50, "Check Words")
	nextTurnButton = Button((WIDTH - 170), RACK_Y, 100, 50, "Next Turn")
	getHintButton = Button(10, RACK_Y, 60, 50, "Cheat")
	scoreLabel = Button(20, 15, 100, 10, "Score: 0", "White", "White")
	#switch = Button(10, 10, 10, 10, "Switch")
	nextTurnButton.remove()
	fillRack(rack)
	bindMouseClick(clicked)
	
	''''while True:
Exemple #10
0
def kazino():
    start = True
    screen.fill([255, 255, 255])
    screen.blit(fon6.image, fon6.rect)
    unNoDialog = Dialog(screen)
    unNoDialog.message = ("Гон: Вполне возможно что Киллуа пропал. Ты не знаешь что-то об этом?.",)
    unNoDialog.show = True
    unNoDialog.sndNext()
    unNoDialog.message = ("Хисока: Вы из-за этого пришли? Не то что бы мне есть дело, но вы рассказали Иллуми?.",)
    unNoDialog.show = True
    unNoDialog.sndNext()
    yes1 = Button.Button()
    yes1.create_button(screen, (124, 124, 124), 0, 500, 900 // 2, 200, 0, 'да', (255, 255, 255), 1)
    no1 = Button.Button()
    no1.create_button(screen, (124, 124, 124), 900 // 2, 500, 900 // 2, 200, 0, 'нет', (255, 255, 255), 1)
    while start:
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if yes1.pressed(pos):
                    start = False
                    yes()
                if no1.pressed(pos):
                    start = False
                    no()
Exemple #11
0
 def __CreateButtonRow(self, parent, rownum, size):
     for col in range(0, size):
         x = col * 25
         y = 0
         button = Button(parent, x, y)
         button.SetButtonID(rownum, col)
         button.SetEventManager(self.__eventManager)
    def draw_main_menu(self, button_list):
        self.window.fill((0, 0, 0))
        background = pygame.image.load(self.background_image).convert()
        background = pygame.transform.scale(
            background, (self.display_width, self.display_width))
        self.window.blit(background, (0, 0))

        button_list.append(
            Button("start_pvc", self.display_width / 4,
                   (self.display_height / 5) * 1, 500, 50,
                   "placeholder/placeholder_1.png"))
        button_list.append(
            Button("start_pvp", self.display_width / 4,
                   (self.display_height / 5) * 2, 500, 50,
                   "placeholder/placeholder_2.png"))
        button_list.append(
            Button("start_trn", self.display_width / 4,
                   (self.display_height / 5) * 3, 500, 50,
                   "placeholder/placeholder_3.png"))
        button_list.append(
            Button("Quit", self.display_width / 4,
                   (self.display_height / 5) * 4, 500, 50,
                   "placeholder/placeholder.png"))
        for item in button_list:
            item.draw(self.window)
Exemple #13
0
    def rulesScreen(self):

        start = True
        # przyciski
        back = Button((30, 30), 50, img=self.back_img)
        buttons = [back]
        while start:
            # fps
            self.clock.tick(FPS)
            # zdarzenia
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    # jezeli exit jest klikniety
                    return False
                elif event.type == pg.MOUSEBUTTONDOWN:
                    # jezeli sprawdzenia guzik
                    if back.triggered(channel=self.click_sound_channel,
                                      sound=self.click_sound,
                                      playing=self.sound_state):
                        return True
            # highlight przycisk
            for button in buttons:
                button.highlighted()
            # rzeczy
            self.screen.blit(self.bg_img, (0, 0))
            textOut(self.screen, 'Rules', 100, ORANGE, (W / 2, H / 3))
            textOutMultiline(self.screen, self.rules_text, 30, BLACK,
                             (W / 2, H / 3))
            # pokazanie
            for button in buttons:
                button.show(self.screen)

            pg.display.flip()
Exemple #14
0
    def __init__(self,
                 text,
                 handler=None,
                 handler_message=None,
                 default_choice=0,
                 x=None,
                 y=None,
                 width=0,
                 height=0,
                 icon=None,
                 vertical_expansion=1,
                 text_prop=None,
                 parent='osd'):

        PopupBox.__init__(self, text, handler, x, y, width, height, icon,
                          vertical_expansion, text_prop, parent)

        self.handler_message = handler_message

        # XXX: It may be nice if we could choose between
        #      OK/CANCEL and YES/NO

        self.b0 = Button(_('OK'), width=(self.width - 60) / 2)
        self.b0.set_h_align(Align.NONE)
        self.add_child(self.b0)

        self.b1 = Button(_('CANCEL'), width=(self.width - 60) / 2)
        self.b1.set_h_align(Align.NONE)
        self.add_child(self.b1)
        select = 'self.b%s.toggle_selected()' % default_choice
        eval(select)
def main():
    buttonL = Button.button(0)
    buttonR = Button.button(35)

    display = display_init()
    ip = connect2WiFi(display)
    printScreen(ip, display, font_30, 20, 20, fg=st7789.WHITE, bg=st7789.BLACK)
    utime.sleep(2)
    setLocalTime()
    utime.sleep(2)
    display.fill(st7789.BLACK)
    utime.sleep(2)
    radio = radio_init()

    s, poller = getUdp_poll_init(ip)

    radio_setFreq(radio, 99.1)
    #printScreen("99.1 MHz",display, 20, 20, fg = st7789.WHITE, bg = st7789.BLACK)

    ready = False
    while (True):
        buttonL.poll()
        buttonR.poll()

        radio_control(radio, display, buttonR.pressed(), buttonL.pressed())
        showLocalTime(display)

        res = getUdp_poll(s, poller)
        if res[0] is True:
            processUdpCommand(radio, display, res[1])

        utime.sleep(0.1)
Exemple #16
0
 def __init__(self):
     """
     Initialize all related modules and the screen
     """
     # 0. initialize all modules and music
     pygame.init()
     pygame.mixer.init()
     # 1. set a screen
     self.window_size = WIDTH, HEIGHT
     self.window = pygame.display.set_mode(self.window_size)
     pygame.display.set_caption("Snake v1.0")
     self.window.fill(GREY)
     self.clock = pygame.time.Clock()
     # 2. set game status
     self.is_quit = False
     self.is_start = False
     # 3. set font and image
     self.title_font = pygame.font.SysFont(GEORGIA, 55)
     self.button_font = pygame.font.SysFont(GEORGIA, 20)
     self.normal_font = pygame.font.SysFont(GEORGIA, 30)
     self.bg_pic = pygame.image.load(BG_PIC)
     self.btn_start = Button.Button((220, 450), (110, 40), (250, 457),
                                    START_BUTTON_TXT)
     self.btn_quit = Button.Button((520, 450), (110, 40), (550, 457),
                                   QUIT_BUTTON_TXT)
Exemple #17
0
 def on_mouse_release(self, x, y, button, modifiers):
     if self.current_state is not GAME_RUNNING:
         Button.check_mouse_release_for_buttons(x, y, self.button_list)
     elif self.current_state == GAME_RUNNING:
         if button == arcade.MOUSE_BUTTON_LEFT and not self.started:
             self.ball.launch(x, y)
             self.started = True
Exemple #18
0
    def pause(self, liste_event):
        self.isPaused = True
        self.screen.fill(0)
        self.screen.blit(
            self.font_pixel_32.render("Pause", False, (255, 255, 255)),
            (SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT / 2 - 50))

        btn_reprendre_pause = Button.Button(
            (56, 142, 60), "Reprendre", 160, 48,
            (SCREEN_WIDTH / 2 - 64, SCREEN_HEIGHT / 2 + 100), 12, 4,
            (56, 142, 60))
        btn_quitter_pause = Button.Button(
            (244, 67, 54), "Quitter", 160, 48,
            (SCREEN_WIDTH / 2 - 64, SCREEN_HEIGHT / 2 + 164), 12, 4,
            (244, 67, 54))
        btn_reprendre_pause.afficher(self.screen)
        btn_quitter_pause.afficher(self.screen)

        for event in liste_event:
            if (event.type == pygame.MOUSEBUTTONUP):
                if (btn_reprendre_pause.pressed(pygame.mouse.get_pos())):
                    connection.Send({
                        "action": "pause",
                        "idJoueur": self.idServeur
                    })
                if (btn_quitter_pause.pressed(pygame.mouse.get_pos())):
                    sys.exit()
    def setupToolButtons(self):
        """Initializes all the tool buttons"""
        toolSpec = (
            ("ClearButton.png", self.clearStrokes, None, QColor.White),
            (),
            # ("SelectTool.png", self.activateSelect, None, QColor.White),
            # ("TextTool.png", self.activateText, None, QColor.White),
            ("SmallBrush.png", self.activateBrush, 2, QColor.White),
            ("MidBrush.png", self.activateBrush, 5, QColor.White),
            ("LargeBrush.png", self.activateBrush, 10, QColor.White),
            (),
            ("DebugButton.png", self.toggleDebug, None, QColor.White),
        )
        px = 4
        py = (self.extent[1] - len(toolSpec) * 32) // 2

        for spec in toolSpec:
            if(len(spec) > 0):
                pic = spec[0]
                image = self.canvas.loadImage(pic)
                if(image is None): self.println("[Scribbler]: Failed to load " + pic)
                box = QRect(px, py, 32, 32)
                button = Button(box, image, spec[3], False)
                button.action = spec[1]
                button.argument = spec[2]
                self.buttons.append(button)
            py = py + 31
Exemple #20
0
def show(menu):
    """
	Display the menu on screen
	@param menu: object of type \"Menu\"
	@type menu: dict

	@return: -
	@rtype: void
	"""
    #display every buttons

    SCREEN_WIDTH, SCREEN_HEIGHT = Object.SCREEN_WIDTH, Object.SCREEN_HEIGHT
    x = int(round((SCREEN_WIDTH / 2.) - (len(menu["title"]) / 2.)))
    Tools.goAt(x + 1, 0)
    sys.stdout.write('\033[53;4;1m\033[38;2;200;0;0m' + menu["title"] +
                     '\033[0m')
    #53:overlined
    #4:Underline
    #1:Bold
    #7:reverse color

    for i in range(0, len(menu["buttonList"])):
        Button.show(menu["buttonList"][i])

    return
Exemple #21
0
def help_loop():
    font = pygame.font.SysFont("arial", 24)
    font_height = font.get_linesize()
    pygame.display.set_caption("Welcome To Snake")
    background = 'data/bg.jpg'
    bg = pygame.image.load(background).convert_alpha()
    back_button = Button()
    while True:
        screen.fill((0, 0, 0))
        screen.blit(bg, (0, 0))
        pygame.draw.polygon(screen, whiteColour,
                            [[175, 225], [175, 400], [900, 400], [900, 225]],
                            4)
        show_message(screen, 'Press WASD to move snake around!', blackColour,
                     40, 200, 250)
        show_message(screen, 'move your snake to yellow wormhole to upgrade!',
                     blackColour, 40, 200, 300)
        show_message(screen, 'eat as much food as possible!', blackColour, 40,
                     200, 350)

        back_button.create_button(screen, whiteColour, 300, 480, 200, 50, 60,
                                  "Back", steelBlue)

        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_f:
                    menu_loop()
                if event.key == pygame.K_ESCAPE:
                    pygame.event.post(pygame.event.Event(pygame.QUIT))
            elif event.type == pygame.MOUSEBUTTONUP:
                if back_button.pressed(pygame.mouse.get_pos()):
                    menu_loop()
Exemple #22
0
    def __init__(self, ThisSurface, Name, Text):
        # Select covers full display surface to prevent other interface items being clicked before the selection has been clicked.
        Visual.Visual.__init__(self, ThisSurface, Name, Visual.PRESS_NONE, 0,
                               0, Visual.BUTTON_HEIGHT, Visual.BUTTON_HEIGHT,
                               Text)

        # Select covers full display, but only draw in middle so some interface can still be seen, but not used.
        self.xLen = self.DisplayXLen / 1.5
        self.yLen = self.DisplayYLen / 1.5
        self.xPos = (self.DisplayXLen - self.xLen) / 2
        self.yPos = (self.DisplayYLen - self.yLen) / 1.65
        self.Align = Visual.ALIGN_TEXT_LEFT
        self.ColourFill = self.ColourDialog
        while len(self.Text) > 0 and self.Text[len(self.Text) - 1] == '\n':
            self.Text = self.Text[:len(self.Text) - 1]

        # Buttons displayed on the confirm dialog.
        self.Buttons = {
            # Confirm covers full display with this button to prevent other user interface being used while dialog visible.
            "UI_BLOCKER":
            Button.Button(self.ThisSurface, "UI_BLOCKER", Visual.PRESS_NONE,
                          -self.xLen, -self.yLen, self.DisplayXLen,
                          self.DisplayYLen, "UI_BLOCKER"),
            "CLOSE":
            Button.Button(self.ThisSurface, "CLOSE", Visual.PRESS_DOWN,
                          self.xLen - Visual.BUTTON_HEIGHT, 0,
                          Visual.BUTTON_HEIGHT, Visual.BUTTON_HEIGHT,
                          "IMAGE:icons/Close.png"),
        }

        self.Buttons["UI_BLOCKER"].SetVisible(False)
Exemple #23
0
 def set_menu_buttons(self):
     x_tela = self.janela.width * 0.5
     y_tela = self.janela.height * 0.5
     dist_btn = 70
     self.buttons_parent.append(
         Button("Assets/images/Btn_01.png",
                "Assets/images/Btn_hover_01.png", x_tela, y_tela,
                GameStates.Running))
     y_tela += dist_btn
     self.buttons_parent.append(
         Button("Assets/images/Btn_03.png",
                "Assets/images/Btn_hover_03.png", x_tela, y_tela,
                GameStates.Dificuldades))
     y_tela += dist_btn
     self.buttons_parent.append(
         Button("Assets/images/Btn_05.png",
                "Assets/images/Btn_hover_05.png", x_tela, y_tela,
                GameStates.Ranking))
     y_tela += dist_btn
     self.buttons_parent.append(
         Button("Assets/images/Btn_07.png",
                "Assets/images/Btn_hover_07.png", x_tela, y_tela,
                GameStates.Exit))
     for b in self.buttons_parent:
         self.game_images.append(b.game_image)
     return
Exemple #24
0
    def setGameButtons(self):
        self.endButton = Button.Button(self.screen,
                                       image="returnButton2.png",
                                       imageFloat="returnButton1.png",
                                       imageClick="buttonClick1.png",
                                       scale=0.9)
        self.peekButton = Button.Button(self.screen,
                                        image="instructionButton2.png",
                                        imageFloat="instructionButton1.png",
                                        imageClick="buttonClick1.png",
                                        scale=0.4)
        self.informationButton = Button.Button(
            self.screen,
            image="informationButton2.png",
            imageFloat="informationButton1.png",
            imageClick="buttonClick1.png",
            scale=0.4)
        self.modeButton = Button.Button(self.screen,
                                        image="modeButton2.png",
                                        imageFloat="modeButton1.png",
                                        imageClick="buttonClick1.png",
                                        scale=0.4)

        self.endButton.setPosition((30, 520))
        self.peekButton.setPosition((40, 0))
        self.informationButton.setPosition((400, 0))
        self.modeButton.setPosition((770, 0))
Exemple #25
0
    def setupButtons(self):
        # Initialize buttons
        self.previousButton = Button(self.screen, 'next', \
                                     self.directory + \
                                     self.previousImage, \
                                     Colour['GRAY'])
        self.playButton     = Button(self.screen, 'next', \
                                     self.directory + \
                                     self.playImage, \
                                     Colour['GRAY'])
        self.pauseButton    = Button(self.screen, 'next', \
                                     self.directory + \
                                     self.pauseImage, \
                                     Colour['GRAY'])
        self.stopButton     = Button(self.screen, 'next', \
                                     self.directory + \
                                     self.stopImage, \
                                     Colour['GRAY'])
        self.nextButton     = Button(self.screen, 'next', \
                                     self.directory + \
                                     self.nextImage, \
                                     Colour['GRAY'])

        # Draw Buttons
        self.drawButtons()
Exemple #26
0
def nachalo():
    start = True
    screen.fill([255, 255, 255])
    screen.blit(tel_leorio5.image, tel_leorio5.rect)
    result = cur.execute("""SELECT replik FROM text WHERE location = 3""").fetchall()
    unNoDialog = Dialog(screen)

    for elem in result:
        phrase = elem[0]
        c = 85
        if phrase == result[2][0]:
            screen.blit(tel_leorio6.image, tel_leorio6.rect)
        elif phrase == result[3][0]:
            screen.blit(tel_leorio7.image, tel_leorio7.rect)
        elif phrase == result[4][0]:
            screen.blit(tel_leorio8.image, tel_leorio8.rect)
        elif phrase == result[5][0]:
            screen.blit(tel_leorio9.image, tel_leorio9.rect)
        elif phrase == result[6][0]:  #золдики
            screen.blit(fon5.image, fon5.rect)
        name = cur.execute(f"""SELECT hero_name FROM heroes WHERE hero_id =
                            (SELECT pers FROM text WHERE replik = ("{phrase}") AND location = 3)""").fetchall()
        name = name[0]
        if len(phrase) > c:
            while phrase[:c][-1] != ' ':
                c -= 1
            first = str(name[0]) + ': ' + phrase[:c]
            unNoDialog.message = (first,
                                  phrase[c:],)
            unNoDialog.show = True
            unNoDialog.sndNext()
        else:
            first = str(name[0]) + ': ' + phrase[:c]
            unNoDialog.message = (first,)
            unNoDialog.show = True
            unNoDialog.sndNext()
    call1 = Button.Button()
    call1.create_button(screen, (124, 124, 124), 0, 500, 900 // 3, 200, 0, 'позвонить Хисоке', (255, 255, 255), 1)
    do1 = Button.Button()
    do1.create_button(screen, (124, 124, 124), 900 // 3, 500, 900 // 3, 200, 0, 'пойти к Хисоке', (255, 255, 255), 1)
    wait1 = Button.Button()
    wait1.create_button(screen, (124, 124, 124), 900 // 3 * 2, 500, 900 // 3, 200, 0, 'подождать Иллуми',
                        (255, 255, 255), 1)
    while start:
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if call1.pressed(pos):
                    start = False
                    call()
                if do1.pressed(pos):
                    start = False
                    do()
                if wait1.pressed(pos):
                    start = False
                    wait()
Exemple #27
0
    def winner(self, winner):
        """Function initiates win sequence and returns list of new fish coordinates.

        Args:
            winner: The team that has won the game ('fish' or 'shark')

        Returns:
            fishList: List of theoretical fish states and positions. Returns [] if user quits.
        """
        if self.fishButton.isActive(): self.fishButton.toggleActivation()
        if self.sharkButton.isActive(): self.sharkButton.toggleActivation()

        listOfConfetti = []
        for i in range(2):
            for j in range(3):
                listOfConfetti.append(
                    Image(Point(i * 700, j * 500),
                          'confetti.gif').draw(self.win))

        popup = GraphWin("Play Again?", 400, 400)
        popup.setBackground(color_rgb(52, 152, 219))
        playAgain = Text(Point(200, 300), "").draw(popup)

        if winner == 'fish':
            playAgain.setText(
                "The fish have won!\nShark died of starvation!\nPlay Again!")
            self.instructionsText.setText("The fish have won!")
        elif winner == 'shark':
            playAgain.setText(
                "The shark has won!\nAll the fish were eaten!\nPlay Again!")
            self.instructionsText.setText("The shark has won!")

        playAgain.setTextColor('white')
        playAgain.setSize(25)
        playAgainButton = Button(200, 140, 200, 60, 10, 'light green',
                                 "Play Again", 'white', 20, popup)
        playAgainButton.toggleActivation()

        quitButton = Button(60, 30, 100, 50, 5, 'red', "Quit", 'white', 20,
                            popup)
        quitButton.toggleActivation()
        self.quitButton.toggleActivation()

        for k in listOfConfetti:
            k.undraw()

        p = popup.getMouse()
        while not quitButton.isClicked(p):
            if playAgainButton.isClicked(p):
                popup.close()
                self.resetWin()
                fishList = self.gatherUserInput()
                return fishList
            if not popup.isClosed():
                p = popup.getMouse()

        popup.close()
        self.win.close()
        return []
Exemple #28
0
def loadWindow():
    screen.fill([245, 245, 220])
    screen.blit(menu2.image, menu2.rect)
    start = True

    count = 0
    saves = open(os.path.join('data', 'lvl.txt')).read().split()
    loc = []
    for i in saves[0:4]:
        loc.append(locations[i])
        slotText = f1.render(locations[i], True, (0, 0, 0))
        screen.blit(slotText, (300, 100 + 100 * count))
        count += 1

    screen.blit(f1.render('to go back click esc ^^', False, (0, 0, 0)),
                (0, 664))

    slot1 = Button.Button()
    slot1.create_button(screen, (90, 255, 100), 40, 100, 200, 50, 0, '1 save',
                        (68, 45, 37))

    slot2 = Button.Button()
    slot2.create_button(screen, (90, 255, 100), 40, 200, 200, 50, 0, '2 save',
                        (68, 45, 37))

    slot3 = Button.Button()
    slot3.create_button(screen, (90, 255, 100), 40, 300, 200, 50, 0, '3 save',
                        (68, 45, 37))

    slot4 = Button.Button()
    slot4.create_button(screen, (90, 255, 100), 40, 400, 200, 50, 0, '4 save',
                        (68, 45, 37))

    while start:
        clock.tick(60)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                start = False
                pygame.quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    start = False
                    startWindow()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if slot1.pressed(pygame.mouse.get_pos()):
                    start = False
                    load(loc[0])
                elif slot2.pressed(pygame.mouse.get_pos()):
                    start = False
                    load(loc[1])
                elif slot3.pressed(pygame.mouse.get_pos()):
                    start = False
                    load(loc[2])
                elif slot4.pressed(pygame.mouse.get_pos()):
                    start = False
                    load(loc[3])

    pygame.quit()
Exemple #29
0
def setup():
    global buttons, diceSound, dots

    buttons['return'] = Button('Return', [100, 65], [25, 15], '#cccccc')
    buttons['dice'] = Button('', [600, center[1]], [500, 500],
                             '#ffffff',
                             borderRadius=30)
    dots = functions.getDicePos(200, 200)
Exemple #30
0
 def __init__(self, x, y, f):
     self.x = x
     self.y = y
     self.f = f
     self.runButton = Button(self.x - 26 * self.f, self.y, "play")
     self.helpButton = Button(self.x + 2 * 26 * self.f, self.y, "help")
     self.automatic = False
     self.start()
Exemple #31
0
 def __init__(self, pos):
     speed = (GameplayConstants.fps - 30) / 5
     self.buttons = [Button.Dragbar(pygame.Rect(pos[0], pos[1], 550, 80), "Game speed", 6, speed, False),
                   Button.Dragbar(pygame.Rect(pos[0], pos[1]+90, 550, 80), "Music volume", 100, GameplayConstants.musicvolume, False),
                   Button.Dragbar(pygame.Rect(pos[0], pos[1]+180, 550, 80), "Effects volume", 100, GameplayConstants.effectsvolume, False)]
     self.drag = False
     self.pos = pos
     self.displayed = False
def menu(run):
    # instantiates the play options and quit buttons placing them relative to screen height and width (scalable)
    win, width, height = alter_window(9 / 16)
    # buttons all in terms of height and width of screen
    quit = Button.Button(int(width / 20), height * (12 / 15), int(width / 3),
                         int(height / 10), white, black, "Quit")
    play = Button.Button(int(width / 20),
                         int(height * (8 / 15)), int(width / 3),
                         int(height / 10), white, black, "Play")
    options = Button.Button(int(width / 20), int(height * (10 / 15)),
                            int(width / 3), int(height / 10), white, black,
                            "Options")
    time = pygame.time.get_ticks()
    win.fill(whiteblue)
    background(lightblue, 10, win)
    playing_music = False  # sets music playing to false but this is changed in options menu

    # checks for user input and draws buttons onto screen and based on input and performs actions based on those inputs
    while run:
        pygame.display.update()
        if (pygame.time.get_ticks() - time) % 2000 < 1000:
            win.fill(whiteblue)
            background(lightblue, 10, win)
        else:
            win.fill(lightblue)
            background(whiteblue, 10, win)
        clock.tick(144)
        run = check_events(run)[0]
        # buttons
        # play
        play.check_on_button()
        play_clicked = play.check_clicked()
        play.draw_button(win)
        if play_clicked:
            quit.draw_button(win)
            options.draw_button(win)
            pygame.display.update()
            game_loop(win, 1)

        # options
        options.check_on_button()
        options_clicked = options.check_clicked()
        options.draw_button(win)
        if options_clicked:
            quit.draw_button(win)
            playing_music = options_menu(playing_music, win)

        # quit
        quit.check_on_button()
        quit_clicked = quit.check_clicked()
        quit.draw_button(win)

        # event actors
        if quit_clicked:
            pygame.display.update()
            run = False
    return run
Exemple #33
0
    def __init__(
        self,
        text,
        handler=None,
        handler_message=None,
        default_choice=0,
        x=None,
        y=None,
        width=0,
        height=0,
        icon=None,
        vertical_expansion=1,
        text_prop=None,
        parent="osd",
    ):
        """
        Initialise an instance of a ConfirmBox

        @ivar text: String to print.
        @ivar handler: Handler call-back for the box
        @ivar handler_message: If 'handler_message' is set, the box will transform
          into a normal pop-up showing this text while 'handler' is called and will
          destroy itself after that.
        @ivar x: x coordinate. Integer
        @ivar y: y coordinate. Integer
        @ivar width: Integer
        @ivar height: Integer
        @ivar icon: icon
        @ivar text_prop: A dict of 4 elements composing text proprieties::

                  { 'align_h': align_h, 'align_v': align_v, 'mode': mode, 'hfill': hfill }
                     align_v = text vertical alignment
                     align_h = text horizontal alignment
                     mode    = hard (break at chars); soft (break at words)
                     hfill   = True (don't shorten width) or False
        """

        PopupBox.__init__(self, text, handler, x, y, width, height, icon, vertical_expansion, text_prop, parent)

        self.handler_message = handler_message

        # XXX: It may be nice if we could choose between
        #      OK/CANCEL and YES/NO

        self.b0 = Button(_("OK"), width=(self.width - 60) / 2)
        self.b0.set_h_align(Align.NONE)
        self.add_child(self.b0)

        self.b1 = Button(_("CANCEL"), width=(self.width - 60) / 2)
        self.b1.set_h_align(Align.NONE)
        self.add_child(self.b1)
        select = "self.b%s.toggle_selected()" % default_choice
        eval(select)
 def setupColorButtons(self):
     """Initializes all the color buttons"""
     allColors = (QColor.White, QColor.Black, QColor.LightGray, QColor.Red, QColor.Yellow,
                  QColor.Green, QColor.Cyan, QColor.Blue, QColor.Magenta)
     px = self.extent[0] - 36
     py = (self.extent[1] - len(allColors) * 32) // 2
     for color in allColors:
         box = QRect(px, py, 32, 32)
         button = Button(box, None, color, False)
         button.action = self.activateColor
         button.argument = color.rgba
         self.buttons.append(button)
         py = py + 31
    def create_new_user(self,db):
        win = GraphWin("Create new user",300,300)
        win.setCoords(0,0,100,100)
        Text(Point(20,60),"User: "******"Password: "******"")
        message.draw(win)

        # Create a create button and a quit button
        new_button = Button("Create",Point(5,15),Point(25,25))
        new_button.draw(win)

        quit_button = Button("Quit",Point(35,15),Point(55,25))
        quit_button.draw(win)

        while True:
            p = win.getMouse()
            if new_button.clicked(p):
                player = Player(user_entry.getText(),password_entry.getText())
                db.addPlayer(player)
                db.write()
                win.close()
                break
            elif quit_button.clicked(p):
                win.close()
                break
Exemple #36
0
class IOManager(object):
    def __init__(self):
        led = 11
        button = 13
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led, GPIO.OUT)

        self.__scanner = Scanner()
        self.__button = Button(button)
        self.__led = LED(led)
        self.__printer = Printer()
        #set up connections and variables for button, light, printer, and scanner
    def getButton(self):
        return self.__button.getButtonBool()

    def getScan(self):
        return self.__scanner.getInput()

    def setLight(self, value):
        self.__led.setValue(value)

    def blinkLight(self):
        self.__led.blink()
        
    def printReceipt(self, items):
        if items:
            self.__printer.printHeader()
            for item in items:
                self.__printer.printItem(item)
            self.__printer.printTotals(items)
            self.__printer.complete()
Exemple #37
0
    def __init__(self, text, handler=None, x=None, y=None, width=0, height=0,
                 icon=None, vertical_expansion=1, text_prop=None, parent='osd'):
        """
        Initialise an instance of a AlertBox

        @ivar text: String to print.
        @ivar x: x coordinate. Integer
        @ivar y: y coordinate. Integer
        @ivar width: Integer
        @ivar height: Integer
        @ivar icon: icon
        @ivar text_prop: A dict of 4 elements composing text proprieties:
          { 'align_h': align_h, 'align_v': align_v, 'mode': mode, 'hfill': hfill }:
            - align_v = text vertical alignment
            - align_h = text horizontal alignment
            - mode    = hard (break at chars); soft (break at words)
            - hfill   = True (don't shorten width) or False
        """

        PopupBox.__init__(self, text, handler, x, y, width, height,
                          icon, vertical_expansion, text_prop, parent)

        self.b1 = Button(_('OK'))
        self.b1.toggle_selected()

        self.add_child(self.b1)
Exemple #38
0
    def __initUI(self):
        self.parent.title("Sudoku")
        self.pack(fill=BOTH)
        self.canvas = Canvas(self,
                             width=WIDTH,
                             height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Clear answers",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_puzzle()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)
Exemple #39
0
class AlertBox(PopupBox):
    """
    """
    def __init__(self, text, handler=None, x=None, y=None, width=0, height=0,
                 icon=None, vertical_expansion=1, text_prop=None, parent='osd'):
        """
        Initialise an instance of a AlertBox

        @ivar text: String to print.
        @ivar x: x coordinate. Integer
        @ivar y: y coordinate. Integer
        @ivar width: Integer
        @ivar height: Integer
        @ivar icon: icon
        @ivar text_prop: A dict of 4 elements composing text proprieties:
          { 'align_h': align_h, 'align_v': align_v, 'mode': mode, 'hfill': hfill }:
            - align_v = text vertical alignment
            - align_h = text horizontal alignment
            - mode    = hard (break at chars); soft (break at words)
            - hfill   = True (don't shorten width) or False
        """

        PopupBox.__init__(self, text, handler, x, y, width, height,
                          icon, vertical_expansion, text_prop, parent)

        self.b1 = Button(_('OK'))
        self.b1.toggle_selected()

        self.add_child(self.b1)


    def eventhandler(self, event):
        if event in (INPUT_ENTER, INPUT_EXIT) or \
            (event == MOUSE_BTN_PRESS and self.b1.rect.collidepoint(event.pos)):
            self.destroy()
            if self.handler:
                self.handler()
            return True

        elif event == MOUSE_BTN_PRESS and event.button == 3:
            self.destroy()
            return True

        return False
Exemple #40
0
    def __init__(self):
        led = 11
        button = 13
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led, GPIO.OUT)

        self.__scanner = Scanner()
        self.__button = Button(button)
        self.__led = LED(led)
        self.__printer = Printer()
Exemple #41
0
	def read_buttons(self, file):
		button_num = int(file.readline().strip().split(' ')[1])

		for i in range(button_num):
			button_type = file.readline().strip().replace('#', '')
			image_id = list(map(int, file.readline().strip().split(' ')[1:]))
			button = Button()
			button.init(ResourceManager.instance().image_path_list[image_id[0]], ResourceManager.instance().image_path_list[image_id[1]])
			button.translate(*map(int, file.readline().strip().split(' ')[1:]))
			button.set_type(button_type)
			self.button_list.append(button)
			self.all_object_list.add(button)
def newGame():
    if (DEBUG):
        print "Welcome to Chess!"
    
    pygame.init() #initialize all imported pygame modules

    window_size = [1000, 650] # width, height
    screen = pygame.display.set_mode(window_size)

    updateText(screen, "Welcome to Chess!")
    pygame.display.set_caption("Colleen's Chess")

    buttons = pygame.sprite.RenderPlain()
    buttons = Button.makeButton(buttons, screen, "Quit", Button.ButtonType.Quit, white, black)
    Button.makeButton(buttons, screen, "Castle", Button.ButtonType.Castle, green, white)

    board = Board()

    turnCount = 0

    clock = pygame.time.Clock()

    mainLoop(screen, board, turnCount, clock, buttons, False)
    def change_password(self,db):        
        win = GraphWin("Change Password",300,300)
        win.setCoords(0,0,100,100)
        Text(Point(20,80),"User: "******"Old Password: "******"New password: "******"")
        message.draw(win)

        # Create a create button and a quit button
        change_button = Button("Change",Point(5,15),Point(25,25))
        change_button.draw(win)

        quit_button = Button("Quit",Point(35,15),Point(55,25))
        quit_button.draw(win)

        while True:
            p = win.getMouse()
            if change_button.clicked(p):
                player = db.get_user(user_entry.getText())
                if player == None:
                    message.setText("User invalid")
                elif player.getPassword() != password_entry.getText():
                    message.setText("Old password incorrect")
                else:
                    player.setPassword(password_entry2.getText())
                    db.write()
                    win.close()
                    return
            elif quit_button.clicked(p):
                win.close()
                return
        screen.fill(RED)
        font = pygame.font.Font(None, 100)
        text = font.render("YOU SUCK!", True, YELLOW)
        screen.blit(text, [150,200])
        pygame.display.flip()
        pygame.time.wait(1000)
        Lose = False


    if again:
        screen.fill(BLUE)
        font = pygame.font.Font(None, 100)
        text = font.render("AGAIN?",True,YELLOW)
        screen.blit(text,[210,50])

        Yes = Button(ORANGE,"YES",GREEN,[50,200,200,100])
        No = Button(ORANGE,"NO", RED, [450,200,200,100])

        Yes.draw(screen)
        No.draw(screen)

    for event in pygame.event.get():
        if event.type == pygame.QUIT: # If user clicked close
                again = False

        elif pygame.mouse.get_pressed()[0]:

            if Yes.get_click():
                done = False
                Knight.back_to_life()
                Dragon.back_to_life()
Exemple #45
0
	def Menu_A(self):
		Arch = self.profile.Return_Achie()
		#carrega imagens
		btn_general = Button(0)
		btn_voltar = Button(0)
		btn_red_e = Button(1)
		btn_red_d = Button(1)
		btn_list_text = []
		btn_list_text.append(self.Old_English_25.render(self.lang.Get(1), False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render("<", False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render(">", False, (226, 157, 54) ))
		bkg = pygame.image.load("Graphics/Screens/Achievment.jpg")
		selected = pygame.image.load("Graphics/Boxes/Selected.jpg")
		unselected = pygame.image.load("Graphics/Boxes/Unselected.jpg")
		#inicia variaveis
		qtd = 0
		pag_atual = 0
		lado = 0
		msc_atual = 0
		aux = 0
		limit = 0

		list,qtd = Arch.return_table()
		esq = []
		dir = []
		tam = qtd[pag_atual]
		voltar = False
		score_aux =score_number = 0
		
		#LACO DO MENU 1
		while (voltar == False):
			esq = []
			dir = []
			#CALCULA QUAIS PAGINAS MOSTRAR
			if ( pag_atual > len(qtd)):
				 pag_atual = 0
			if pag_atual < len(qtd):
				if pag_atual == 0:
					score_number= i = 0
					limit =qtd[pag_atual]
				else:
					score_number =i = qtd[pag_atual-1]
				while i < qtd[pag_atual]:
					esq.append(self.Carolingia_20.render(self.lang.Get(28+i), False, (255*(1-list[i][1]),0,0) ))
					i+=1
			if pag_atual +1 < len(qtd):
				i = qtd[pag_atual]
				while i <qtd[pag_atual+1]:
					dir.append(self.Carolingia_20.render(self.lang.Get(28+i), False, (255*(1-list[i][1]),0,0) ))
					i+=1
			
			sair = mudar = False
			score_aux = score_number
			#LACO DO MENU 2
			while (sair == False):
				score_number = score_aux
				#PEGA EVENTOS
				for evento in pygame.event.get():
					#EVENTOS DO MOUSE
					if evento.type == pygame.MOUSEBUTTONUP:
						if Bleft == True:
							px , py = pygame.mouse.get_pos()
							if ((px>= 80)and (px<=105)) and ((py>= 462)and (py<=487)):
								msc_atual = 0
								if lado == 0:
									pag_atual -=2
									if pag_atual < -2:
										pag_atual = 4
										lado = 1
									sair = mudar = True
								else:
									lado = 0
									tam = len(dir)
							if ((px>= 695)and (px<=720)) and ((py>= 462)and (py<=487)):
								msc_atual = 0
								if lado == 1:
									pag_atual +=2
									if pag_atual == 6:
										pag_atual = 0
										lado = 0
									sair = mudar = True
								else:
									lado = 1
									tam = len(esq)
							#if ((px>= 50)and (px<=250)) and ((py>= 510)and (py<=560)):
							#	sair = True
							if ((px>= 530)and (px<=730)) and ((py>= 510)and (py<=560)):
								btn_voltar.click()
								voltar = sair = True


							aux = Const_default_y
							for i in range(len(esq)):
								if ((px>= 65)and (px<=397)) and ((py>= aux)and (py<=aux+25)):
									if (lado == 0)  and (msc_atual == ((aux - Const_default_y)/30)):
										sair = True
									else:
										msc_atual = int ((aux - Const_default_y)/30)
										lado = 0
								aux+=30

							aux = Const_default_y
							for i in range(len(dir)):
								if ((px>= 415)and (px<=747)) and ((py>= aux)and (py<=aux+25)):
									if (lado == 1)  and (msc_atual == ((aux - Const_default_y)/30)):
										sair = True
									else:
										msc_atual = int ((aux - Const_default_y)/30)
										lado = 1
								aux+=30
							Bleft == False
					if evento.type == pygame.MOUSEBUTTONDOWN:
						Bleft,Bmiddle, Bright =  pygame.mouse.get_pressed()
					if evento.type == pygame.QUIT:
						sys.exit(0)
					#EVENTOS DO TECLADO
					if evento.type == pygame.KEYDOWN:
						if evento.key == pygame.K_RETURN:
							sair = True
						if evento.key == pygame.K_ESCAPE:
							return False
							msc_atual = -1
						if evento.key == pygame.K_LEFT:
							msc_atual = 0
							if lado == 0:
								pag_atual -=2
								if pag_atual == -2:
									pag_atual = 2
									lado = 0
								sair = mudar = True
							else:
								lado = 0
								tam = len(esq)
						if evento.key == pygame.K_RIGHT:
							msc_atual = 0
							if lado == 1:
								pag_atual +=2
								if pag_atual == 4:
									pag_atual = 0
									lado = 0
								sair = mudar = True
							else:
								lado = 1
								tam = len(dir)
								if pag_atual == 4:
									pag_atual = 0
									lado = 0
						if evento.key == pygame.K_DOWN:
							msc_atual += 1
							if msc_atual > tam-1:
								msc_atual = 0
						if evento.key == pygame.K_UP:
							msc_atual -= 1
							if msc_atual < 0:
								msc_atual = tam-1

				#Desenha Fundo
				self.tela.blit(bkg,(0,0))
				#Escreve Numero das paginas esquerda e direita
				self.tela.blit(self.Carolingia_20.render((repr(pag_atual+1)), False, (226, 157, 54) ),(230,128))
				self.tela.blit(self.Carolingia_20.render((repr(pag_atual+2)), False, (226, 157, 54) ),(590,128))
				#self.tela.blit(self.Carolingia_25.render(self.lang.Get(19), False, (226, 157, 54) ),(70,520))
				self.tela.blit(self.Carolingia_25.render(self.lang.Get(1), False, (226, 157, 54) ),(576,520))
				#self.tela.blit(self.Carolingia_25.render(("Achivments \o/:  "), False, (226, 157, 54) ),(0,0))
				#Desenha botoes
				self.tela.blit(btn_general.desenha(),(70,510))
				self.tela.blit(btn_red_e.desenha(),(280,500))
				self.tela.blit(btn_red_d.desenha(),(450,500))
				self.tela.blit(btn_voltar.desenha(),(530,510))
				#escreve texto dos botoes
				#self.tela.blit(btn_list_text[0],(90,520))
				self.tela.blit(btn_list_text[1],(310,520))
				self.tela.blit(btn_list_text[2],(480,520))
				self.tela.blit(btn_list_text[0],(600,520))
				#ESCREVE ITENS DA PAGINA ESQUERDA
				if (len(esq) > len(dir)):
					num = len(esq)
				else:
					num = len(dir)
				num2 = (-1)*(num/2)
				for i in range(len(esq)):
					aux = Const_default_y+(num2*30)
					num2 += 1
					if (lado == 0):
						if (i == msc_atual):
							self.tela.blit(selected,(60,aux-2))
						else:
							self.tela.blit(unselected,(60,aux-2))
					else:
						self.tela.blit(unselected,(60,aux-2))
					self.tela.blit(esq[i],(65,aux))
					#self.tela.blit(self.Carolingia_20.render((repr((self.profile.Get_V()[score_number])[1])), False, (226, 157, 54) ),(330,aux))
					score_number+=1
				#ESCREVE ITENS DA PAGINA DIREITA
				num2 = (-1)*(num/2)
				for i in range(len(dir)):
					aux = Const_default_y+(num2*30)
					num2 += 1
					if (lado == 1):
						if (i == msc_atual):
							self.tela.blit(selected,(410,aux-2))
						else:
							self.tela.blit(unselected,(410,aux-2))
					else:
						self.tela.blit(unselected,(410,aux-2))
					self.tela.blit(dir[i],(415,aux))
					#self.tela.blit(self.Carolingia_20.render((repr((self.profile.Get_V()[score_number])[1])), False, (226, 157, 54) ),(700,aux))
					score_number+=1
				#DESENHA O MOUSE
				self.tela.blit(self.cursor_picture, pygame.mouse.get_pos())
				#atualiza a tela
				pygame.display.flip()
				if btn_voltar.getState():
					time.sleep(0.2)
def mainLoop(screen, board, turnCount, clock, buttons, done):
    board.squares.draw(screen) #draw Sprites (Squares)
    if board.border != None:
        pygame.draw.rect(screen, red, board.border, BORDER_THICKNESS)
    board.piecesOnBoard.draw(screen) #draw Sprites (Pieces)
    pygame.display.flip() #update screen
    
    if done == True:
        #Button.makeButton(buttons, screen, "Play Again", Button.ButtonType.PlayAgain, blue, white)
        while done == True:
            for e in pygame.event.get():
                if e.type == pygame.QUIT: #user clicks close
                    if (DEBUG):
                        print "Close clicked"
                    done = True
                elif e.type == pygame.MOUSEBUTTONUP:               
                    x, y = e.pos
                    clickedButton = Button.clicked(buttons, e.pos)
                    if (clickedButton != False):
                        if (clickedButton.ButtonType == Button.ButtonType.Quit):
                            clickedButton.kill()
                            makeButton(buttons, screen, "Play Again", Button.ButtonType.PlayAgain, blue, white)
                        elif (clickedButton.ButtonType == Button.ButtonType.PlayAgain):
                            newGame()
                        else:
                            print "no button type"
        #again = raw_input("Would you like to play again? If yes, type 'yes'\n")
        #if again == 'yes':
        #    newGame()
    while done == False:
        currentMouseOverSquare = board.mouseOverSquare
        currentLoc = None
        for e in pygame.event.get():
            if e.type == pygame.QUIT: #user clicks close
                if (DEBUG):
                    print "Close clicked"
                done = True
            elif e.type == pygame.MOUSEBUTTONUP:               
                x, y = e.pos
                clickedButton = Button.clicked(buttons, e.pos)
                if (clickedButton != False):
                    if (clickedButton.ButtonType == Button.ButtonType.Quit):
                        clickedButton.kill()
                        castleButton = buttons.sprites()[0]
                        buttons.empty() # takes castle button out of list, but it's still showing
                        pygame.draw.rect(screen, black, castleButton.rect) # draws black over where the castle button used to be
                        Button.makeButton(buttons, screen, "Play Again", Button.ButtonType.PlayAgain, blue, white)
                        updateText(screen, "Do you want to play again?")
                        mainLoop(screen, board, turnCount, clock, buttons, True)
                    elif (clickedButton.ButtonType == Button.ButtonType.PlayAgain):
                        newGame() #sets done=False, emptys buttons (and puts new quit button in)
                    else:
                        print "no button type"
                row = get_row_from_mouse_y(y)
                col = get_col_from_mouse_x(x)
                currentLoc = colStr(col)+str(row)
                if currentLoc in board.squareDic.keys():
                    if board.selectedPiece == None:
                        board.selectedPiece = board.squareDic[currentLoc].piece
                        board.border = board.squareDic[currentLoc].get_rect()
                    elif (board.selectedPiece.row == str(row) and board.selectedPiece.col == colStr(col)):
                        
                        board.border = None
                        board.selectedPiece = None
                    else:
                        oldLocation = board.selectedPiece.row + "," + board.selectedPiece.col
                        newLocation = str(row) + "," + str(colStr(col))
                        if (DEBUG):
                            print oldLocation #new location
                            print newLocation #old location
                        madeMove, exp = makeMove(screen, board, colStr(col), str(row), turnCount, clock)
                        # returns (bool, string explaination )

                        if madeMove:
                            if (DEBUG):
                                print "made move"
                                print exp
                            if turnCount%2==0:
                                turnColor = 'black'
                            else:
                                turnColor = 'white'
                            if 'Game Over' in exp:
                                updateText(screen, exp)

                                buttons.empty() # takes buttons out of list
                                Button.makeButton(buttons, screen, "Play Again", Button.ButtonType.PlayAgain, blue, white)
                                mainLoop(screen, board, turnCount, clock, buttons, True)

                            else:     
                                updateText(screen, turnColor + " moved from " + oldLocation + " to " + newLocation)
                                turnCount +=1
                                board.border = None
                                board.selectedPiece = None
                                for hSquare in board.highlightedSquares:
                                    hSquare.un_highlight() # unhighlight old possible moves
                        else: #error
                            print "exp: " + exp
                            if (DEBUG):
                                print exp
                            updateText(screen, exp)
                
            elif e.type == pygame.MOUSEMOTION:
                x, y = e.pos
                row = get_row_from_mouse_y(y)
                col = get_col_from_mouse_x(x)
                currentLoc = colStr(col)+str(row)

            if currentLoc in board.squareDic.keys():
                    board.mouseOverSquare = board.squareDic[currentLoc]
                    
            if board.mouseOverSquare != currentMouseOverSquare: # hovering over new square
                if board.selectedPiece == None:
                    for hSquare in board.highlightedSquares:
                        hSquare.un_highlight() # unhighlight old possible moves
                    if isinstance(board.mouseOverSquare, Square):
                        board.highlight_legal_moves()
                        # ^ highlight new available moves

        board.squares.draw(screen) #draw Sprites (Squares)

        if board.border != None:
            pygame.draw.rect(screen, red, board.border, BORDER_THICKNESS)
        
        board.piecesOnBoard.draw(screen) #draw Sprites (Pieces)
        
        labelSquares(screen) # displays letters for columns and numbers for rows

        pygame.display.flip() #update screen

        clock.tick(5)

    pygame.quit() #closes things, keeps idle from freezing
    sys.exit()
# Draws the smallest circle that encloses a list of points
# By David Pick

from graphics import *
from Button import *
from math import *

WIN_HEIGHT = 400
WIN_WIDTH = 500
pointList = []
win = GraphWin("Smallest Enclosing Circle", WIN_HEIGHT, WIN_WIDTH)
b1 = Button(win, "Draw Circle", Point(150, 300), 20, 10)
b1.enable() 
b2 = Button(win, "Exit", Point(350, 300), 20, 10)  
b2.enable() 

def drawEnclosingCircle(center, radius):
    """Uses the center point (center) and radius of the enclosing circle to 
    draw the circle.  Display the center poing so that it looks different from
    all other points"""
    circle = Circle(center, radius)
    circle.draw(win)
def smallestEnclosingCircle(plist):
    """returns the center and radius of the smallest circle that has one
    of the points in plist (the list of points) as its center, and all of 
    the points in plist on its boundary or in its interior.  """
    # TO DO: complete this function, change the return statement to reflect what
    # what needs to be returned.
    maxpoint = pointList[0]
    Distance1 = 0
    Distance2 = 0
def ler(tela,lang):
    btn_salvar = Button(0)
    btn_cancelar = Button(0)
    ct =0
    capslock =0
    b = ""
    aux = ''
    cursor_picture = pygame.image.load('Graphics/Mouse/Batuta.png').convert_alpha()
    fonte = pygame.font.Font("Data/Carolingia.ttf", 25)
    flag =0
    bkg = pygame.image.load("Graphics/Screens/Create.jpg")
    tela.blit(bkg,(0,0))
    tela.blit(fonte.render(("Create Profile:  "), False, (226, 157, 54) ),(0,0))
    pygame.display.flip()
    while (flag == 0):
        tela.blit(bkg,(0,0))
        tela.blit(fonte.render(("Create Profile:  "), False, (226, 157, 54) ),(0,0))
        for evento in pygame.event.get():
            if evento.type == pygame.MOUSEBUTTONUP:
                if Bleft == True:
                    px , py = pygame.mouse.get_pos()
                    #botao salvar
                    if ((px>= 70)and (px<=270)) and ((py>= 510)and (py<=560)):
                        flag = 1
                        return (b)
                    #botao cancelar
                    if ((px>= 530)and (px<=730)) and ((py>= 510)and (py<=560)):
                        flag = 1
                        b = '#'
                        btn_cancelar.click()
                    Bleft == False
            if evento.type == pygame.MOUSEBUTTONDOWN:
                Bleft,Bmiddle, Bright =  pygame.mouse.get_pressed()
            if evento.type == pygame.QUIT:
                sys.exit()
            if evento.type == pygame.KEYDOWN:
                if evento.key == pygame.K_ESCAPE:
                    flag = 1
                    b = '#'
                if evento.key == pygame.K_RETURN:
                    if (len(b) > 0):
                        flag = 1
                        return (b)
                # pega letras minusculas
                if (evento.key>= 97 and evento.key<=122):
                    aux =chr(evento.key)
                    ct = 1
                # pega letras maiusculas
                if (evento.key>= 65 and evento.key<=90):
                    aux =chr(evento.key)
                    ct = 1
                if evento.key == pygame.K_BACKSPACE:
                    if (len(b) > 0):
                        b = b[:-1]
            if (ct > 0):
                ct =0
                if (len(b) < 15):
                    if (capslock == 1):
                        b = b +aux.upper()
                    else:
                        b = b +aux
            #DESENHA O MOUSE
            tela.blit(cursor_picture, pygame.mouse.get_pos())
            tela.blit(fonte.render(b, False, (226, 157, 54) ),(265,300))
            #Desenha botoes
            tela.blit(btn_salvar.desenha(),(70,510))
            tela.blit(btn_cancelar.desenha(),(530,510))
            tela.blit(fonte.render(lang.Get(16), False, (226, 157, 54) ),(70,520))
            tela.blit(fonte.render(lang.Get(17), False, (226, 157, 54) ),(576,520))
            pygame.display.flip()
            if btn_salvar.getState() or btn_cancelar.getState():
                time.sleep(0.2)
    return (b)
Exemple #49
0
    def run(self):
        mainloop = True
        
        on = self.screen.blit(self.dummy, (-1,0))
        off = self.screen.blit(self.dummy, (-1,0))
        bbg = self.screen.blit(self.dummy, (-1,0))
        bbh = self.screen.blit(self.dummy, (-1,0))
        bp2 = self.screen.blit(self.dummy, (-1,0))
        bp3 = self.screen.blit(self.dummy, (-1,0))
        bp4 = self.screen.blit(self.dummy, (-1,0))
        bpr = self.screen.blit(self.dummy, (-1,0))
        bpb = self.screen.blit(self.dummy, (-1,0))
        bpg = self.screen.blit(self.dummy, (-1,0))
        bpy = self.screen.blit(self.dummy, (-1,0))
        bst = self.screen.blit(self.dummy, (-1,0))
        throw_dice = self.screen.blit(self.dummy, (-1,0))
        throw_dice_fight = self.screen.blit(self.dummy, (-1,0))
        sc1 = self.screen.blit(self.dummy, (-1,0))
        sc2 = self.screen.blit(self.dummy, (-1,0))
        sc3 = self.screen.blit(self.dummy, (-1,0))
        bsg = self.screen.blit(self.dummy, (-1,0))
        bai = self.screen.blit(self.dummy, (-1,0))
        bsb = self.screen.blit(self.dummy, (-1,0))
        bfs = self.screen.blit(self.dummy, (-1,0))
        ai1 = Button(FONT_TEXT.render('Easy', 1, BLACK), self.screen, (SIZE[0] / 10 + 120, SIZE[1] / 10 + (LINE_OFFSET * 2)),0,1)
        ai2 = Button(FONT_TEXT.render('Easy', 1, BLACK), self.screen, (SIZE[0] / 10 + 120, SIZE[1] / 10 + (LINE_OFFSET * 3)),0,1)
        ai3 = Button(FONT_TEXT.render('Easy', 1, BLACK), self.screen, (SIZE[0] / 10 + 120, SIZE[1] / 10 + (LINE_OFFSET * 4)),0,1)
        ai4 = Button(FONT_TEXT.render('Easy', 1, BLACK), self.screen, (SIZE[0] / 10 + 120, SIZE[1] / 10 + (LINE_OFFSET * 5)),0,1)
        ai1h = Button(FONT_TEXT.render('Hard', 1, BLACK), self.screen, (SIZE[0] / 10 + 185, SIZE[1] / 10 + (LINE_OFFSET * 2)),0,2)
        ai2h = Button(FONT_TEXT.render('Hard', 1, BLACK), self.screen, (SIZE[0] / 10 + 185, SIZE[1] / 10 + (LINE_OFFSET * 3)),0,2)
        ai3h = Button(FONT_TEXT.render('Hard', 1, BLACK), self.screen, (SIZE[0] / 10 + 185, SIZE[1] / 10 + (LINE_OFFSET * 4)),0,2)
        ai4h = Button(FONT_TEXT.render('Hard', 1, BLACK), self.screen, (SIZE[0] / 10 + 185, SIZE[1] / 10 + (LINE_OFFSET * 5)),0,2)
        players = Empty()

        sound = True
        fullscreen = False

        self.screen.fill(self.bg_color)
        self.screen.blit(pygame.transform.scale(self.bg, (self.scr_height,self.scr_height)),(self.bgoffset,0))
        
        bs = Button(FONT.render('Start', 1, FONT_COLOR), self.screen, 0,-1)
        bh = Button(FONT.render('How to play', 1, FONT_COLOR), self.screen, 0,0)
        bss = Button(FONT.render('Settings', 1, FONT_COLOR), self.screen, 0,1)
        bc = Button(FONT.render('Exit', 1, FONT_COLOR), self.screen, 0,2)

        while mainloop:
            self.clock.tick(9)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    mainloop = False
            #Back to menu button
            ButtonHover(self.screen,self.curpage,bbg,'Game','Back to menu',FONT_TEXT,(23*TILESIZE,0.2*TILESIZE))
            #Back buttons hover
            ButtonHover(self.screen,self.curpage,bbh,'HelpMenu','Back',FONT,0,3)
            ButtonHover(self.screen,self.curpage,bbh,'PlayerSelect','Back',FONT,0,5)
            #Start button hover
            ButtonHover(self.screen,self.curpage,bs,'Menu','Start',FONT,0,-1)
            #How to play hover
            ButtonHover(self.screen,self.curpage,bh,'Menu','How to play',FONT,0,0)
            #Exit button
            ButtonHover(self.screen,self.curpage,bc,'Menu','Exit',FONT,0,2)
            #Play again button hover
            ButtonHover(self.screen,self.curpage,bsg,'Winning_screen','Play again',FONT,0,3)
            #Settings Hover
            ButtonHover(self.screen,self.curpage,bss,'Menu','Settings',FONT,0,1)
            #Settings Hover
            ButtonHover(self.screen,self.curpage,bsb,'Settings','Back',FONT,0,3)

            aiPlayerCheckList = players

            if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1) or (not aiPlayerCheckList.Filter(lambda x : x.Turn and x.AI > 0).IsEmpty):
                pos = pygame.mouse.get_pos()

                if self.curpage == 'Turn2':
                    if aiPlayerCheckList.Filter(lambda x : x.Turn and x.AI > 0).IsEmpty:
                        if sc1.collidepoint(pos):
                            try:
                                player_stats
                            except NameError:
                                player_stats = False
                            if not player_stats:
                                player_stats = ScoreBtn(sc1, self.screen, dicenumber2, players)
                            else:
                                self.curpage = ScoreBtn(sc1, self.screen, dicenumber2, players, player_stats)
                                player_stats = False
                        elif sc2.collidepoint(pos):
                            try:
                                player_stats
                            except NameError:
                                player_stats = False
                            if not player_stats:
                                player_stats = ScoreBtn(sc1, self.screen, dicenumber2, players)
                            else:
                                self.curpage = ScoreBtn(sc1, self.screen, dicenumber2, players, player_stats)
                                player_stats = False
                        elif sc3.collidepoint(pos):
                            try:
                                player_stats
                            except NameError:
                                player_stats = False
                            if not player_stats:
                                player_stats = ScoreBtn(sc1, self.screen, dicenumber2, players)
                            else:
                                self.curpage = ScoreBtn(sc1, self.screen, dicenumber2, players, player_stats)
                                player_stats = False
                    else:
                        #ai hier i guess
                        print('AI')

                if self.curpage == 'PlayerSelect':
                    if ai1.collidepoint(pos):
                        if not len(self.pc1) == 2:
                            self.pc1.append(1)
                    if ai2.collidepoint(pos):
                        if not len(self.pc2) == 2:
                            self.pc2.append(1)
                    if ai3.collidepoint(pos):
                        if not len(self.pc3) == 2:
                            self.pc3.append(1)
                    if ai4.collidepoint(pos):
                        if not len(self.pc4) == 2:
                            self.pc4.append(1)
                    if ai1h.collidepoint(pos):
                        if not len(self.pc1) == 2:
                            self.pc1.append(2)
                    if ai2h.collidepoint(pos):
                        if not len(self.pc2) == 2:
                            self.pc2.append(2)
                    if ai3h.collidepoint(pos):
                        if not len(self.pc3) == 2:    
                            self.pc3.append(2)
                    if ai4h.collidepoint(pos):
                        if not len(self.pc4) == 2:
                            self.pc4.append(2)
                    if len(self.players) == 2:
                        if self.pc1[0] == '-1' and self.pc2[0] == '-2' and self.pc3[0] == '-3' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpy.Value]
                        elif self.pc2[0] == '-2' and not self.pc1[0] == '-1' and self.pc3[0] == '-3' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpr.Value:
                                self.pc2 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpb.Value:
                                self.pc2 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpg.Value:
                                self.pc2 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpy.Value:
                                self.pc2 = [bpy.Value]
                        CheckPlayers(self.screen, [self.pc1, self.pc2])
                        if not self.pc1[0] == '-1' and not self.pc2[0] == '-2':
                            self.players = [self.pc1,self.pc2]
                            bst = Button(FONT.render('Play', 1, FONT_COLOR), self.screen, 0,2)
                    elif len(self.players) == 3:
                        if self.pc1[0] == '-1' and self.pc2[0] == '-2' and self.pc3[0] == '-3' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpy.Value]
                        elif self.pc2[0] == '-2' and not self.pc1[0] == '-1' and self.pc3[0] == '-3' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpr.Value:
                                self.pc2 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpb.Value:
                                self.pc2 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpg.Value:
                                self.pc2 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpy.Value:
                                self.pc2 = [bpy.Value]
                        elif self.pc3[0] == '-3' and not self.pc1[0] == '-1' and not self.pc2[0] == '-2' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpr.Value and not self.pc2[0] == bpr.Value:
                                self.pc3 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpb.Value and not self.pc2[0] == bpb.Value:
                                self.pc3 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpg.Value and not self.pc2[0] == bpg.Value:
                                self.pc3 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpy.Value and not self.pc2[0] == bpy.Value:
                                self.pc3 = [bpy.Value]
                        CheckPlayers(self.screen, [self.pc1, self.pc2, self.pc3])
                        if not self.pc1[0] == '-1' and not self.pc2[0] == '-2' and not self.pc3[0] == '-3':
                            self.players = [self.pc1,self.pc2, self.pc3]
                            bst = Button(FONT.render('Play', 1, FONT_COLOR), self.screen, 0,2)
                    elif len(self.players) == 4:
                        if self.pc1[0] == '-1' and self.pc2[0] == '-2' and self.pc3[0] == '-3' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect':
                                self.pc1 = [bpy.Value]
                        elif self.pc2[0] == '-2' and not self.pc1[0] == '-1' and self.pc3[0] == '-3' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpr.Value:
                                self.pc2 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpb.Value:
                                self.pc2 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpg.Value:
                                self.pc2 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpy.Value:
                                self.pc2 = [bpy.Value]
                        elif self.pc3[0] == '-3' and not self.pc1[0] == '-1' and not self.pc2[0] == '-2' and self.pc4[0] == '-4':
                            if bpr.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpr.Value and not self.pc2[0] == bpr.Value:
                                self.pc3 = [bpr.Value]
                            elif bpb.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpb.Value and not self.pc2[0] == bpb.Value:
                                self.pc3 = [bpb.Value]
                            elif bpg.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpg.Value and not self.pc2[0] == bpg.Value:
                                self.pc3 = [bpg.Value]
                            elif bpy.collidepoint(pos) and self.curpage == 'PlayerSelect' and not self.pc1[0] == bpy.Value and not self.pc2[0] == bpy.Value:
                                self.pc3 = [bpy.Value]
                        elif self.pc4[0] == '-4' and not self.pc1[0] == '-1' and not self.pc2[0] == '-2' and not self.pc3[0] == '-3':
                            if not self.pc1[0] == bpr.Value and not self.pc2[0] == bpr.Value and not self.pc3[0] == bpr.Value:
                                self.pc4 = [bpr.Value]
                            elif not self.pc1[0] == bpb.Value and not self.pc2[0] == bpb.Value and not self.pc3[0] == bpb.Value:
                                self.pc4 = [bpb.Value]
                            elif not self.pc1[0] == bpg.Value and not self.pc2[0] == bpg.Value and not self.pc3[0] == bpg.Value:
                                self.pc4 = [bpg.Value]
                            elif not self.pc1[0] == bpy.Value and not self.pc2[0] == bpy.Value and not self.pc3[0] == bpy.Value:
                                self.pc4 = [bpy.Value]
                        CheckPlayers(self.screen, [self.pc1, self.pc2, self.pc3, self.pc4])
                        if not self.pc1[0] == '-1' and not self.pc2[0] == '-2' and not self.pc3[0] == '-3' and not self.pc4[0] == '-4':
                            self.players = [self.pc1,self.pc2, self.pc3, self.pc4]
                            bst = Button(FONT.render('Play', 1, FONT_COLOR), self.screen, 0,2)
                
                if bp2.collidepoint(pos) and self.curpage == 'PlayerSelect':
                    bp2 = Button(FONT.render('2', 1, WHITE), self.screen, 0,-2,2)
                    bp3 = Button(FONT.render('3', 1, FONT_COLOR), self.screen, 0,-1,3)
                    bp4 = Button(FONT.render('4', 1, FONT_COLOR), self.screen, 0,0,4)

                    bpr = Button(FONT.render('Red', 1, RED_BTN), self.screen, ((self.scr_width/6)*1, 1.7*OFFSET),0,1)
                    bpb = Button(FONT.render('Blue', 1, BLUE), self.screen, ((self.scr_width/6)*2, 1.7*OFFSET),0,0)
                    bpg = Button(FONT.render('Green', 1, GREEN), self.screen, ((self.scr_width/6)*4, 1.7*OFFSET),0,2)
                    bpy = Button(FONT.render('Yellow', 1, YELLOW), self.screen, ((self.scr_width/6)*5, 1.7*OFFSET),0,3)

                    self.pc1 = ['-1']
                    self.pc2 = ['-2']
                    self.pc3 = ['-3']
                    self.pc4 = ['-4']

                    self.players = [self.pc1, self.pc2]

                elif bp3.collidepoint(pos) and self.curpage == 'PlayerSelect':
                    bp2 = Button(FONT.render('2', 1, FONT_COLOR), self.screen, 0,-2,2)
                    bp3 = Button(FONT.render('3', 1, WHITE), self.screen, 0,-1,3)
                    bp4 = Button(FONT.render('4', 1, FONT_COLOR), self.screen, 0,0,4)

                    bpr = Button(FONT.render('Red', 1, RED_BTN), self.screen, ((self.scr_width/6)*1, 1.7*OFFSET),0,1)
                    bpb = Button(FONT.render('Blue', 1, BLUE), self.screen, ((self.scr_width/6)*2, 1.7*OFFSET),0,0)
                    bpg = Button(FONT.render('Green', 1, GREEN), self.screen, ((self.scr_width/6)*4, 1.7*OFFSET),0,2)
                    bpy = Button(FONT.render('Yellow', 1, YELLOW), self.screen, ((self.scr_width/6)*5, 1.7*OFFSET),0,3)

                    self.pc1 = ['-1']
                    self.pc2 = ['-2']
                    self.pc3 = ['-3']
                    self.pc4 = ['-4']
                    self.players = [self.pc1, self.pc2, self.pc3]

                elif bp4.collidepoint(pos) and self.curpage == 'PlayerSelect':
                    bp2 = Button(FONT.render('2', 1, FONT_COLOR), self.screen, 0,-2,2)
                    bp3 = Button(FONT.render('3', 1, FONT_COLOR), self.screen, 0,-1,3)
                    bp4 = Button(FONT.render('4', 1, WHITE), self.screen, 0,0,4)

                    bpr = Button(FONT.render('Red', 1, RED_BTN), self.screen, ((self.scr_width/6)*1, 1.7*OFFSET),0,1)
                    bpb = Button(FONT.render('Blue', 1, BLUE), self.screen, ((self.scr_width/6)*2, 1.7*OFFSET),0,0)
                    bpg = Button(FONT.render('Green', 1, GREEN), self.screen, ((self.scr_width/6)*4, 1.7*OFFSET),0,2)
                    bpy = Button(FONT.render('Yellow', 1, YELLOW), self.screen, ((self.scr_width/6)*5, 1.7*OFFSET),0,3)

                    self.pc1 = ['-1']
                    self.pc2 = ['-2']
                    self.pc3 = ['-3']
                    self.pc4 = ['-4']
                    self.players = [self.pc1, self.pc2, self.pc3, self.pc4]
                
                if bst.collidepoint(pos) and self.curpage == 'PlayerSelect':
                    if sound:
                        bell = pygame.mixer.Sound('Sounds/boxing_bell.wav')
                        bell.play()
                    if self.curpage == 'PlayerSelect' or self.curpage == 'Menu':
                        if len(self.players) >= 2:
                            start = False
                            for v in self.players:
                                if int(v[0]) > -1:
                                    start = True
                                else:
                                    start = False
                            if start:
                                #Start het spel
                                self.curpage = 'Game'
                                self.screen.fill(self.bg_color)
                                #Display gameboard
                                GameBoard(screen)
                                #Display players on board
                                players = PlayerList(self.players)
                                players.Iterate(lambda x: x.Draw(self.screen,players))
                                ScoreMenu(self.screen, players)

                                playerturn(self.screen, players, 0)

                                bbg = Button(FONT_TEXT.render('Back to menu', 1, FONT_COLOR), self.screen, (23*TILESIZE,0.2*TILESIZE))
                                throw_dice = Button(FONT_TEXT.render('Throw Dice', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE))

                                screen.blit(FONT_TEXT.render('P to pause the game', 1, RED_BTN), (21*TILESIZE,9*TILESIZE))
                                screen.blit(FONT_TEXT.render('R to view the rules', 1, RED_BTN), (21*TILESIZE,10*TILESIZE))
                                screen.blit(FONT_TEXT.render('ESC to exit the game', 1, RED_BTN), (21*TILESIZE,11*TILESIZE))

                                sc1 = Button(FONT_TEXT.render('Clicklabel', 1, BLACK), self.screen, (21*TILESIZE,5*TILESIZE),0,1)
                                sc2 = Button(FONT_TEXT.render('Clicklabel', 1, BLACK), self.screen, (21*TILESIZE,6*TILESIZE),0,2)
                                sc3 = Button(FONT_TEXT.render('Clicklabel', 1, BLACK), self.screen, (21*TILESIZE,7*TILESIZE),0,3)
                            else:
                                print('zzz')
                                #label op scherm toevoegen
                elif bs.collidepoint(pos) and self.curpage == 'Menu':
                    self.screen.fill(self.bg_color)
                    self.curpage = 'PlayerSelect'
                    label = FONT.render('Choose amount of players', 1, FONT_COLOR)
                    screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))

                    bp2 = Button(FONT.render('2', 1, FONT_COLOR), self.screen, 0,-2,2)
                    bp3 = Button(FONT.render('3', 1, FONT_COLOR), self.screen, 0,-1,3)
                    bp4 = Button(FONT.render('4', 1, FONT_COLOR), self.screen, 0,0,4)

                    bbh = Button(FONT.render('Back', 1, FONT_COLOR), self.screen, 0,5)
                elif bh.collidepoint(pos) and self.curpage == 'Menu':
                    #How to play page
                    pygame.display.set_caption('How to play Menu')
                    self.curpage = 'HelpMenu'
                    self.screen.fill(self.bg_color)
                    #Back btn op het scherm plaatsen
                    bbh = Button(FONT.render('Back', 1, FONT_COLOR), self.screen, 0,3)
                    #Informatie op het scherm zetten | Margin van 10%
                    Rules(screen)
                elif bss.collidepoint(pos) and self.curpage == 'Menu':
                     self.screen.fill(self.bg_color)
                     bsb = Button(FONT.render('Back', 1, FONT_COLOR), self.screen, 0,3)
                     if sound:
                        off = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,-2)
                        self.curpage = 'SettingsOn'
                     else:
                        on = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,-2)
                        self.curpage = 'Settings'
                     label = FONT.render('Sound:', 1, WHITE)
                     screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))
                     label2 = FONT.render('Fullscreen:', 1, WHITE)
                     screen.blit(label2, (SIZE[0] / 2 - label2.get_rect().width / 2, (SIZE[1] / 2 - label2.get_rect().height / 2)))
                     if fullscreen:
                        bfs = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,1)
                     else:
                        bfs = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,1)
                elif bfs.collidepoint(pos) and (self.curpage == 'Settings' or self.curpage == 'SettingsOn'):
                    if fullscreen:
                        pygame.display.set_mode(SIZE)
                        fullscreen = False
                    else:
                        pygame.display.set_mode(SIZE,pygame.FULLSCREEN)
                        fullscreen = True
                    self.screen.fill(self.bg_color)
                    bsb = Button(FONT.render('Back', 1, FONT_COLOR), self.screen, 0,3)
                    if sound:
                       off = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,-2)
                       self.curpage = 'SettingsOn'
                    else:
                       on = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,-2)
                       self.curpage = 'Settings'
                    label = FONT.render('Sound:', 1, WHITE)
                    screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))
                    label2 = FONT.render('Fullscreen:', 1, WHITE)
                    screen.blit(label2, (SIZE[0] / 2 - label2.get_rect().width / 2, (SIZE[1] / 2 - label2.get_rect().height / 2)))
                    if fullscreen:
                       bfs = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,1)
                    else:
                       bfs = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,1)
                elif on.collidepoint(pos) and self.curpage == 'Settings':
                    sound = True
                    self.curpage = 'SettingsOn'
                    self.screen.fill(self.bg_color)
                    bsb = Button(FONT.render('Back', 1, FONT_COLOR), self.screen, 0,3)
                    off = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,-2)
                    label = FONT.render('Sound:', 1, WHITE)
                    screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))
                    label2 = FONT.render('Fullscreen:', 1, WHITE)
                    screen.blit(label2, (SIZE[0] / 2 - label2.get_rect().width / 2, (SIZE[1] / 2 - label2.get_rect().height / 2)))
                    if fullscreen:
                       bfs = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,1)
                    else:
                       bfs = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,1)
                elif off.collidepoint(pos) and self.curpage == 'SettingsOn':
                    sound = False
                    self.curpage = 'Settings'
                    self.screen.fill(self.bg_color)
                    bsb = Button(FONT.render('Back', 1, FONT_COLOR), self.screen, 0,3)
                    on = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,-2)
                    label = FONT.render('Sound:', 1, WHITE)
                    screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))
                    label2 = FONT.render('Fullscreen:', 1, WHITE)
                    screen.blit(label2, (SIZE[0] / 2 - label2.get_rect().width / 2, (SIZE[1] / 2 - label2.get_rect().height / 2)))
                    if fullscreen:
                       bfs = Button(FONT.render('Off', 1, FONT_COLOR), self.screen, 0,1)
                    else:
                       bfs = Button(FONT.render('On', 1, FONT_COLOR), self.screen, 0,1)
                elif bsb.collidepoint(pos) and (self.curpage == 'Settings' or self.curpage == 'SettingsOn'):
                    self.curpage = 'Menu'
                    self.screen.fill(self.bg_color)
                    self.screen.blit(pygame.transform.scale(self.bg, (self.scr_height,self.scr_height)),(self.bgoffset,0))
                    #Btns start/how to play/exit op het scherm plaatsen
                    bs = Button(FONT.render('Start', 1, FONT_COLOR), self.screen, 0,-1)
                    bh = Button(FONT.render('How to play', 1, FONT_COLOR), self.screen, 0,0)
                    bss = Button(FONT.render('Settings', 1, FONT_COLOR), self.screen, 0,1)
                    bc = Button(FONT.render('Exit', 1, FONT_COLOR), self.screen, 0,2)
                elif bc.collidepoint(pos) and self.curpage == 'Menu':
                    #Exit game, stop loop en exit de console
                    mainloop = False
                    pygame.quit()
                    sys.exit()
                elif bbh.collidepoint(pos) or bbg.collidepoint(pos):
                    if self.curpage == 'Game' or self.curpage == 'HelpMenu' or self.curpage == 'PlayerSelect':
                        pygame.display.set_caption('Game Menu')
                        self.curpage = 'Menu'
                        self.screen.fill(self.bg_color)
                        self.screen.blit(pygame.transform.scale(self.bg, (self.scr_height,self.scr_height)),(self.bgoffset,0))
                        #Btns start/how to play/exit op het scherm plaatsen
                        bs = Button(FONT.render('Start', 1, FONT_COLOR), self.screen, 0,-1)
                        bh = Button(FONT.render('How to play', 1, FONT_COLOR), self.screen, 0,0)
                        bss = Button(FONT.render('Settings', 1, FONT_COLOR), self.screen, 0,1)
                        bc = Button(FONT.render('Exit', 1, FONT_COLOR), self.screen, 0,2)
                elif bsg.collidepoint(pos) and self.curpage == 'Winning_screen':
                        pygame.display.set_caption('Game Menu')
                        self.curpage = 'Menu'
                        self.screen.fill(self.bg_color)
                        self.screen.blit(pygame.transform.scale(self.bg, (self.scr_height,self.scr_height)),(self.bgoffset,0))
                        #Btns start/how to play/exit op het scherm plaatsen
                        bs = Button(FONT.render('Start', 1, FONT_COLOR), self.screen, 0,-1)
                        bh = Button(FONT.render('How to play', 1, FONT_COLOR), self.screen, 0,0)
                        bss = Button(FONT.render('Settings', 1, FONT_COLOR), self.screen, 0,1)
                        bc = Button(FONT.render('Exit', 1, FONT_COLOR), self.screen, 0,2)
                elif (throw_dice.collidepoint(pos) or not aiPlayerCheckList.Filter(lambda x : x.Turn and x.AI > 0).IsEmpty) and self.curpage == 'Game':
                    dicenumber = Dice(self.screen)
                    pygame.time.delay(1000)             
                    ResetMap(self.screen, players)

                    throw_dice = Button(FONT_TEXT.render('Throw Dice', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE))
                    sc1 = Button(FONT_TEXT.render('Clicklabel', 1, BLACK), self.screen, (21*TILESIZE,5*TILESIZE),0,1)
                    sc2 = Button(FONT_TEXT.render('Clicklabel', 1, BLACK), self.screen, (21*TILESIZE,6*TILESIZE),0,2)
                    sc3 = Button(FONT_TEXT.render('Clicklabel', 1, BLACK), self.screen, (21*TILESIZE,7*TILESIZE),0,3)      
                    players = RemoveDeathPlayers(players)
                    playerturn(self.screen, players,10)#dicenumber)
                    players.Iterate(lambda x: x.Draw(self.screen,players))
                    temp = players
                    x = players
                    y = players
                    while not x.IsEmpty:
                        if x.Value.Turn:
                            if x.Value.Tile.Index in [5, 15, 25, 35]:
                                pygame.draw.rect(screen, BLACK, (0, 0 , 250,30))
                                throw_dice_fight = Button(FONT_TEXT.render('Fight', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE))
                                self.curpage = 'Turn2'
                            elif x.Value.Tile.Index in [0, 10, 20, 30]:
                                if not temp.Filter(lambda z:z.Home == x.Value.Tile.Index and not x.Value.Home == z.Home).IsEmpty:
                                    pygame.draw.rect(screen, BLACK, (0, 0 , 250,30))
                                    throw_dice_fight = Button(FONT_TEXT.render('Fight', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE))
                                    self.curpage = 'Turn2'
                                    player1 = True
                                else:
                                    endplayerturn(self.screen, players)
                                    break
        #marcels custom loop for PVP on tiles
        #I'm Kinda stuck
                            elif x.Value.Tile.Index in range (0,39):
                                while not y.IsEmpty:
                                    if not x.Value.Home == y.Value.Home and x.Value.Tile.Index == y.Value.Tile.Index:
                                        pygame.draw.rect(screen, BLACK, (0, 0 , 250,30))
                                        throw_dice_fight = Button(FONT_TEXT.render('Fight', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE))
                                        self.curpage = 'Turn2'
                                        p2 = y.Value.Home
                                        p1 = x.Value.Home
                                    y = y.Tail
                                if y.IsEmpty:
                                    endplayerturn(self.screen, players)
                                    break
                            else:
                                endplayerturn(self.screen, players)
                                break
                        x = x.Tail
                elif throw_dice_fight.collidepoint(pos) and self.curpage == 'Turn2':
                    dicenumber2 = Dice(self.screen)

                    x = players
                    while not x.IsEmpty:
                        if x.Value.Turn:
                            try:
                                p1
                            except NameError:
                                p1 = -2
                            try:
                                p2
                            except NameError:
                                p2 = -2
                            if p1 > -1:
                                DisplayScoreCard(screen, x.Value.Home, dicenumber2, x.Value.Condition)
                                p1 = -2
                            elif p2 > -1 and not p1 > -1:
                                z = x
                                tempPlayers = z.Filter(lambda x: x.Home == p2)
                                DisplayScoreCard(screen, p2, dicenumber2, tempPlayers.Value.Condition)
                            elif x.Value.Tile.Index in [0, 10, 20, 30]:
                                if player1:
                                    DisplayScoreCard(screen, x.Value.Home, dicenumber2, x.Value.Condition)
                                    player1 = False
                                else:
                                    DisplayScoreCard(screen, x.Value.Tile.Index, dicenumber2, x.Value.Condition)
                            else:
                                DisplayScoreCard(screen, x.Value.Home, dicenumber2, x.Value.Condition)
                        x = x.Tail
                    pygame.time.delay(1000)

            #Winning screen , verander countcurrent players naar == 2 om te testen!
            if CountCurrentPlayers(players) == 1:
                colors = [BLUE, RED, GREEN, YELLOW]
                self.curpage = 'Winning_screen'
                self.screen.fill(self.bg_color)
                label = FONT.render('Player '+str(players.Value.Number)+ ' Wins', 1, colors[int(math.floor(players.Value.Home)/10)])
                screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))
                bsg = Button(FONT.render('Play again', 1, FONT_COLOR), self.screen, 0,3)
                players = Empty()
                self.players = []
                if sound:
                    winning.play()



            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == pygame.K_p and (self.curpage == 'Game' or self.curpage == 'Pause'):
                    if self.curpage == 'Pause':
                        self.curpage = 'Game'
                        ResetMap(self.screen, players)
                        players.Iterate(lambda x: x.Draw(self.screen,players))
                        throw_dice = Button(FONT_TEXT.render('Throw Dice', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE)) 
                    else:
                        self.curpage = 'Pause'
                        screen.fill(self.bg_color)
                        label = FONT.render('Game is paused', 1, WHITE)
                        screen.blit(label, (SIZE[0] / 2 - label.get_rect().width / 2, (SIZE[1] / 3.8 - label.get_rect().height / 2)))
                if event.key == pygame.K_r and (self.curpage == 'Game' or self.curpage == 'GameRules'):
                    if self.curpage == 'Game':
                        self.curpage = 'GameRules'
                        screen.fill(self.bg_color)
                        Rules(screen)
                    else:
                        self.curpage = 'Game'
                        ResetMap(self.screen, players)
                        players.Iterate(lambda x: x.Draw(self.screen,players))
                        throw_dice = Button(FONT_TEXT.render('Throw Dice', 1, FONT_COLOR), self.screen, (2*TILESIZE,0.2*TILESIZE)) 

            if mainloop:
                pygame.display.flip()
            else:
                pygame.quit()
                sys.exit()
Exemple #50
0
	def __init__(self):
		"""Creates a GUI object for use with Chess, complete with Mouse, Square, and Message functionality."""

		# Determining the width and length
		self.width = 1000
		self.height = 700

		# Create the square colors
		self.darkSquareColor = "LightSteelBlue1"
		self.darkSquareColorHighlighted = "blue2"

		self.lightSquareColor = "MistyRose2"
		self.lightSquareColorHighlighted = "maroon1"

		# Create the line color
		self.lineColor = "black"

		# Creating the graphics window
		self.window = GraphWin("Chess!!!", self.width, self.height)

		# Creating the background color
		self.background = "honeydew2"

		# Filling in the background color
		self.window.setBackground(self.background)

		# Set the size of the chess board
		self.boardLength = self.height * 7 / 8

		# Creating the interaction options

		self.messageBox = Text(Point(self.width * 10 / 12, self.height * 1 / 4), "")
		self.messageBox.draw(self.window)
		self.messageBox.setFace("times roman")

		self. moveBox = Text(Point(self.width * 10 / 12, self.height * 1 / 2), "")
		self.moveBox.draw(self.window)
		self.moveBox.setFace("times roman")

		self.quitButton = Button(self.window, Point(self.width * 10 / 12, self.height * 2 / 3), 70, 40, "Quit", "CadetBlue1")
		self.resetButton = Button(self.window, Point(self.width * 10 / 12, self.height * 5 / 6), 70, 40, "New Game!", "CadetBlue1")

		self.quitButton.activate()

		# Create the squared grid
		self.listOfSquares = [[],[],[],[],[],[],[],[]]
		alpha = ["a","b","c","d","e","f","g","h"]
		numbers = ["1","2","3","4","5","6","7","8"]
		labelsX,labelsY = [],[]

		for i in range(8):
			for j in range(8):
				if(i % 2 == 0 and j % 2 != 0) or (i % 2 != 0 and j % 2 == 0):
					self.listOfSquares[i].append(Square(self.darkSquareColor, self.darkSquareColorHighlighted, self.lineColor, self.boardLength * i / 8 + self.width * 1 / 18, self.boardLength * j / 8 + self.height * 1/18, self.boardLength / 8))
				else:
					self.listOfSquares[i].append(Square(self.lightSquareColor, self.lightSquareColorHighlighted, self.lineColor, self.boardLength * i / 8 + self.width * 1 / 18, self.boardLength * j / 8 + self.height * 1/18, self.boardLength / 8))
				labelsY.append(Text(Point(self.width * 1 / 18 + self.boardLength + 15, self.boardLength * j / 8 + self.height * 1/18 + self.boardLength / 16), numbers[7-j]))
			labelsX.append(Text(Point(self.boardLength * i / 8 + self.width * 1 / 18 + self.boardLength / 16, self.height * 1/18 - 14), alpha[i]))

		# Draw the squares
		for squareList in self.listOfSquares:
			for square in squareList:
				square.draw(self.window)

		# Draw the labels
		for i in range(8):
			labelsX[i].draw(self.window)
			labelsY[i].draw(self.window)

		# Create the border lines
		self.borderLine1 = Line(Point(self.width * 1 / 18, self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.height * 1/18))
		self.borderLine2 = Line(Point(self.width * 1 / 18, self.height * 1/18), Point(self.width * 1 / 18, self.boardLength + self.height * 1/18))
		self.borderLine3 = Line(Point(self.boardLength + self.width * 1 / 18, self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.boardLength + self.height * 1/18))
		self.borderLine4 = Line(Point(self.width * 1 / 18, self.boardLength + self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.boardLength + self.height * 1/18))

		# Draw the border lines
		self.borderLine1.draw(self.window)
		self.borderLine2.draw(self.window)
		self.borderLine3.draw(self.window)
		self.borderLine4.draw(self.window)

		# Change the color of the border lines
		self.borderLine1.setFill(self.lineColor)
		self.borderLine2.setFill(self.lineColor)
		self.borderLine3.setFill(self.lineColor)
		self.borderLine4.setFill(self.lineColor)

		# Create a list of highlighted squares to reduce lag
		self.highlightedSquares = []
    def MainLoop(self):
        """Create the background"""
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()
        self.screen.fill((255,255,255))

        # timer stuff 
        clock = pygame.time.Clock()
        frame_count = 0
        frame_rate = 20
        start_time = 60

        while True: # main game loop

            font = pygame.font.Font(None, 30)
            # --- Timer going down ---
            # --- Timer going up ---
            # Calculate total seconds
            total_seconds = start_time - (frame_count // frame_rate)
            if total_seconds < 0:
                total_seconds = 0
             
            # Divide by 60 to get total minutes
            minutes = total_seconds // 60
             
            # Use modulus (remainder) to get seconds
            seconds = total_seconds % 60
             
            # Use python string formatting to format in leading zeros
            output_string = "Time left: {0:02}:{1:02}".format(minutes,seconds)
            
            # when timer runs out 
            if total_seconds == 0: 
                pygame.draw.rect(self.screen, self.GRAY, pygame.Rect(0, 0, 640, 480))
                text = font.render("Game over, thanks for playing! Your score is: "+str(self.score),1,self.RED)
                x ,y = self.screen.get_size()
                self.screen.blit(text, [50,y/2])
                pygame.display.flip() 
                pygame.time.wait(1000)
                sys.exit()

            # warning towards the end of the game
            rectCol = self.WHITE 
            # Blit to the screen
            if total_seconds <= 5 and total_seconds > 0: 
                if frame_count%20 == 0: 
                    rectCol = self.RED 
                else : 
                    rectCol = self.WHITE
            pygame.draw.rect(self.screen, rectCol, pygame.Rect(425, 0, 240, 40))
            text = font.render(output_string,1,self.BLACK)
            self.screen.blit(text, [450,10])
            pygame.display.flip() 

            '''timer = 0 
            seconds = clock.tick(40)/1000.0
            timer += seconds 
            displaytimer = math.trunc(timer)
            myfont = pygame.font.SysFont(None, 30)
            # apply it to text on a label
            label_time = myfont.render("Timer: "+str(displaytimer), 1, GREEN)
            # put the label object on the screen at point x=100, y=100
            self.screen.blit(label_time, (500, 450))
            pygame.display.flip()'''

            gobut = Button(10,10,"goMed.png")
            txtbx = eztext.Input(x=70,y=10,maxlength=2, color=(0,255,0), prompt='Type your guess: ')
            self.screen.blit(gobut.image,gobut.rect)
            pygame.display.flip() #update display



            k = pygame.event.poll() #look for an event
            if k.type == MOUSEBUTTONDOWN: #if they click,
                if k.button == 1: #if it's the left button,  
                    if gobut.clicked(k.pos): #check if the button's limits are clicked
                        self.screen.fill(self.WHITE)
                        pygame.display.flip()

                        gobut.press() #depress the button
                        self.screen.blit(gobut.image,gobut.rect) #update the screen
                        print "they clicked the go button"
                        pygame.display.flip() #update display

                        self.generateRandom()
 
                        # update txtbx
                        txtbx.update([k])
                        # blit txtbx on the sceen
                        txtbx.draw(self.screen)
                        # refresh the display
                        pygame.display.flip()

                        

            elif k.type == KEYDOWN: 
                if k.key == 13: 
                    print "entered enter"
                    # TODO: send the current guess to the log 
                    # refresh the page ie. get new problem 
                    # generate random measurement and reference lines and positions 
                    self.screen.fill(self.WHITE)
                    pygame.display.flip()
                    self.generateRandom()
                    pygame.display.flip()
                    generatedMouse1 = pygame.event.Event(MOUSEBUTTONDOWN,{'pos':(11,11),'button':gobut})
                    generatedMouse2 = pygame.event.Event(MOUSEBUTTONUP,{'pos':(11,11),'button':gobut})
                    pygame.event.post(generatedMouse1)
                    pygame.event.post(generatedMouse2)

                    # display the score 
                    myfont = pygame.font.SysFont(None, 30)
                    # apply it to text on a label
                    label = myfont.render("Score: "+str(self.score), 1, self.BLUE)
                    # put the label object on the screen at point x=100, y=100
                    self.screen.blit(label, (300, 10))
                    pygame.display.flip()

                # update txtbx
                txtbx.update([k])
                # blit txtbx on the sceen
                txtbx.draw(self.screen)
                # refresh the display
                pygame.display.flip()
                #peek at value 
                print "USER ENTERED: ", txtbx.value
                print "MULT RIGHT HERE", self.mult
                
                if k.key != 13 and int(txtbx.value) == self.mult: 
                    print 'Trueee'
                    self.score += self.mult 

            frame_count += 1
            # Limit to 20 frames per second
            clock.tick(frame_rate)
          
            # Go ahead and update the screen with what we've drawn.
            pygame.display.flip()


            if k.type == QUIT:
                    pygame.quit()
                    sys.exit()   
            pygame.display.update()

            '''# drawing the first bar! :) 
Exemple #52
0
def characterchoose():
    #Create the window
    win = GraphWin("Choose Character", 1000, 800)
    win.setCoords(0,0,15,11)
    win.setBackground('lightgray')

    #Draw wizard box
    w = Button(win, Point(3, 7), 2.5, 2.5, "Wizard", 'lightblue')
    wtext = "A magic user who channels his arcane abilities in the form of fire and lighting. \nHe also has a pointy hat."
    
    #Draw fighter box
    f = Button(win, Point(7, 7), 2.5, 2.5, "Fighter", 'red')
    ftext = "A skilled martial combatant, who uses a sword and shield \nto smash his foes."
    
    #Draw archer box
    a = Button(win, Point(11, 7), 2.5, 2.5, "Archer", 'green')
    atext = "A woodsman who uses his bow and arrows to rain \ndeath and destruction on his foes."

    #Draw text box
    t = Rectangle(Point(1,1),Point(13,3))
    t.setFill('black')
    t.draw(win)

    #Set the text for the text box
    ttext = Text(Point(6.5,2),"Select a class to see a description.")
    ttext.setFill('white')
    ttext2 = Text(Point(6.5, 1.75), "Then choose your favorite and press ok.")
    ttext2.setFill('white')
    ttext3 = Text(Point(6.5, 1.5), "To quit, press quit.")
    ttext3.setFill('white')
    ttext.draw(win)
    ttext2.draw(win)
    ttext3.draw(win)

    #Draw quit button
    q = Button(win, Point(0.75, 10.25), 0.5, 0.5, "quit", 'darkgray')
    q.activate()

    #Draw the ok button
    o = Button(win, Point(14.25, 1.5), 0.5, 0.5, "OK", 'darkgray')
    o.activate()

    #Change the text in the text box based on which character the player chooses
    p = win.getMouse()
    while q.clicked(p) == False:
        if w.clicked(p) == True:
            ttext.setText(wtext)
            ttext2.setText("")
            ttext3.setText("")
        if f.clicked(p) == True:
            ttext.setText(ftext)
            ttext2.setText("")
            ttext3.setText("")
        if a.clicked(p) == True:
            ttext.setText(atext)
            ttext2.setText("")
            ttext3.setText("")
        p = win.getMouse()

    #Tell the game which character the player chose
        if o.clicked(p) == True:
            if ttext.getText() == wtext:
                player = wizard()
            elif ttext.getText() == ftext:
                player = fighter()
            else:
                player = archer()
            win.close()
            return player
            
    #Quit the game
    if q.clicked(p) == True:
            win.close()
Exemple #53
0
def main():
    letters_list = ["",""]
    for i in range(9):
        letters_list.append("A")
    for i in range(2):
        letters_list.append("B")
        letters_list.append("C")
    for i in range(4):
        letters_list.append("D")
    for i in range(12):
        letters_list.append("E")
    for i in range(2):
        letters_list.append("F")
    for i in range(3):
        letters_list.append("G")
    for i in range(2):
        letters_list.append("H")
    for i in range(9):
        letters_list.append("I")
    for i in range(1):
        letters_list.append("J")
        letters_list.append("K")
    for i in range(4):
        letters_list.append("L")
    for i in range(2):
        letters_list.append("M")
    for i in range(6):
        letters_list.append("N")
    for i in range(8):
        letters_list.append("O")
    for i in range(2):
        letters_list.append("P")
    for i in range(1):
        letters_list.append("Q")
    for i in range(6):
        letters_list.append("R")
    for i in range(4):
        letters_list.append("S")
    for i in range(6):
        letters_list.append("T")
    for i in range(4):
        letters_list.append("U")
    for i in range(2):
        letters_list.append("V")
        letters_list.append("W")
    for i in range(1):
        letters_list.append("X")
    for i in range(2):
        letters_list.append("Y")
    for i in range(1):
        letters_list.append("Z")
    window = GraphWin("Tiles",400,400)
    window.setCoords(0,0,210,210)
    
    p1 = Player("Paul","123")
    p2 = Player("Liz", "123")
    
    instructions = Text(Point(105,200),"Click on a tile to move them")
    instructions.draw(window)

    quit = Button("Quit",Point(175,180),Point(190,190))
    quit.draw(window)
    
    i = 0
    while i < 7:
        letter_i = random.randint(0,len(letters_list)-1)
        letter = letters_list[letter_i]
        letters_list.remove(letter)
        tile = Tile(letter)
        p1.addTile(tile)
        i = i + 1
        
    k = 0
    while k < 7:
        letter_i = random.randint(0,len(letters_list)-1)
        letter = letters_list[letter_i]
        letters_list.remove(letter)
        tile = Tile(letter)
        p2.addTile(tile)
        k = k + 1
    
    xp1 = 25
    yp1 = 10
    for j in range(len(p1.tiles)):
        p = Point(xp1,yp1)
        p1.tiles[j].setRect(p,window)
        p1.tiles[j].draw_tile(window)
        xp1 = xp1 + 25
        
    xp2 = 15
    yp2 = 190
    for j in range(len(p1.tiles)):
        p = Point(xp2,yp2)
        p2.tiles[j].setRect(p,window)
        p2.tiles[j].draw_tile(window)
        yp2 = yp2 - 25
        
    while True:
        p = window.getMouse()
        for i in range(len(p1.tiles)):
            if p1.tiles[i].clicked(p):
                p1.tiles[i].setRectColor()
                point2 = window.getMouse()
                p1.tiles[i].move(point2,window)
            elif p2.tiles[i].clicked(p):
                p2.tiles[i].setRectColor()
                point2 = window.getMouse()
                p2.tiles[i].move(point2,window)
        if quit.clicked(p):
            break
    window.close()
Exemple #54
0
	def Menu_H(self):
		Msc = Musics()
		btn_general = Button(0)
		btn_voltar = Button(0)
		btn_red_e = Button(1)
		btn_red_d = Button(1)
		btn_list_text = []
		btn_list_text.append(self.Old_English_25.render(self.lang.Get(1), False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render("<", False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render(">", False, (226, 157, 54) ))
		bkg = pygame.image.load("Graphics/Screens/High_score.jpg")
		selected = pygame.image.load("Graphics/Boxes/Selected.jpg")
		unselected = pygame.image.load("Graphics/Boxes/Unselected.jpg")
		qtd = 0
		qtd_opus = 0
		pag_atual = 0
		lado = 0
		msc_atual = 0
		aux = 0
		limit = 0
		
		list,qtd = Msc.GetList()
		esq = []
		dir = []
		tam = qtd[pag_atual]
		qtd_opus = len(qtd)
		voltar = False
		score_aux =score_number = 0
		#LACO DO MENU 1
		while (voltar == False):
			esq = []
			dir = []
			#CALCULA QUAIS PAGINAS MOSTRAR
			if pag_atual < qtd_opus:
				if pag_atual == 0:
					score_number= i = 0
					limit =qtd[pag_atual]
				else:
					score_number =i = qtd[pag_atual-1]
				while i < qtd[pag_atual]:
					esq.append(self.Carolingia_20.render(arruma_texto(list[i]), False, (226, 157, 54) ))
					i+=1
			if pag_atual +1 < qtd_opus:
				i = qtd[pag_atual]
				while i <qtd[pag_atual+1]:
					dir.append(self.Carolingia_20.render(arruma_texto(list[i]), False, (226, 157, 54) ))
					i+=1
			sair = mudar = False
			score_aux = score_number
			#LACO DO MENU 2
			while (sair == False):
				score_number = score_aux
				#PEGA EVENTOS
				for evento in pygame.event.get():
					#EVENTOS DO MOUSE
					if evento.type == pygame.MOUSEBUTTONUP:
						if Bleft == True:
							px , py = pygame.mouse.get_pos()
							if ((px>= 280)and (px<=348)) and ((py>= 500)and (py<=568)):
								msc_atual = 0
								if lado == 0:
									pag_atual -=2
									if pag_atual <0:
										pag_atual = qtd_opus-2
										lado = 1
									sair = mudar = True
								else:
									lado = 0
									tam = len(dir)
							if ((px>= 450)and (px<=518)) and ((py>= 500)and (py<=568)):
								msc_atual = 0
								if lado == 1:
									pag_atual +=2
									if pag_atual > qtd_opus-2:
										pag_atual = 0
										lado = 0
									sair = mudar = True
								else:
									lado = 1
									tam = len(esq)
							if ((px>= 530)and (px<=730)) and ((py>= 510)and (py<=560)):
								btn_voltar.click()
								mudar =voltar = sair = True
								#return False
							if (len(esq) > len(dir)):
								num = len(esq)
							else:
								num = len(dir)
							aux = Const_default_y+(((-1)*(num/2))*30)
							num2 =0
							for i in range(len(esq)):						
								if ((px>= 65)and (px<=397)) and ((py>= aux+30*num2) and (py<=aux+30*(num2)+25)):
									if (lado == 0)  and (msc_atual == num2):
										sair = True
									else:
										msc_atual = num2
										lado = 0
								num2 += 1
							num2 = 0
							for i in range(len(dir)):
								if ((px>= 415)and (px<=747)) and ((py>= aux+30*num2) and (py<=aux+30*(num2)+25)):
									if (lado == 1)  and (msc_atual == num2):
										sair = True
									else:
										msc_atual = num2
										lado = 1
								num2 += 1
							Bleft == False
					if evento.type == pygame.MOUSEBUTTONDOWN:
						Bleft,Bmiddle, Bright =  pygame.mouse.get_pressed()
					if evento.type == pygame.QUIT:
						sys.exit(0)
					#EVENTOS DO TECLADO
					if evento.type == pygame.KEYDOWN:
						if evento.key == pygame.K_RETURN:
							sair = True
						if evento.key == pygame.K_ESCAPE:
							return False
							msc_atual = -1
						if evento.key == pygame.K_LEFT:
							msc_atual = 0
							if lado == 0:
								pag_atual -=2
								if pag_atual <0:
									pag_atual = qtd_opus-2
								lado = 1
								sair = mudar = True
							else:
								lado = 0
								tam = len(esq)
								
						if evento.key == pygame.K_RIGHT:
							msc_atual = 0
							if lado == 1:
								pag_atual +=2
								if pag_atual > qtd_opus-2:
									pag_atual = 0
								lado = 0
								sair = mudar = True
							else:
								lado = 1
								tam = len(dir)
						if evento.key == pygame.K_DOWN:
							msc_atual += 1
							if msc_atual > tam-1:
								msc_atual = 0
						if evento.key == pygame.K_UP:
							msc_atual -= 1
							if msc_atual < 0:
								msc_atual = tam-1
				
				#Desenha Fundo
				self.tela.blit(bkg,(0,0))
				#Escreve Numero das paginas esquerda e direita
				self.tela.blit(self.Carolingia_20.render((repr(pag_atual+1)), False, (226, 157, 54) ),(230,128))
				self.tela.blit(self.Carolingia_20.render((repr(pag_atual+2)), False, (226, 157, 54) ),(590,128))
				self.tela.blit(self.Carolingia_25.render(self.lang.Get(1), False, (226, 157, 54) ),(576,520))
				#self.tela.blit(self.Carolingia_25.render(("High Score:  "+repr(msc_atual)), False, (226, 157, 54) ),(0,0))
				#Desenha botoes
				self.tela.blit(btn_general.desenha(),(70,510))
				self.tela.blit(btn_red_e.desenha(),(280,500))
				self.tela.blit(btn_red_d.desenha(),(450,500))
				self.tela.blit(btn_voltar.desenha(),(530,510))
				#escreve texto dos botoes
				#self.tela.blit(btn_list_text[0],(90,520))
				self.tela.blit(btn_list_text[1],(310,520))
				self.tela.blit(btn_list_text[2],(480,520))
				self.tela.blit(btn_list_text[0],(600,520))
				#ESCREVE ITENS DA PAGINA ESQUERDA
				if (len(esq) > len(dir)):
					num = len(esq)
				else:
					num = len(dir)
				num2 = (-1)*(num/2)
				for i in range(len(esq)):
					aux = Const_default_y+(num2*30)
					num2 += 1
					if (lado == 0):
						if (i == msc_atual):
							self.tela.blit(selected,(60,aux-2))
						else:
							self.tela.blit(unselected,(60,aux-2))
					else:
						self.tela.blit(unselected,(60,aux-2))
					self.tela.blit(esq[i],(65,aux))
					self.tela.blit(self.Carolingia_20.render((repr((self.High_S.Get()[score_number])[1])), False, (226, 157, 54) ),(330,aux-2))
					score_number+=1
				#ESCREVE ITENS DA PAGINA DIREITA
				num2 = (-1)*(num/2)
				for i in range(len(dir)):
					aux = Const_default_y+(num2*30)
					num2 += 1
					if (lado == 1):
						if (i == msc_atual):
							self.tela.blit(selected,(410,aux-2))
						else:
							self.tela.blit(unselected,(410,aux-2))
					else:
						self.tela.blit(unselected,(410,aux-2))
					self.tela.blit(dir[i],(415,aux))
					self.tela.blit(self.Carolingia_20.render((repr((self.High_S.Get()[score_number])[1])), False, (226, 157, 54) ),(700,aux))
					score_number+=1
				#DESENHA O MOUSE
				self.tela.blit(self.cursor_picture, pygame.mouse.get_pos())
				#ATUALIZA A TELA
				pygame.display.flip()
				if btn_voltar.getState():
					time.sleep(0.2)
			esq = []
			dir = []
Exemple #55
0
	def Option(self):
		btn_salvar = Button(0)
		btn_cancelar = Button(0)
		sair = False
		#variaveis de config
		Nivel = [self.lang.Get(10),self.lang.Get(11),self.lang.Get(12),self.lang.Get(13)]
		nivel =[1,2,5,10]
		language = self.languages.GetNameList()
		lang_id = 0
		lvl = 0
		full = self.config.Get_full()
		audio = self.config.Get_audio()
		for i in nivel:
			if (i == self.config.Get_lvl()):
				break
			lvl +=1
		y=0;
		bkg = pygame.image.load("Graphics/Screens/Option.jpg")
		bar = pygame.image.load("Graphics/Boxes/Bar.jpg")
		#LACO DO MENU
		while (sair == False):
			#PREPARA PARA Desenha
			if full == 1:
				checkbox= pygame.image.load("Graphics/Boxes/Checked.jpg")
			else:
				checkbox= pygame.image.load("Graphics/Boxes/Unchecked.jpg")
			#PEGA EVENTOS
			for evento in pygame.event.get():
				#EVENTOS DO MOUSE
				if evento.type == pygame.MOUSEBUTTONUP:
					if Bleft == True:
						px , py = pygame.mouse.get_pos()
						#botao de salvar
						if ((px>= 50)and (px<=250)) and ((py>= 510)and (py<=560)):
							btn_salvar.click()
							self.config.Set(nivel[lvl], audio, full,language[lang_id])
							self.profile.Set_Conf(self.config)
							self.config = self.profile.Return_Config()
							#carregando linguagem
							self.languages = Language(self.config.Get_lang())
							self.lang = Lang (self.languages.GetOne())
							self.profile.save()
							sair = True
						#botao de cancelar
						if ((px>= 550)and (px<=750)) and ((py>= 510)and (py<=560)):
							btn_cancelar.click()
							sair = True
						Bleft == False
				if evento.type == pygame.MOUSEBUTTONDOWN:
					Bleft,Bmiddle, Bright =  pygame.mouse.get_pressed()
				#EVENTOS DO TECLADO
				if evento.type == pygame.QUIT:
					sys.exit()
				if evento.type == pygame.KEYDOWN:
					if evento.key == pygame.K_RETURN:
						#salva as configuracoes
						self.config.Set(nivel[lvl], audio, full,language[lang_id])
						self.profile.Set_Conf(self.config)
						self.config = self.profile.Return_Config()
						#carregando linguagem
						self.languages = Language(self.config.Get_lang())
						self.lang = Lang (self.languages.GetOne())
						#print (self.languages.GetOne())
						self.profile.save()
						sair = True
					if evento.key == pygame.K_ESCAPE:
						sair = True
					if evento.key == pygame.K_LEFT:
						if (y == 0):
							lvl -=1
							if lvl <0:
								lvl = 3
						elif (y== 1):
							if audio >0.0:
								audio -=0.1
							if audio <0.0:
								audio = 0.0
						elif (y==2):
							if (full == 1):
								full = 0
							else:
								full = 1
						else:
							lang_id -=1
							if lang_id <0:
								lang_id = len(language)-1
					if evento.key == pygame.K_RIGHT:
						if (y == 0):
							lvl +=1
							if lvl >3:
								lvl = 0
						elif (y== 1):
							if audio <1.0:
								audio +=0.1
							if audio >1.0:
								audio = 1.0
						elif (y==2):
							if (full == 1):
								full = 0
							else:
								full = 1
						else:
							lang_id +=1
							if lang_id >len(language)-1:
								lang_id = 0
					if evento.key == pygame.K_DOWN:
						y += 1
						if y > 3:
							y = 0
					if evento.key == pygame.K_UP:
						y -= 1
						if y < 0:
							y = 3
			#DESENHA FUNDO
			self.tela.blit(bkg,(0,0))
			#self.tela.blit(self.Carolingia_25.render(("Options:  "+repr(y)), False, (226, 157, 54) ),(0,0))
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(16), False, (226, 157, 54) ),(90,610))
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(17), False, (226, 157, 54) ),(596,610))
			#opcoes
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(22), False, (226, 157, 54) ),(120,236))
			self.tela.blit(self.Carolingia_25.render((Nivel[lvl]), False, (226, 157, 54) ),(315,236))
			
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(23), False, (226, 157, 54) ),(120,306))
			self.tela.blit(pygame.transform.scale(bar ,(int (180*audio), 36)),(308,306))
			
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(24), False, (226, 157, 54) ),(120,376))
			self.tela.blit(checkbox,(308,376))
			
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(25), False, (226, 157, 54) ),(120,446))
			self.tela.blit(self.Carolingia_25.render((language[lang_id]), False, (226, 157, 54) ),(315,446))
			#Desenha botoes
			self.tela.blit(btn_salvar.desenha(),(50,510))
			self.tela.blit(btn_cancelar.desenha(),(550,510))
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(16), False, (226, 157, 54) ),(70,520))
			self.tela.blit(self.Carolingia_25.render(self.lang.Get(17), False, (226, 157, 54) ),(576,520))
			#desenha seta de selecionado
			self.tela.blit(pygame.transform.rotate(self.cursor_picture,-125), (55,227+70*y))
			#DESENHA O MOUSE
			self.tela.blit(self.cursor_picture, pygame.mouse.get_pos())
			#ATUALIZA A TELA
			pygame.display.flip()
			if btn_salvar.getState() or btn_cancelar.getState():
					time.sleep(0.2)
Exemple #56
0
	def Menu_Q(self):
		Msc = Musics()
		btn_jogar = Button(0)
		btn_voltar = Button(0)
		btn_red_e = Button(1)
		btn_red_d = Button(1)
		btn_list_text = []
		btn_list_text.append(self.Old_English_25.render(self.lang.Get(19), False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render(self.lang.Get(1), False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render("<", False, (226, 157, 54) ))
		btn_list_text.append(self.Old_English_25.render(">", False, (226, 157, 54) ))
		bkg = pygame.image.load("Graphics/Screens/Quick_play.jpg")
		selected = pygame.image.load("Graphics/Boxes/Selected.jpg")
		unselected = pygame.image.load("Graphics/Boxes/Unselected.jpg")
		qtd = 0
		qtd_opus = 0
		pag_atual = 0
		lado = 0
		msc_atual = 0
		aux = 0
		limit = 0
		
		list,qtd = Msc.GetList()
		esq = []
		dir = []
		tam = qtd[pag_atual]
		qtd_opus = len(qtd)
		voltar = False
		score_aux =score_number = 0
		ajuda = False
		#LACO DO MENU 1
		while (voltar == False):
			esq = []
			dir = []
			#CALCULA QUAIS PAGINAS MOSTRAR
			if pag_atual < qtd_opus:
				if pag_atual == 0:
					score_number= i = 0
					limit =qtd[pag_atual]
				else:
					score_number =i = qtd[pag_atual-1]
				while i < qtd[pag_atual]:
					esq.append(self.Carolingia_20.render(arruma_texto(list[i]), False, (226, 157, 54) ))
					i+=1
			if pag_atual +1 < qtd_opus:
				i = qtd[pag_atual]
				while i <qtd[pag_atual+1]:
					dir.append(self.Carolingia_20.render(arruma_texto(list[i]), False, (226, 157, 54) ))
					i+=1
			sair = mudar = False
			score_aux = score_number
			#LACO DO MENU 2
			while (sair == False):
				score_number = score_aux
				#PEGA EVENTOS
				for evento in pygame.event.get():
					#EVENTOS DO MOUSE
					px , py = pygame.mouse.get_pos()
					if ((px>= 729)and (px<=760)) and ((py>= 82)and (py<=110)):
						ajuda = True
					else:
						ajuda = False
					if evento.type == pygame.MOUSEBUTTONUP:
						if Bleft == True:
							px , py = pygame.mouse.get_pos()
							if ((px>= 280)and (px<=348)) and ((py>= 500)and (py<=568)):
								msc_atual = 0
								if lado == 0:
									pag_atual -=2
									if pag_atual <0:
										pag_atual = qtd_opus-2
										lado = 1
									sair = mudar = True
								else:
									lado = 0
									tam = len(dir)
							if ((px>= 450)and (px<=518)) and ((py>= 500)and (py<=568)):
								msc_atual = 0
								if lado == 1:
									pag_atual +=2
									if pag_atual > (qtd_opus-2):
										pag_atual = 0
										lado = 0
									sair = mudar = True
								else:
									lado = 1
									tam = len(esq)
							if ((px>= 70)and (px<=270)) and ((py>= 510)and (py<=560)):
								btn_jogar.click()
								sair = True
							if ((px>= 530)and (px<=730)) and ((py>= 510)and (py<=560)):
								btn_voltar.click()
								mudar =voltar = sair = True
								#return False
							if (len(esq) > len(dir)):
								num = len(esq)
							else:
								num = len(dir)
							aux = Const_default_y+(((-1)*(num/2))*30)
							num2 =0
							for i in range(len(esq)):						
								if ((px>= 65)and (px<=397)) and ((py>= aux+30*num2) and (py<=aux+30*(num2)+25)):
									if (lado == 0)  and (msc_atual == num2):
										sair = True
									else:
										msc_atual = num2
										lado = 0
								num2 += 1
							num2 = 0
							for i in range(len(dir)):
								if ((px>= 415)and (px<=747)) and ((py>= aux+30*num2) and (py<=aux+30*(num2)+25)):
									if (lado == 1)  and (msc_atual == num2):
										sair = True
									else:
										msc_atual = num2
										lado = 1
								num2 += 1
							Bleft == False
					if evento.type == pygame.MOUSEBUTTONDOWN:
						Bleft,Bmiddle, Bright =  pygame.mouse.get_pressed()
					if evento.type == pygame.QUIT:
						sys.exit(0)
					#EVENTOS DO TECLADO
					if evento.type == pygame.KEYDOWN:
						if evento.key == pygame.K_RETURN:
							sair = True
						if evento.key == pygame.K_ESCAPE:
							return False
							msc_atual = -1
						if evento.key == pygame.K_LEFT:
							msc_atual = 0
							if lado == 0:
								pag_atual -=2
								if pag_atual < 0:
									pag_atual = qtd_opus-2
								lado = 1
								sair = mudar = True
							else:
								lado = 0
								tam = len(esq)
								
						if evento.key == pygame.K_RIGHT:
							msc_atual = 0
							if lado == 1:
								pag_atual +=2
								if pag_atual >(qtd_opus-2):
									pag_atual = 0
								lado = 0
								sair = mudar = True
							else:
								lado = 1
								tam = len(dir)
						if evento.key == pygame.K_DOWN:
							msc_atual += 1
							if msc_atual > tam-1:
								msc_atual = 0
						if evento.key == pygame.K_UP:
							msc_atual -= 1
							if msc_atual < 0:
								msc_atual = tam-1
				
				#Desenha Fundo
				self.tela.blit(bkg,(0,0))
				#Escreve Numero das paginas esquerda e direita
				self.tela.blit(self.Carolingia_20.render((repr(pag_atual+1)), False, (226, 157, 54) ),(230,128))
				self.tela.blit(self.Carolingia_20.render((repr(pag_atual+2)), False, (226, 157, 54) ),(590,128))
				self.tela.blit(self.Carolingia_25.render(self.lang.Get(19), False, (226, 157, 54) ),(70,520))
				self.tela.blit(self.Carolingia_25.render(self.lang.Get(1), False, (226, 157, 54) ),(576,520))
				#self.tela.blit(self.Carolingia_25.render(("High Score:  "+repr(msc_atual)), False, (226, 157, 54) ),(0,0))
				#Desenha botoes
				self.tela.blit(btn_jogar.desenha(),(70,510))
				self.tela.blit(btn_red_e.desenha(),(280,500))
				self.tela.blit(btn_red_d.desenha(),(450,500))
				self.tela.blit(btn_voltar.desenha(),(530,510))
				#escreve texto dos botoes
				self.tela.blit(btn_list_text[0],(90,520))
				self.tela.blit(btn_list_text[2],(310,520))
				self.tela.blit(btn_list_text[3],(480,520))
				self.tela.blit(btn_list_text[1],(600,520))
				#ESCREVE ITENS DA PAGINA ESQUERDA
				if (len(esq) > len(dir)):
					num = len(esq)
				else:
					num = len(dir)
				num2 = (-1)*(num/2)
				for i in range(len(esq)):
					aux = Const_default_y+(num2*30)
					num2 += 1
					if (lado == 0):
						if (i == msc_atual):
							self.tela.blit(selected,(60,aux-2))
						else:
							self.tela.blit(unselected,(60,aux-2))
					else:
						self.tela.blit(unselected,(60,aux-2))
					self.tela.blit(esq[i],(65,aux))
					self.tela.blit(self.Carolingia_20.render((repr((self.profile.Get_Q()[score_number])[1])), False, (226, 157, 54) ),(330,aux))
					score_number+=1
				#ESCREVE ITENS DA PAGINA DIREITA
				num2 = (-1)*(num/2)
				for i in range(len(dir)):
					aux = Const_default_y+(num2*30)
					num2 += 1
					if (lado == 1):
						if (i == msc_atual):
							self.tela.blit(selected,(410,aux-2))
						else:
							self.tela.blit(unselected,(410,aux-2))
					else:
						self.tela.blit(unselected,(410,aux-2))
					self.tela.blit(dir[i],(415,aux))
					self.tela.blit(self.Carolingia_20.render((repr((self.profile.Get_Q()[score_number])[1])), False, (226, 157, 54) ),(700,aux))
					score_number+=1
				#DESENHA O MOUSE
				self.tela.blit(self.cursor_picture, pygame.mouse.get_pos())
				if ajuda == True:
					self.help()
				#atualiza a tela
				pygame.display.flip()
				if btn_jogar.getState() or btn_voltar.getState():
					time.sleep(0.2)
			#CHAMA GAMEPLAY
			if (msc_atual >= 0) and (mudar == False):
				if (pag_atual == 0) and lado == 0:
					music_number = msc_atual
				else:
					music_number =msc_atual+qtd[pag_atual-1+lado] #msc_atual+qtd[pag_atual]+lado
				#print (repr(msc_atual)+"|"+repr(qtd[pag_atual+lado])+"|"+repr(lado))
				# [0]1 [2]3 [4]5 [6]
				#print (music_number)
				#if (((self.profile.Get_V()[music_number-1])[2]) >= 50) or (music_number == 0):
				music = Music(Msc.GetOne(music_number))
				Game = Gameplay(self.tela, self.lang, music.GetTable(), music.GetName(), music.GetTempo(), self.config.Get_lvl(), self.config.Get_audio(), music.GetHeaderTicks())
				#recebe os valores de pontuacao
				point, miss, maxcombo,perform = Game.Play()
				if point == miss and miss == maxcombo and maxcombo==perform and perform == 0:
					#chama tela de exibicao
					self.Mostra(point,miss,maxcombo,perform)
				else:
					#verificar a pontuacao
					self.profile.Update_Q(Msc.GetOne(music_number),point)
					self.High_S.Update (Msc.GetOne(music_number),point, self.profile.nome)
					#salva a pontuacao
					self.profile.save()
					#chama tela de exibicao
					self.Mostra(point,miss,maxcombo,perform)
    def login(self,db):        
        win = GraphWin("CofC Scrabble",300,300)
        win.setCoords(0,0,100,100)

        Text(Point(17,80),"User: "******"Password: "******"")
        message.draw(win)

        # Create a login button and a quit button
        login_button = Button("New game",Point(5,50),Point(35,60))
        login_button.draw(win)

        continue_button = Button("Continue game",Point(5,35),Point(50,45))
        continue_button.draw(win)
        game_id_entry = Entry(Point(70,40),10)
        game_id_entry.draw(win)

        new_button = Button("New user",Point(5,2),Point(35,12))
        new_button.draw(win)

        change_button = Button("Change Password",Point(45,2),Point(95,12))
        change_button.draw(win)

        quit_button = Button("Quit",Point(5,15),Point(25,25))
        quit_button.draw(win)
        
        while True: # Maximum number of clicks
            p = win.getMouse()
            if login_button.clicked(p):
                user1 = user_entry.getText()
                password1 = password_entry.getText()
                if db.valid_user(user1,password1):
                    self.player = db.get_user(user1)
                    win.close()
                    return "new"
                else:
                    message.setText("Invalid user and/or password")
            elif continue_button.clicked(p):
                user1 = user_entry.getText()
                password1 = password_entry.getText()
                gid = int(game_id_entry.getText())
                in_progress = Game.is_game_in_progress(gid)
                if db.valid_user(user1,password1) and in_progress:
                    self.player = db.get_user(user1)
                    win.close()
                    return gid
                else:
                    message.setText("Invalid user/password or game ID")
            elif new_button.clicked(p):
                screen = CreateNewUserScreen()
                screen.create_new_user(db)
            elif change_button.clicked(p):
                screen = ChangePasswordScreen()
                screen.change_password(db)
            elif quit_button.clicked(p):
                win.close()
                return "quit"
Exemple #58
0
class ChessGUI:

	def __init__(self):
		"""Creates a GUI object for use with Chess, complete with Mouse, Square, and Message functionality."""

		# Determining the width and length
		self.width = 1000
		self.height = 700

		# Create the square colors
		self.darkSquareColor = "LightSteelBlue1"
		self.darkSquareColorHighlighted = "blue2"

		self.lightSquareColor = "MistyRose2"
		self.lightSquareColorHighlighted = "maroon1"

		# Create the line color
		self.lineColor = "black"

		# Creating the graphics window
		self.window = GraphWin("Chess!!!", self.width, self.height)

		# Creating the background color
		self.background = "honeydew2"

		# Filling in the background color
		self.window.setBackground(self.background)

		# Set the size of the chess board
		self.boardLength = self.height * 7 / 8

		# Creating the interaction options

		self.messageBox = Text(Point(self.width * 10 / 12, self.height * 1 / 4), "")
		self.messageBox.draw(self.window)
		self.messageBox.setFace("times roman")

		self. moveBox = Text(Point(self.width * 10 / 12, self.height * 1 / 2), "")
		self.moveBox.draw(self.window)
		self.moveBox.setFace("times roman")

		self.quitButton = Button(self.window, Point(self.width * 10 / 12, self.height * 2 / 3), 70, 40, "Quit", "CadetBlue1")
		self.resetButton = Button(self.window, Point(self.width * 10 / 12, self.height * 5 / 6), 70, 40, "New Game!", "CadetBlue1")

		self.quitButton.activate()

		# Create the squared grid
		self.listOfSquares = [[],[],[],[],[],[],[],[]]
		alpha = ["a","b","c","d","e","f","g","h"]
		numbers = ["1","2","3","4","5","6","7","8"]
		labelsX,labelsY = [],[]

		for i in range(8):
			for j in range(8):
				if(i % 2 == 0 and j % 2 != 0) or (i % 2 != 0 and j % 2 == 0):
					self.listOfSquares[i].append(Square(self.darkSquareColor, self.darkSquareColorHighlighted, self.lineColor, self.boardLength * i / 8 + self.width * 1 / 18, self.boardLength * j / 8 + self.height * 1/18, self.boardLength / 8))
				else:
					self.listOfSquares[i].append(Square(self.lightSquareColor, self.lightSquareColorHighlighted, self.lineColor, self.boardLength * i / 8 + self.width * 1 / 18, self.boardLength * j / 8 + self.height * 1/18, self.boardLength / 8))
				labelsY.append(Text(Point(self.width * 1 / 18 + self.boardLength + 15, self.boardLength * j / 8 + self.height * 1/18 + self.boardLength / 16), numbers[7-j]))
			labelsX.append(Text(Point(self.boardLength * i / 8 + self.width * 1 / 18 + self.boardLength / 16, self.height * 1/18 - 14), alpha[i]))

		# Draw the squares
		for squareList in self.listOfSquares:
			for square in squareList:
				square.draw(self.window)

		# Draw the labels
		for i in range(8):
			labelsX[i].draw(self.window)
			labelsY[i].draw(self.window)

		# Create the border lines
		self.borderLine1 = Line(Point(self.width * 1 / 18, self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.height * 1/18))
		self.borderLine2 = Line(Point(self.width * 1 / 18, self.height * 1/18), Point(self.width * 1 / 18, self.boardLength + self.height * 1/18))
		self.borderLine3 = Line(Point(self.boardLength + self.width * 1 / 18, self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.boardLength + self.height * 1/18))
		self.borderLine4 = Line(Point(self.width * 1 / 18, self.boardLength + self.height * 1/18), Point(self.boardLength + self.width * 1 / 18, self.boardLength + self.height * 1/18))

		# Draw the border lines
		self.borderLine1.draw(self.window)
		self.borderLine2.draw(self.window)
		self.borderLine3.draw(self.window)
		self.borderLine4.draw(self.window)

		# Change the color of the border lines
		self.borderLine1.setFill(self.lineColor)
		self.borderLine2.setFill(self.lineColor)
		self.borderLine3.setFill(self.lineColor)
		self.borderLine4.setFill(self.lineColor)

		# Create a list of highlighted squares to reduce lag
		self.highlightedSquares = []

	def getSquare(self, requestedSquare):
		"""Returns the square requested by the format of either[letter,number] or [number,number]. Works with Tuples too."""

		# Two branches in case the protocol is changed
		if(type(requestedSquare[0]) == int):
			return self.listOfSquares[requestedSquare[0]][requestedSquare[1]]
		else:
			# Use .index to convert letter to number
			return self.listOfSquares[["a","b","c","d","e","f","g","h","i"].index(requestedSquare[0])][requestedSquare[1] - 1]

	def getClickedSquare(self, point):
		"""Returns the the square at the given point, or returns false."""

		# Set a default return value		
		returnValue = False

		# Cycle through all squares to find the clicked square
		for squareList in self.listOfSquares:
			for square in squareList:
				if square.clicked(point):
					returnValue = square

		return returnValue

	def getInput(self):
		"""Validates input, waiting until a square is clicked or the quitButton is quit and returning the selected square or a QuitError."""
		while True:
			clickPoint = self.window.getMouse()
			# Test the point
			if(self.getClickedSquare(clickPoint)):
				squareToReturn = self.getClickedSquare(clickPoint)
				return(self.getIndex(squareToReturn))
				break
			elif(self.quitButton.clicked(clickPoint)):
				raise NotImplementedError("Quit by user.")

	def getIndex(self, square):
		"""Gets the X and Y of a given squarem, or returns to False, False for an error."""
		# Scan all squares to check for a match
		x = False
		y = False
		for i in range(8):
			for j in range(8):
				if(self.listOfSquares[i][j] == square):
					x = i
					y = j
		# Format the return
		tupleToReturn = (x,y)
		return(tupleToReturn)

	def getMouse(self):
		"""Gets a mouse in the window and returns the given point."""
		mouseClick = self.window.getMouse()
		return(mouseClick)

	def printMessage(self, Message):
		"""Prints a message on screen."""
		# Make sure the message ends in a period
		if(Message[-1] != "." and Message[-1] != "!"):
			Message += "."
		self.messageBox.setText(Message)

	def draw(self, objectToBeDrawn):
		"""Draws and object with proper encapsulation."""
		objectToBeDrawn.draw(self.window)

	def highlightSelectedSquare(self, requestedSquare):
		"""Highlights the square at a given coordinate."""
		# Add the square to highlighted squares and highlight it
		squareToHighlight = self.getSquare(requestedSquare)
		self.highlightedSquares.append(squareToHighlight)
		squareToHighlight.highlight()

	def unHighlightSelectedSquare(self, requestedSquare):
		"""Unhighlights the square at a given coordinate."""
		self.getSquare(requestedSquare).unHighlight()

	def unHighlightAllSquares(self):
		"""Unhighlights all squares."""
		# Use selected squares to reduce lag
		for square in self.highlightedSquares:
			square.unHighlight()
		self.highlightedSquares = []

	def clearMessage(self):
		"""Clears the message being displayed."""
		self.messageBox.setText("")

	def printMoves(self, message):
		"""Prints the move message on screen."""
		# Add a period to the end if needed
		if(message[-1] != "."):
			message += "."
		# Print the message
		self.moveBox.setText(message)

	def clearMoves(self):
		"""Clears the move message."""
		self.moveBox.setText("")

	def closeWindow(self):
		"""Closes the window."""
		self.window.close()

	def reset(self):
		"""Resets the GUI window for a new game."""
		# Wait for the reset button to be clicked
		self.resetButton.activate()
		while True:
			clickPoint = self.window.getMouse()
			# Check input
			if(self.resetButton.clicked(clickPoint)):
				break
			elif(self.quitButton.clicked(clickPoint)):
				raise NotImplementedError("Quit by user.")

		# Unhighlight all Squares
		for squareList in self.listOfSquares:
			for square in squareList:
				square.unHighlight()

		# Reset the GUI Message
		self.messageBox.setText("New game! White goes first.")
Exemple #59
0
def play():
    #draw window
    win = GraphWin("Hangman",300,300, autoflush = False)
    
    #close and play buttons , and opening text
    close = Button('Quit', Point(273, 5), Point(295, 18), win)
    PLAY = Button('PLAY!', Point(100,100), Point(200,200), win)
    PLAY.setTextSize(24)
    hangmanText = Text(Point(150,80), "Hangman!")
    hangmanText.setSize(22)
    hangmanText.setFill('blue')
    hangmanText.draw(win)

    #wait for play or close to be clicked
    p = win.getMouse()
    while not close.buttonClicked(p):
        if PLAY.buttonClicked(p):
            PLAY.hide()
            hangmanText.undraw()
            break
        p = win.getMouse()

    #make playAgain and restart buttons
    playAgain = Button('Play Again', Point(230,270), Point(290,290), win)
    playAgain.hide()
    restart = Button('Restart', Point(230,270), Point(290,290), win)
    restart.hide()

    #draw hangman stand
    drawStand(win)   

    #draw letter buttons
    a = Button('A', Point(30,19), Point(40,30), win)
    b = Button('B', Point(42,19), Point(52,30), win)
    c = Button('C', Point(54,19), Point(64,30), win)
    d = Button('D', Point(66,19), Point(76,30), win)
    e = Button('E', Point(78,19), Point(88,30), win)
    f = Button('F', Point(90,19), Point(100,30), win)
    g = Button('G', Point(102,19), Point(112,30), win)
    h = Button('H', Point(114,19), Point(124,30), win)
    i = Button('I', Point(126,19), Point(136,30), win)
    j = Button('J', Point(138,19), Point(148,30), win)
    k = Button('K', Point(150,19), Point(160,30), win)
    l = Button('L', Point(162,19), Point(172,30), win)
    m = Button('M', Point(174,19), Point(184,30), win)
    n = Button('N', Point(186,19), Point(196,30), win)
    o = Button('O', Point(198,19), Point(208,30), win)
    Lp = Button('P', Point(210,19), Point(220,30), win)
    q = Button('Q', Point(30,35), Point(40,45), win)
    r = Button('R', Point(42,35), Point(52,45), win)
    s = Button('S', Point(54,35), Point(64,45), win)
    t = Button('T', Point(66,35), Point(76,45), win)
    u = Button('U', Point(78,35), Point(88,45), win)
    v = Button('V', Point(90,35), Point(100,45), win)
    w = Button('W', Point(102,35), Point(112,45), win)
    x = Button('X', Point(114,35), Point(124,45), win)
    y = Button('Y', Point(126,35), Point(136,45), win)
    z = Button('Z', Point(138,35), Point(148,45), win)
        
    #draw difficulty buttons
    easy = Button('Easy', Point(230, 50), Point(280, 62), win)
    med = Button('Medium', Point(230,65), Point(280, 77), win)
    hard = Button('Hard', Point(230, 80), Point(280, 92), win)
    random = Button('Random', Point(230,95),Point(280,107),win)

    #define order for body drawing
    bodyOrder = ['head','torso','leftArm','rightArm','leftLeg','rightLeg']

    #START GAME LOOP
    while not close.buttonClicked(p):

        #select difficulty prompt
        selectDifficulty = Text(Point(170,60), 'Select difficulty >>>')
        selectDifficulty.draw(win)
        #CLICK LOOP REGIONvvvvvvvvvvvvv
        p = win.getMouse()
        #inf loop, difficulty selection (or close) breaks loop
        while 1==1:
            if easy.buttonClicked(p):
                mode = 'Easy'
                easy.deactivate()
                break
            elif med.buttonClicked(p):
                mode = 'Medium'
                med.deactivate()
                break
            elif hard.buttonClicked(p):
                mode = 'Hard'
                hard.deactivate()
                break
            elif random.buttonClicked(p):
                mode = 'Random'
                random.deactivate()
                break
            elif close.buttonClicked(p):
                win.close()
                return 0
            else:
                #if nothing clicked, get mouse
                p = win.getMouse()
        #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        #GAME STARTS HERE!!!

        #unhide restart button
        restart.unhide()

        #display current mode, undraw difficulty prompt
        modeT = Text(Point(230, 120), "Mode: " + mode)
        modeT.draw(win)
        selectDifficulty.undraw()

        #choose words, set spaces, get length
        word = chooseWord(mode)
        drawSpaces(len(word),win)
        length = len(word)

        '''vvv old length usage - out dated vvv'''
        #gLength = gameWordLength(word)
        #print(gLength)
        '''^^^ old length usage - out dated ^^^'''

        #set default letter, loseCount, winCount,
        #L for drawing list, and notChosenList
        letter = ''
        loseCount = 0
        winCount = 0
        L = ['0']
        notChosenList=['a','b','c','d','e','f','g','h','i','j','k','l','m',
                   'n','o','p','q','r','s','t','u','v','w','x','y','z']

        #CLICK LOOP REGIONvvvvvvvvvvvvvvvvvvv
        p = win.getMouse()
        while not close.buttonClicked(p):
            #if restart pressed, break back to game loop
            #if letter pressed, set letter
            if restart.buttonClicked(p):
                break
            if a.buttonClicked(p):
                a.deactivate()
                letter = 'a'
            elif b.buttonClicked(p):
                b.deactivate()
                letter = 'b'
            elif c.buttonClicked(p):
                c.deactivate()
                letter = 'c'
            elif d.buttonClicked(p):
                d.deactivate()
                letter = 'd'
            elif e.buttonClicked(p):
                e.deactivate()
                letter = 'e'
            elif f.buttonClicked(p):
                f.deactivate()
                letter = 'f'
            elif g.buttonClicked(p):
                g.deactivate()
                letter = 'g'
            elif h.buttonClicked(p):
                h.deactivate()
                letter = 'h'
            elif i.buttonClicked(p):
                i.deactivate()
                letter = 'i'
            elif j.buttonClicked(p):
                j.deactivate()
                letter = 'j'
            elif k.buttonClicked(p):
                k.deactivate()
                letter = 'k'
            elif l.buttonClicked(p):
                l.deactivate()
                letter = 'l'
            elif m.buttonClicked(p):
                m.deactivate()
                letter = 'm'
            elif n.buttonClicked(p):
                n.deactivate()
                letter = 'n'
            elif o.buttonClicked(p):
                o.deactivate()
                letter = 'o'
            elif Lp.buttonClicked(p):
                Lp.deactivate()
                letter = 'p'
            elif q.buttonClicked(p):
                q.deactivate()
                letter = 'q'
            elif r.buttonClicked(p):
                r.deactivate()
                letter = 'r'
            elif s.buttonClicked(p):
                s.deactivate()
                letter = 's'
            elif t.buttonClicked(p):
                t.deactivate()
                letter = 't'
            elif u.buttonClicked(p):
                u.deactivate()
                letter = 'u'
            elif v.buttonClicked(p):
                v.deactivate()
                letter = 'v'
            elif w.buttonClicked(p):
                w.deactivate()
                letter = 'w'
            elif x.buttonClicked(p):
                x.deactivate()
                letter = 'x'
            elif y.buttonClicked(p):
                y.deactivate()
                letter = 'y'
            elif z.buttonClicked(p):
                z.deactivate()
                letter = 'z'
            #no letter pressed
            else:
                letter = ''

            #if letter was pressed
            if letter != '':
                #find letter, show letter
                L = findLetter(word, letter)
                showLetter(L,word,win)
                '''if letter in word:
                    winCount+=1'''
                #set winCount -
                #if letter in word one or multiple times, sets accordingly
                for letters in word:
                    if letters == letter:
                        winCount+=1
                #if letter hasn't been used, remove from notChosenList
                if letter in notChosenList:
                    notChosenList.remove(letter)

            #L==[] when the letter is not in word
            #in this case, add to lose count, draw according body part
            if L == []:
                loseCount+=1
                body = bodyOrder[loseCount-1]

                if body == 'head':
                    drawHead(win)
                elif body == 'torso':
                    drawTorso(win)
                elif body == 'leftArm':
                    drawLeftArm(win)
                elif body == 'rightArm':
                    drawRightArm(win)
                elif body == 'leftLeg':
                    drawLeftLeg(win)
                elif body == 'rightLeg':
                    drawRightLeg(win)

            #WIN-------------------------!!!!!!!!!!!!!!!!!!!
            #v old winCount, do not use
            #if winCount == gLength:
            #^old winCount, do not use
            if winCount == length:
                #display large green text 'you win'
                winText = Text(Point(100,200), "YOU WIN!!!")
                winText.setFill('green')
                winText.setSize(22)
                winText.draw(win)
                #CLICK LOOP REGIONvvvvvv
                #play again or quit
                playAgain.unhide()
                while 1==1:
                    p = win.getMouse()
                    if playAgain.buttonClicked(p):
                        break
                    elif close.buttonClicked(p):
                        win.close()
                        return 0
                break
                #^^^^^^^^^^^^^^^^^^^^^^^^^^
                
            #LOSE------------------------!!!!!!!!!!!!!!!!!!
            #at loseCount == 6, all body parts drawn, you lose
            elif loseCount == 6:
                #display large red text 'you lose'
                loseText = Text(Point(100,200), "YOU LOSE")
                loseText.setFill('red')
                loseText.setSize(22)
                loseText.draw(win)
                displayWord(notChosenList,word,win)
                #CLICK LOOP REGIONvvvvvvvvvvvvvvv'
                #play again or quit
                playAgain.unhide()
                while 1==1:
                    p = win.getMouse()
                    if playAgain.buttonClicked(p):
                        break
                    elif close.buttonClicked(p):
                        win.close()
                        return 0
                #^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                break
            
            #no buttons clicked
            else:
                p = win.getMouse()
                L = [0]
                letter = ''
        #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        #----------------------------------------------
        #RESET DISPLAY
        if winCount == length:
            winText.undraw()
        elif loseCount == 6:
            loseText.undraw()

        easy.activate()
        med.activate()
        hard.activate()
        random.activate()
        modeT.undraw()
        playAgain.hide()
        clearWord = Rectangle(Point(0,230),Point(300,250))
        clearWord.setFill('white')
        clearWord.setOutline('white')
        clearWord.draw(win)
        clearBody = Rectangle(Point(105,85),Point(135,145))
        clearBody.setFill('white')
        clearBody.setOutline('white')
        clearBody.draw(win)

        a.activate()
        b.activate()
        c.activate()
        d.activate()
        e.activate()
        f.activate()
        g.activate()
        h.activate()
        i.activate()
        j.activate()
        k.activate()
        l.activate()
        m.activate()
        n.activate()
        o.activate()
        Lp.activate()
        q.activate()
        r.activate()
        s.activate()
        t.activate()
        u.activate()
        v.activate()
        w.activate()
        x.activate()
        y.activate()
        z.activate()

        #RESET DISPLAY^^^
        #-----------------------------------------------------
        
    #close window at loop break
    win.close()
Exemple #60
0
def main():
    player = characterchoose()
    
    #Draws new window in which the rest of the game will take place
    win1 = GraphWin("Esperium", 1000, 800)
    win1.setCoords(0, 0, 15, 11)
    win1.setBackground('black')

    #Draws quit button
    q = Button(win1, Point(1, 10), 0.5, 0.5, "X", 'gray')
    
    #Draws character
    if player.getHP() == 30:
        pshape = Circle(Point(7.5, 2), 1)
        pshape.setFill('lightblue')
        pshape.draw(win1)
    elif player.getHP() == 50:
        pshape = Circle(Point(7.5, 2), 1)
        pshape.setFill('red')
        pshape.draw(win1)
    else:
        pshape = Circle(Point(7.5, 2), 1)
        pshape.setFill('green')
        pshape.draw(win1)

    #Creates text box for instructions
    textbox = Button(win1, Point(7.5, 6), 8, 2, "", 'gray')
    text = Text(Point(7.5, 6), "Ready yourself! Enemies approach! \n[Click here to continue]")
    text.draw(win1)

    #Creates and draws enemies
    enemy1 = enemy()
    enemy2 = enemy()
    enemy3 = enemy()

    e1 = Button(win1, Point(3, 8), 1.5, 1.5, "ORC 1", 'purple')
    e2 = Button(win1, Point(7, 8), 1.5, 1.5, "ORC 2", 'purple')
    e3 = Button(win1, Point(11, 8), 1.5, 1.5, "ORC 3", 'purple')

    p = win1.getMouse()

    if textbox.clicked(p):
        text.setText("Click an enemy to attack them")
        
    #COMBAT
    p = win1.getMouse()
    while not q.clicked(p):
        p = win1.getMouse()

        if e1.clicked(p):
            enemy1.attacked()
            text.setText("ORC 1 hit!")
            player.attacked()
            if player.edied():
                text.setText("You have died. Poor mortal. Click the 'X' to quit.")
            if enemy1.edied():
                e1.deactivate()
                text.setText("ORC 1 is dead!")
        elif e2.clicked(p):
            enemy2.attacked()
            text.setText("ORC 2 hit!")
            player.attacked()
            if player.edied():
                text.setText("You have died. Poor mortal. Click the 'X' to quit.")
            if enemy2.edied():
                e2.deactivate()
                text.setText("ORC 2 is dead!")
        elif e3.clicked(p):
            enemy3.attacked()
            text.setText("ORC 3 hit!")
            player.attacked()
            if player.edied():
                text.setText("You have died. Poor mortal. Click the 'X' to quit.")
            if enemy3.edied():
                e3.deactivate()
                text.setText("ORC 3 is dead!")
        elif q.clicked(p):
            win1.close()
        else:
            p = win1.getMouse()

        #BOSS BATTLE!
        if enemy1.edied() and enemy2.edied() and enemy3.edied():
            dragon = boss()
            b1 = Button(win1, Point(7.5, 9), 12, 3, "ELDER DRAGON", 'orange')
            player.setHP(25)
            text.setText("Your health has been restored!")
            p = win1.getMouse()
            while not q.clicked(p):
                if b1.clicked(p):
                    dragon.attacked()
                    text.setText("Elder Dragon hit!")
                    player.attacked()
                    if player.edied():
                        text.setText("You were roasted to a crisp. Click the 'X' to quit.")
                        b1.deactivate()
                    if dragon.edied():
                        b1.deactivate()
                        text.setText("You did it! You vanquished the beast! Dance for joy! \n[Click the 'X' to quit]")
                if q.clicked(p):
                    win1.close()
                p = win1.getMouse()
                
    win1.close()