Exemplo n.º 1
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)
Exemplo n.º 2
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)
Exemplo n.º 3
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)
Exemplo n.º 4
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()
Exemplo n.º 5
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()
Exemplo n.º 6
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()
Exemplo n.º 7
0
                            CONSTANTS['y'] = randint(
                                0,
                                screen_size.get_height() - image.get_height())
                            pygame.display.update()
                        textbox.setText("Image Loaded")
                    else:
                        textbox.setText("Wrong file type")

    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()