示例#1
0
class EstadoSom(Estado):
    def __init__(self):
        super().__init__()
        self.__texto_som = Texto("Som", "Materials/Early GameBoy.ttf", 50, self.BLACK, [130, 40])
        
        self.__texto_musica = Texto("Volume música:", "Materials/Retro Gaming.ttf", 25, self.WHITE, [20, 150])
        self.__texto_efeitos = Texto("Volume efeitos:", "Materials/Retro Gaming.ttf", 25, self.WHITE, [20, 300])
        
        self.__slider_musica = Slider(self.tela.display, 20, 230, 300, 20, min=0, max=1, step=0.1, handleColour=self.GREEN)
        self.__slider_musica.setValue(self.som_controller.volume_atual_music)
        self.__slider_sons = Slider(self.tela.display, 20, 380, 300, 20, min=0, max=1, step=0.1, handleColour=self.GREEN)
        self.__slider_sons.setValue(self.som_controller.volume_atual_sound)
        self.__sliders = [self.__slider_musica, self.__slider_sons]
        self.__events_som = EventsSom(self.__sliders)

        self.__numero_musica = Texto("", "Materials/Retro Gaming.ttf", 25, self.WHITE, [335, 225])
        self.__numero_sons = Texto("", "Materials/Retro Gaming.ttf", 25, self.WHITE, [335, 375])
        
        self.__imagem_botao_voltar = pygame.image.load("Materials/voltar.png").convert_alpha(self.tela.display)
        self.__fundo_voltar = Fundo([20, 510, 70, 70], self.WHITE)
        self.__botao_voltar = BotaoImagem(self.__imagem_botao_voltar, (25, 515), self.__fundo_voltar, self.GREEN, self.DARK_GREEN, self.__events_som)
        
        self.__texto_vol_padrao = Texto("Volume Padrão", "Materials/Retro Gaming.ttf", 27, self.BLACK, [125, 525])
        self.__fundo_vol_padrao = Fundo([110, 510, 270, 70], self.WHITE)
        self.__botao_vol_padrao = Botao(self.__texto_vol_padrao, self.__fundo_vol_padrao, self.GREEN, self.DARK_GREEN, self.__events_som)


    def start(self):
        #Updates
        self.__events_som.check_events()
        self.som_controller.set_volume_music(self.__slider_musica.getValue())
        self.som_controller.set_volume_sounds(self.__slider_sons.getValue())
        voltar = self.__botao_voltar.update()
        padrao = self.__botao_vol_padrao.update()
        if padrao:
            self.som_controller.set_volume_padrao()
            self.__slider_musica.setValue(self.som_controller.volume_atual_music)
            self.__slider_sons.setValue(self.som_controller.volume_atual_sound)
        
        porcentagem_musica = self.__slider_musica.getValue() * 100
        porcentagem_sons = self.__slider_sons.getValue() * 100
        self.__numero_musica.texto = str(int(porcentagem_musica)) + "%"
        self.__numero_sons.texto = str(int(porcentagem_sons)) + "%"

        #Draws
        self.tela.fill(self.GREY)
        self.__texto_som.draw()
        self.__texto_musica.draw()
        self.__texto_efeitos.draw()
        self.__slider_musica.draw()
        self.__slider_sons.draw()
        self.__numero_musica.draw()
        self.__numero_sons.draw()
        self.__botao_voltar.draw()
        self.__botao_vol_padrao.draw()

        if voltar:
            return "inicial"
        else:
            return "som"
示例#2
0
class LabeledSlider:
    def __init__(self,
                 screen,
                 pos_x,
                 pos_y,
                 label_text,
                 width=200,
                 label_size=150,
                 min=0.0,
                 max=1.0,
                 initial=0.5,
                 margin=20):
        self.width = width
        self.label_size = label_size

        self.label = TextBox(screen, pos_x, pos_y, label_size, 30, fontSize=16)
        self.label.setText(label_text)
        self.slider = Slider(screen,
                             pos_x + self.label_size + margin,
                             pos_y,
                             self.width,
                             20,
                             min=min,
                             max=max,
                             step=0.01,
                             initial=initial)
        self.output = TextBox(screen,
                              pos_x + self.label_size + self.width +
                              margin * 2,
                              pos_y,
                              30,
                              20,
                              fontSize=10)

    def draw(self):
        self.label.draw()
        self.slider.draw()
        self.output.draw()

    def update(self, events):
        self.slider.listen(events)
        self.output.setText("%.2f" % self.slider.getValue())

    def get_value(self):
        return self.slider.getValue()

    def set_value(self, value):
        self.slider.setValue(value)
示例#3
0
    def show_options_screen(self):
        bg = pg.image.load(background_path('japan_menu.png'))
        bg = pg.transform.scale(bg, WINDOW_SIZE)
        button_width = 200
        button_height = 50
        x = WIDTH // 16
        y = HEIGHT // 16
        sliderMusic = Slider(self.screen,
                             WIDTH // 3,
                             y * 5,
                             WIDTH // 3,
                             40,
                             min=0,
                             max=100,
                             step=1,
                             colour=DARKGREY,
                             handleColour=LIGHTGREY,
                             handleRadius=30,
                             initial=self.audioplayer.get_music_volume())
        sliderSounds = Slider(self.screen,
                              WIDTH // 3,
                              y * 7,
                              WIDTH // 3,
                              40,
                              min=0,
                              max=100,
                              step=1,
                              colour=DARKGREY,
                              handleColour=LIGHTGREY,
                              handleRadius=30,
                              initial=self.audioplayer.get_sound_volume())
        outputMusic = TextBox(self.screen,
                              sliderMusic.getX() + sliderMusic.getWidth() + 50,
                              y * 5,
                              50,
                              40,
                              fontSize=30)
        outputSounds = TextBox(self.screen,
                               sliderSounds.getX() + sliderSounds.getWidth() +
                               50,
                               y * 7,
                               50,
                               40,
                               fontSize=30)
        running_options = True
        while running_options:
            self.screen.blit(bg, (0, 0))
            draw_text('Options', self.font, WHITE, self.screen,
                      WIDTH // 2 - len('Options') * button_width // 30, y * 3)

            mx, my = pg.mouse.get_pos()

            button_exit = pygame.Rect(x * 5, y * 14, button_width,
                                      button_height)
            button_save = pygame.Rect(x * 9, y * 14, button_width,
                                      button_height)

            if button_exit.collidepoint((mx, my)):
                if self.click:
                    running_options = False
            if button_save.collidepoint((mx, my)):
                if self.click:
                    running_options = False
                    self.audioplayer.set_sounds_volume(sliderSounds.getValue())
                    self.audioplayer.set_music_volume(sliderMusic.getValue())

            pygame.draw.rect(self.screen, LIGHTGREY, button_exit)
            pygame.draw.rect(self.screen, LIGHTGREY, button_save)

            draw_text(
                'Exit', self.font, WHITE, self.screen,
                x * 5 + button_width // 2 - len('Exit') * button_width // 30,
                y * 14 + button_height // 2 - 11)
            draw_text(
                'Save', self.font, WHITE, self.screen,
                x * 9 + button_width // 2 - len('Save') * button_width // 30,
                y * 14 + button_height // 2 - 11)

            self.click = False

            sliderMusic.listen(self.events())
            sliderMusic.draw()
            outputMusic.setText(sliderMusic.getValue())
            outputMusic.draw()

            sliderSounds.listen(self.events())
            sliderSounds.draw()
            outputSounds.setText(sliderSounds.getValue())
            outputSounds.draw()

            self.events()
            pg.display.update()
            self.clock.tick(FPS)
示例#4
0
class Settings():
    def __init__(self, sounds):
        self.frame_h = int(str_dict.get("h"))
        self.frame_w = int(str_dict.get("w"))
        self.sc = pygame.display.set_mode((self.frame_w, self.frame_h))

        self.mus_curr_vol = 0
        self.snd_curr_vol = 0
        self.sounds = sounds
        self.diff = 'medium'
        # Инициализация слайдеров, координаты наверное можно лучше сделать
        self.sound_vol_slider = Slider(self.sc,
                                       self.frame_w * 2 // 5,
                                       self.frame_h * 1 // 10,
                                       100,
                                       20,
                                       colour=(100, 100, 100),
                                       handleColour=(40, 40, 40))
        self.music_vol_slider = Slider(self.sc,
                                       self.frame_w * 2 // 5,
                                       self.frame_h * 2 // 10,
                                       100,
                                       20,
                                       colour=(100, 100, 100),
                                       handleColour=(40, 40, 40))
        update_settings()
        self.sound_vol_slider.setValue(
            int(float(settings_dict.get('sound_volume')) * 100))
        self.music_vol_slider.setValue(
            int(float(settings_dict.get('music_volume')) * 100))

        self.BACKGROUND_offset = 0
        self.BACKGROUND_speed = 3
        self.FPS = int(str_dict.get("FPS"))
        self.clock = pygame.time.Clock()

    # Запуск
    def run(self):
        global event
        while True:
            events = pygame.event.get()
            # Обновление слайдеров
            self.music_vol_slider.listen(events)
            self.sound_vol_slider.listen(events)
            self.clock.tick(self.FPS)
            for event in events:
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    rect = pygame.Rect(
                        0,
                        self.sc.get_height() - int(str_dict.get('button_y')),
                        int(str_dict.get('button_x')),
                        int(str_dict.get('button_y')))
                    # Взаимодействие с кнопками сложности
                    if self.easy_b_rect.collidepoint(pos):
                        self.diff = 'easy'
                    elif self.medium_b_rect.collidepoint(pos):
                        self.diff = 'medium'
                    elif self.hard_b_rect.collidepoint(pos):
                        self.diff = 'hard'
                    # Выход из настроек. Сохранение настроек.
                    if rect.collidepoint(pos):
                        with open('Res/CSV/settings.csv',
                                  encoding="utf8") as csvfile:
                            change, write = dict(), list()
                            reader = csv.reader(csvfile,
                                                delimiter=',',
                                                quotechar='"')
                            for row in reader:
                                change[row[0]] = row[1]
                            # В change записываются изменённые настройки
                            change[
                                'music_volume'] = self.music_vol_slider.getValue(
                                ) / 100
                            change[
                                'sound_volume'] = self.sound_vol_slider.getValue(
                                ) / 100
                            change['difficulty'] = self.diff
                            write = list(
                                map(lambda x: [x, change[x]], change.keys()))
                            writer = csv.writer(open('Res/CSV/settings.csv',
                                                     'w',
                                                     encoding="utf8",
                                                     newline=''),
                                                delimiter=',',
                                                quoting=csv.QUOTE_ALL)
                            writer.writerows(write)
                        return
            self.redraw_window()

    # Перерисовка окна
    def redraw_window(self):
        # Текст около слайдеров
        sound_text = MAIN_FONT.render("Sound:", True, (170, 170, 170))
        music_text = MAIN_FONT.render("Music:", True, (170, 170, 170))

        # Движение фона
        self.sc.blit(BACKGROUND,
                     (0, self.BACKGROUND_offset - BACKGROUND.get_height()))
        self.sc.blit(BACKGROUND, (0, self.BACKGROUND_offset))
        self.BACKGROUND_offset += self.BACKGROUND_speed
        if self.BACKGROUND_offset > BACKGROUND.get_height():
            self.BACKGROUND_offset = 0
        self.sc.blit(BACK_BUTTON,
                     (0, self.sc.get_height() - int(str_dict.get('button_y'))))
        # Кнопки сложности
        self.easy_b_rect = self.sc.blit(easy_b, (40, 180))
        self.medium_b_rect = self.sc.blit(medium_b, (150, 180))
        self.hard_b_rect = self.sc.blit(hard_b, (260, 180))
        # Текст около слайдеров
        self.sc.blit(sound_text,
                     (self.frame_w * 1 // 10 - 10, self.frame_h * 1 // 10 - 5))
        self.sc.blit(music_text,
                     (self.frame_w * 1 // 10 - 1, self.frame_h * 2 // 10 - 5))
        self.sc.blit(settings_txt,
                     ((self.frame_w - settings_txt.get_width()) // 2,
                      settings_txt.get_height()))

        self.music_vol_slider.draw()
        self.sound_vol_slider.draw()
        # Изменение громкости если значение было изменено
        if self.mus_curr_vol != self.music_vol_slider.getValue():
            self.change_volume(music=True,
                               volume=self.music_vol_slider.getValue())
            self.mus_curr_vol = self.music_vol_slider.getValue()
        if self.snd_curr_vol != self.sound_vol_slider.getValue():
            self.change_volume(music=False,
                               volume=self.sound_vol_slider.getValue())
            self.snd_curr_vol = self.sound_vol_slider.getValue()
        pygame.display.update()

    # Изменение громкости, music - отвечает за тип звуков (True - изменение громкости музыки, False - остальных звуков)
    def change_volume(self, music=False, volume=99):
        volume /= 100
        for i in self.sounds.keys():
            if not (music ^ ('music' in i)):
                for j in self.sounds[i]:
                    pygame.mixer.Channel(j).set_volume(volume)
示例#5
0
def settings(mode='STANDARD'):
    pygame.init()

    json_file = open(os.getcwd() + r"\components\constants.json", "r")
    json_content = json.load(json_file)
    round_int = json_content["round_int"]
    json_file.close()

    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GREY = (100, 100, 100)
    BROWN = (138, 79, 28)
    font = pygame.font.SysFont("DejaVu Sans", 30)
    # RED = (255, 0, 0), GREEN = (0, 255, 0), BLUE = (0, 0, 255)

    screen = pygame.display.set_mode((720, 480))
    screen.fill(BROWN)

    clock = pygame.time.Clock()

    pygame.display.update()

    title_label = font.render(mode, True, BLACK)

    Player1_label = font.render("Player 1:", True, BLACK)
    Player2_label = font.render("AI Difficuly:", True, BLACK)

    Player1 = InputBox(345, 200, 120, 32, WHITE, GREY)
    bot_diff = Slider(screen,
                      350,
                      260,
                      120,
                      15,
                      min=1,
                      max=20,
                      step=1,
                      initial=6)

    Accept_Button = Button(x=300,
                           y=300,
                           w=100,
                           h=50,
                           color_b=BLACK,
                           color_in=WHITE,
                           color_t=WHITE,
                           command=lambda: [
                               main(player1=Player1.export(),
                                    player2='Computer',
                                    mode=mode,
                                    bot_bool=True,
                                    bot_difficulty=bot_diff.getValue())
                           ],
                           text='Start Game')

    while True:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

            Player1.checkActivation(event)
            bot_diff.listen(event)

            Accept_Button.processEvent(event)

            screen.fill(BROWN)
            screen.blit(Player1_label, (150, 200))
            screen.blit(Player2_label, (150, 250))
            screen.blit(title_label, (pygame.display.get_window_size()[0] / 2 -
                                      title_label.get_rect().w / 2, 30))
            Player1.draw(screen)
            bot_diff.draw()

            Accept_Button.draw(screen)

            pygame.display.flip()
示例#6
0
key_block = False
while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    frame_start_time = time()
    screen.fill(0)
    mouse_press = pygame.mouse.get_pressed()
    mouse_x, mouse_y = pygame.mouse.get_pos()

    # region slider handling
    # depth
    draw_ui(depth_slider, 'Depth', events)
    if depth_slider.getValue() != depth:
        depth = depth_slider.getValue()
        tree = new_tree()

    # angle
    draw_ui(angle_slider, 'Max Angle', events)
    if angle_slider.getValue() != max_angle:
        max_angle = angle_slider.getValue()
        tree = new_tree()

    # branches
    draw_ui(branches_slider, 'Max Branches', events)
    if branches_slider.getValue() != max_branches:
        max_branches = branches_slider.getValue()
        tree = new_tree()
示例#7
0
    pygame.gfxdraw.aacircle(screen, arrow_tup[2][0], arrow_tup[2][1], 15,
                            (0, 255, 255, 250))
    #-------------------------------------------------------------------
    #                 Keyboard and Mouse Interactions
    #-------------------------------------------------------------------
    events = pygame.event.get()
    keys = pygame.key.get_pressed()
    c1, c2, c3 = pygame.mouse.get_pressed()
    mx, my = pygame.mouse.get_pos()
    if c3:
        theta = -np.arctan2(mx - origin[0], my - origin[1]) + np.pi
        omega = 0
    if c2:
        origin = [mx, my]
        omega = 0
    if keys[pygame.K_q]:
        done = True
    slider.listen(events)
    slider.draw()
    l = slider.getValue(
    ) + 0.001  # a value of zero will result in a divide by zero error
    output.setText("{:.2f}m".format(slider.getValue()))
    output.draw()
    pygame.display.flip()
    if keys[pygame.K_s]:
        pygame.image.save(
            screen,
            datetime.now().strftime("CapturedImages/%m%d%Y_%H%M%S.png"))
    clock.tick(framerate)
pygame.display.quit()
示例#8
0
    def main(self):

        # Buttons for cards in home screen
        blue = Button(black, 145, 295, 110, 160)
        gray = Button(black, 295, 295, 110, 160)
        green = Button(black, 445, 295, 110, 160)

        # Custom Bet Input
        slider = Slider(self.win, 250, 250, 200, 40, min=1, max=500, step=1, handleRadius=25)
        outputText = TextBox(self.win, 315, 325, 70, 50, fontSize=30)

        # Buttons for Bet Selection
        minButton = Button(white, 190, 400, 100, 50, 'MIN')
        maxButton = Button(white, 410, 400, 100, 50, 'MAX')
        customButton = Button(white, 300, 400, 100, 50, "CUSTOM")

        # Buttons for Game Selection
        hitButton = Button(white, 600, 150, 90, 50, 'HIT')
        standButton = Button(white, 600, 250, 90, 50, 'STAND')
        splitButton = Button(white, 600, 350, 90, 50, 'SPLIT')
        doubleButton = Button(white, 600, 450, 90, 50, 'DOUBLE')

        back = ''
        state = 0

        # Game Class
        blackjack = Blackjack()
        user = blackjack.user
        dealer = blackjack.dealer

        run = True
        while run:
            events = pygame.event.get()
            for event in events:
                pos = pygame.mouse.get_pos()
                if event.type == pygame.QUIT:
                    run = False

                self.checkHover(blue, gray, green, minButton, maxButton, customButton, hitButton, standButton, splitButton, doubleButton, pos)

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if state == 0:
                        if blue.isOver(pos):
                            back = pygame.transform.scale(blueCard, (80, 110))
                        elif gray.isOver(pos):
                            back = pygame.transform.scale(grayCard, (80, 110))
                        elif green.isOver(pos):
                            back = pygame.transform.scale(greenCard, (80, 110))
                        else:
                            break
                        state = 1
                        self.fade()
                        blackjack.deckOfCards.shuffle()
                    elif state == 1:
                        bet = 0
                        if minButton.isOver(pos):
                            bet = 1
                        elif maxButton.isOver(pos):
                            bet = 500
                        elif customButton.isOver(pos):
                            bet = slider.getValue()
                        else:
                            break
                        state = 2
                        blackjack.place_bet(bet)
                        blackjack.deal_start_cards()
                        self.display_first_cards(user, dealer, back, blackjack)
                    elif state == 2:
                        if hitButton.isOver(pos):
                            blackjack.hit()
                        elif standButton.isOver(pos):
                            blackjack.stand()
                        elif doubleButton.isOver(pos):
                            blackjack.double()
                        elif splitButton.isOver(pos):
                            pass
                        else:
                            break

            if state == 0:
                self.display_homescreen(blue, gray, green)
            elif state == 1:
                slider.listen(events)
                blackjack.set_status('user')
                self.display_betting(user.balance, slider, outputText, minButton, maxButton, customButton, back)
            elif state == 2:
                self.display_game(blackjack, user, dealer, back, hitButton, standButton, splitButton, doubleButton)
                self.display_status(blackjack)

            stat = blackjack.get_status()
            if stat == 'user':
                blackjack.check_blackjack()
            elif stat == 'dealer':
                self.display_status(blackjack)
                self.dealer_turn(blackjack)
            elif stat == 'reset' or stat == 'over' or stat == 'dealerbust' or stat == 'won' or stat == 'lost':
                state = 1
                self.display_status(blackjack)
                pygame.display.update()
                blackjack.reset_game()
                pygame.time.delay(2500)

            pygame.display.update()
示例#9
0
文件: main.py 项目: fangyman/PyJaC
    events = pygame.event.get()
    moving()
    pygame.draw.rect(
        root, (91, 100, 103),
        pygame.Rect(screen_size.get_width() - 100, 0, 100,
                    screen_size.get_height()))
    textbox.draw()
    xslider.listen(events)
    xslider.draw()
    xtextbox.setText(f"X-speed: {xslider.getValue()}")
    xtextbox.draw()
    '''
    Remembering the momentum in the x direction
    '''
    if CONSTANTS['x_move'] > 0:
        CONSTANTS['x_move'] = xslider.getValue()
        if xslider.getValue() != 0:
            last_x = CONSTANTS['x_move']
    elif CONSTANTS['x_move'] == 0 and xslider.getValue() > 0:
        if last_x > 0:
            CONSTANTS['x_move'] = xslider.getValue()
        else:
            CONSTANTS['x_move'] = -xslider.getValue()
    else:
        CONSTANTS['x_move'] = -xslider.getValue()
        if xslider.getValue() != 0:
            last_x = CONSTANTS['x_move']

    yslider.listen(events)
    yslider.draw()
    ytextbox.setText(f"Y-speed: {yslider.getValue()}")