Ejemplo n.º 1
0
class EnemyQuitGame(Dialog):
    def __init__(self, master: Window):
        Dialog.__init__(self,
                        master,
                        bg_color=BLUE,
                        outline=2,
                        outline_color=WHITE)
        self.master = master
        self.bg = RectangleShape(self.width, self.height, (0, 0, 0, 170))
        self.text = Text(font=RESOURCES.font("heavy", 50))
        self.button_quit = Button(self,
                                  "Return to menu",
                                  theme=["section"],
                                  font=RESOURCES.font("heavy", 40),
                                  y_add_size=-25,
                                  callback=self.stop)
        self.objects.set_priority(self.bg, 0)
        self.master = master

    def on_quit(self) -> None:
        self.master.stop()

    def on_start_loop(self) -> None:
        self.button_quit.focus_set()

    def place_objects(self) -> None:
        self.text.center = self.frame.center
        self.button_quit.move(centerx=self.frame.centerx,
                              bottom=self.frame.bottom - 10)
Ejemplo n.º 2
0
class EnemyQuitGame(Window):
    def __init__(self, master):
        Window.__init__(self, master=master, bg_music=master.bg_music)
        self.bg = RectangleShape(self.width, self.height, (0, 0, 0, 170))
        self.frame = RectangleShape(0.5 * self.width,
                                    0.5 * self.height,
                                    GREEN_DARK,
                                    outline=2)
        self.text_finish = Text("The enemy has left\nthe game",
                                font=(None, 70))
        params_for_all_buttons = {
            "font": (None, 40),
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "highlight_color": YELLOW
        }
        self.button_return_to_menu = Button(self,
                                            "Return to menu",
                                            callback=self.stop,
                                            **params_for_all_buttons)
        self.bind_key(pygame.K_ESCAPE, lambda event: self.stop())

    def place_objects(self):
        self.frame.center = self.center
        self.text_finish.center = self.frame.center
        self.button_return_to_menu.move(bottom=self.frame.bottom - 20,
                                        centerx=self.frame.centerx)
Ejemplo n.º 3
0
class PlayerClient(Dialog):

    def __init__(self, master, **kwargs):
        Dialog.__init__(self, master=master, bg_color=GREEN_DARK, **kwargs)
        params_for_all_buttons = {
            "font": ("calibri", 30),
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "highlight_color": YELLOW,
            "outline": 3
        }
        self.start_game = NavySetup(2)
        self.text_title = Text("Connect to Player 1", ("calibri", 50))
        self.ip = Entry(self, width=15, font=("calibri", 40), bg=GREEN, highlight_color=YELLOW, outline=2)
        self.text_ip_address = Text("IP address", ("calibri", 40), YELLOW)
        self.port = Entry(self, width=15, font=("calibri", 40), bg=GREEN, highlight_color=YELLOW, outline=2)
        self.text_port_of_connection = Text("Port", ("calibri", 40), YELLOW)
        self.text_connection = Text(font=("calibri", 25), color=YELLOW)
        self.text_connection.hide()
        self.button_connect = Button(self, "Connection", callback=self.connection, **params_for_all_buttons)
        self.button_cancel = Button(self, "Return to menu", callback=self.stop, **params_for_all_buttons)
        self.lets_play_countdown = CountDown(self, 3, "Connected.\nGame start in {seconds} seconds", font=("calibri", 35), color=YELLOW, justify="center")

    def on_dialog_quit(self):
        self.disable_text_input()
        self.stop_connection()

    def place_objects(self):
        self.frame.move(center=self.center)
        self.text_title.move(centerx=self.frame.centerx, top=self.frame.top + 50)
        self.lets_play_countdown.move(center=self.text_title.center)
        self.ip.move(centerx=self.frame.centerx + self.frame.w // 10, bottom=self.frame.centery - 10)
        self.text_ip_address.move(centery=self.ip.centery, right=self.ip.left - 10)
        self.port.move(left=self.ip.left, top=self.ip.bottom + 20)
        self.text_port_of_connection.move(centery=self.port.centery, right=self.port.left - 10)
        self.text_connection.move(centerx=self.frame.centerx, top=self.port.bottom + 5)
        self.button_connect.move(centerx=self.frame.centerx - (self.frame.width // 4), bottom=self.frame.bottom - 10)
        self.button_cancel.move(centerx=self.frame.centerx + (self.frame.width // 4), bottom=self.frame.bottom - 10)

    def connection(self):
        self.text_connection.show()
        self.text_connection.message = "Connection..."
        self.draw_and_refresh()
        if not self.connect_to_server(self.ip.get(), int(self.port.get()), 3):
            self.text_connection.message = "Connection failed. Try again."
        else:
            self.text_connection.hide()
            self.text_title.hide()
            self.button_connect.state = self.button_cancel.state = Button.DISABLED
            self.button_connect.focus_leave()
            self.lets_play_countdown.start(at_end=self.play)

    def play(self):
        self.start_game.mainloop()
        self.stop()
Ejemplo n.º 4
0
class PlayerClient(Dialog):

    def __init__(self, master, **kwargs):
        Dialog.__init__(self, master=master, bg_color=GREEN_DARK, **kwargs)
        self.start_game = master.start_game
        self.text_title = Text("Connect to Player 1", font=("calibri", 50))
        self.form = Form(self)
        self.form.add_entry("IP", Text("IP address", font=("calibri", 40), color=YELLOW), Entry(self, width=15, font=("calibri", 30), bg=GREEN, highlight_color=YELLOW, outline=2))
        self.form.add_entry("Port", Text("Port", font=("calibri", 40), color=YELLOW), Entry(self, width=15, font=("calibri", 30), bg=GREEN, highlight_color=YELLOW, outline=2))
        self.text_connection = Text(font=("calibri", 25), color=YELLOW)
        self.text_connection.hide()
        self.button_connect = Button(self, "Connection", theme="option", callback=self.connection)
        self.button_cancel = Button(self, "Return to menu", theme="option", callback=self.stop)
        self.lets_play_countdown = CountDown(self, 3, "Connected.\nGame start in {seconds} seconds", font=("calibri", 35), color=YELLOW, justify="center")

    def on_quit(self):
        self.stop_connection()

    def place_objects(self):
        self.frame.move(center=self.center)
        self.text_title.move(centerx=self.frame.centerx, top=self.frame.top + 50)
        self.lets_play_countdown.move(center=self.text_title.center)
        self.form.move(center=self.frame.center)
        self.text_connection.move(centerx=self.frame.centerx, top=self.form.bottom + 5)
        self.button_connect.move(centerx=self.frame.centerx - (self.frame.width // 4), bottom=self.frame.bottom - 10)
        self.button_cancel.move(centerx=self.frame.centerx + (self.frame.width // 4), bottom=self.frame.bottom - 10)

    def connection(self):
        self.text_connection.show()
        self.text_connection.message = "Connection..."
        self.draw_and_refresh()
        try:
            address = self.form.get("IP")
            port = int(self.form.get("Port"))
        except ValueError:
            self.text_connection.message = "The port of connection must be a number."
            return
        if not self.connect_to_server(address, port, 3):
            self.text_connection.message = "Connection failed. Try again."
        else:
            self.text_connection.hide()
            self.text_title.hide()
            self.button_connect.state = self.button_cancel.state = Button.DISABLED
            self.button_connect.focus_leave()
            self.lets_play_countdown.start(at_end=self.play)

    def play(self):
        self.start_game.start(2)
        self.stop()
Ejemplo n.º 5
0
class ConfirmPayement(Window):
    def __init__(self, master):
        Window.__init__(self, master=master, bg_music=master.bg_music)
        self.bg = RectangleShape(*self.size, (0, 0, 0, 170))
        self.frame = RectangleShape(0.50 * self.width,
                                    0.50 * self.height,
                                    GREEN,
                                    outline=3)
        self.text = Text("Are you sure you want\nto buy this car ?",
                         (RESOURCES.FONT["algerian"], 60),
                         justify=Text.T_CENTER)
        self.button_yes = Button(self,
                                 "Yes",
                                 self.text.font,
                                 bg=GREEN,
                                 hover_bg=GREEN_LIGHT,
                                 active_bg=GREEN_DARK,
                                 hover_sound=RESOURCES.SFX["select"],
                                 on_click_sound=RESOURCES.SFX["validate"],
                                 highlight_color=YELLOW,
                                 callback=self.buy)
        self.button_red_cross = ImageButton(
            self,
            img=RESOURCES.IMG["red_cross"],
            active_img=RESOURCES.IMG["red_cross_hover"],
            hover_sound=RESOURCES.SFX["select"],
            on_click_sound=RESOURCES.SFX["back"],
            callback=self.stop,
            highlight_color=YELLOW)
        self.buyed = False
        self.bind_key(pygame.K_ESCAPE,
                      lambda event: self.stop(sound=RESOURCES.SFX["back"]))
        self.bind_joystick(
            0, "B", lambda event: self.stop(sound=RESOURCES.SFX["back"]))

    def place_objects(self):
        self.text.center = self.frame.center = self.center
        self.button_red_cross.move(left=self.frame.left + 5,
                                   top=self.frame.top + 5)
        self.button_yes.move(bottom=self.frame.bottom - 10,
                             centerx=self.frame.centerx)

    def set_grid(self):
        self.button_red_cross.set_obj_on_side(on_bottom=self.button_yes)
        self.button_yes.set_obj_on_side(on_top=self.button_red_cross)

    def buy(self):
        self.buyed = True
        self.stop()
Ejemplo n.º 6
0
class PlayerServer(Dialog):

    def __init__(self, master, **kwargs):
        Dialog.__init__(self, master=master, bg_color=GREEN_DARK, **kwargs)
        params_for_all_buttons = {
            "font": ("calibri", 30),
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "outline": 3,
            "highlight_color": YELLOW
        }
        self.start_game = master.start_game
        self.text_title = Text("Waiting for Player 2", ("calibri", 50))
        self.text_ip_address = Text(font=("calibri", 40))
        self.text_port_of_connection = Text(font=("calibri", 40))
        self.button_cancel = Button(self, "Return to menu", callback=self.stop, **params_for_all_buttons)
        self.lets_play_countdown = CountDown(self, 3, "Player 2 connected.\nGame start in {seconds} seconds", font=("calibri", 35), color=YELLOW, justify="center")

    def on_dialog_start_loop(self):
        try:
            ip, port = self.create_server(12800, 1)
            self.text_ip_address.message = f"IP address: {ip}"
            self.text_port_of_connection.message = f"Port: {port}"
        except OSError:
            self.stop()

    def on_dialog_quit(self):
        self.stop_connection()

    def place_objects(self):
        self.frame.move(center=self.center)
        self.text_title.move(centerx=self.frame.centerx, top=self.frame.top + 50)
        self.lets_play_countdown.move(center=self.text_title.center)
        self.text_ip_address.move(centerx=self.centerx, bottom=self.frame.centery - 10)
        self.text_port_of_connection.move(centerx=self.text_ip_address.centerx, top=self.text_ip_address.bottom + 20)
        self.button_cancel.move(centerx=self.frame.centerx, bottom=self.frame.bottom - 10)

    def update(self) -> None:
        if self.get_server_clients_count() > 1 and not self.lets_play_countdown.started():
            self.set_server_listen(0)
            self.text_title.hide()
            self.button_cancel.state = Button.DISABLED
            self.lets_play_countdown.start(at_end=self.play)

    def play(self):
        self.start_game.mainloop()
        self.stop()
Ejemplo n.º 7
0
class NavyWindow(Window):
    def __init__(self):
        Window.__init__(self, size=(1280, 720), flags=pygame.DOUBLEBUF, bg_music=RESOURCES.MUSIC["menu"])
        self.set_icon(RESOURCES.IMG["icon"])
        self.set_title(f"Navy - v{__version__}")
        self.set_fps(60)
        self.disable_key_joy_focus_for_all_window()

        self.bg = Image(RESOURCES.IMG["menu_bg"], self.size)
        self.logo = Image(RESOURCES.IMG["logo"])

        params_for_all_buttons = {
            "font": (None, 100),
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "outline": 3,
            "highlight_color": YELLOW,
        }

        params_for_dialogs = {
            "outline": 5,
            "hide_all_without": [self.bg, self.logo]
        }

        self.start_game = NavySetup(1)
        self.multiplayer_server = PlayerServer(self, **params_for_dialogs)
        self.multiplayer_client = PlayerClient(self, **params_for_dialogs)
        self.dialog_credits = Credits(self, **params_for_dialogs)
        self.dialog_options = Options(self, **params_for_dialogs)

        self.menu_buttons = ButtonListVertical(offset=30)
        self.menu_buttons.add(
            Button(self, "Play against AI", **params_for_all_buttons, callback=self.start_game.mainloop),
            Button(self, "Play as P1", **params_for_all_buttons, callback=self.multiplayer_server.mainloop),
            Button(self, "Play as P2", **params_for_all_buttons, callback=self.multiplayer_client.mainloop),
            Button(self, "Quit", **params_for_all_buttons, callback=self.stop)
        )

        self.button_credits = Button(self, "Credits", callback=self.dialog_credits.mainloop, **params_for_all_buttons)
        self.button_settings = Button.withImageOnly(self, Image(RESOURCES.IMG["settings"], size=self.button_credits.height - 20), callback=self.dialog_options.mainloop, **params_for_all_buttons)

    def place_objects(self):
        self.bg.center = self.center
        self.logo.centerx = self.centerx
        self.menu_buttons.move(centerx=self.centerx, bottom=self.bottom - 20)
        self.button_settings.move(left=10, bottom=self.bottom - 10)
        self.button_credits.move(right=self.right - 10, bottom=self.bottom - 10)
Ejemplo n.º 8
0
class Options(Dialog):

    def __init__(self, master: Window, **kwargs):
        Dialog.__init__(self, master=master, bg_color=GREEN_DARK, **kwargs)
        self.text_title = Text("Options", ("calibri", 50))
        params_for_all_scales = {
            "width": 0.45 * self.frame.w,
            "height": 30,
            "color": TRANSPARENT,
            "scale_color": GREEN,
            "from_": 0,
            "to": 100,
            "highlight_color": YELLOW,
            "outline": 3
        }
        params_for_all_buttons = {
            "font": ("calibri", 30),
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "highlight_color": params_for_all_scales["highlight_color"],
            "outline": params_for_all_scales["outline"]
        }
        self.scale_music = Scale(
            self, **params_for_all_scales,
            default=Window.music_volume() * 100,
            callback=lambda value, percent: Window.set_music_volume(percent)
        )
        self.scale_music.show_label("Music: ", Scale.S_LEFT, font=params_for_all_buttons["font"])
        self.scale_music.show_value(Scale.S_RIGHT, font=params_for_all_buttons["font"])
        self.scale_sound = Scale(
            self, **params_for_all_scales,
            default=Window.sound_volume() * 100,
            callback=lambda value, percent: Window.set_sound_volume(percent)
        )
        self.scale_sound.show_label("SFX: ", Scale.S_LEFT, font=params_for_all_buttons["font"])
        self.scale_sound.show_value(Scale.S_RIGHT, font=params_for_all_buttons["font"])
        self.button_cancel = Button(self, "Return to menu", callback=self.stop, **params_for_all_buttons)

    def place_objects(self):
        self.text_title.move(centerx=self.frame.centerx, top=self.frame.top + 50)
        self.scale_music.move(centerx=self.frame.centerx, bottom=self.frame.centery - 20)
        self.scale_sound.move(centerx=self.frame.centerx, top=self.frame.centery + 20)
        self.button_cancel.move(centerx=self.frame.centerx, bottom=self.frame.bottom - 10)
Ejemplo n.º 9
0
class FinishWindow(Window):
    def __init__(self, master):
        Window.__init__(self, master=master)
        self.master = master
        self.bg = RectangleShape(self.width, self.height, (0, 0, 0, 170))
        self.frame = RectangleShape(0.5 * self.width, 0.5 * self.height, GREEN_DARK, outline=2)
        self.victory = None
        self.text_finish = Text(font=(None, 70))
        self.button_restart = Button(self, "Restart", font=(None, 40), callback=self.restart)
        self.button_return_to_menu = Button(self, "Return to menu", font=(None, 40), callback=self.stop)
        self.ask_restart = False
        self.bind_key(pygame.K_ESCAPE, lambda event: self.stop())

    def start(self, victory: bool) -> None:
        self.victory = victory
        if victory is not None:
            self.text_finish.message = "{winner} won".format(winner="You" if victory else "Enemy")
        else:
            self.text_finish.message = "The enemy has left\nthe game"
        self.ask_restart = False
        self.mainloop()

    def update(self):
        if self.ask_restart:
            if self.master.client_socket.recv("restart"):
                self.master.restart = True
                self.stop()
            elif self.master.client_socket.recv("quit"):
                self.text_finish.message = "The enemy has left\nthe game"

    def place_objects(self):
        self.frame.center = self.center
        self.text_finish.center = self.frame.center
        if self.victory is not None:
            self.button_restart.move(bottom=self.frame.bottom - 20, centerx=self.frame.centerx - (self.frame.w // 4))
            self.button_return_to_menu.move(bottom=self.frame.bottom - 20, centerx=self.frame.centerx + (self.frame.w // 4))
        else:
            self.button_restart.hide()
            self.button_return_to_menu.move(bottom=self.frame.bottom - 20, centerx=self.frame.centerx)

    def restart(self):
        if self.master.client_socket.connected():
            self.ask_restart = True
            self.master.client_socket.send("restart")
            self.text_finish.message = "Waiting for\nenemy response"
            self.button_restart.hide()
            self.button_return_to_menu.move(bottom=self.frame.bottom - 20, centerx=self.frame.centerx)
        else:
            self.master.restart = True
            self.stop()
Ejemplo n.º 10
0
class GameMenu(Window):
    def __init__(self, master: Window):
        Window.__init__(self)
        self.bg = master.bg
        self.title = Text("Game", font=(FONT["death_star"], 220), color=YELLOW)
        params_for_all_buttons = {
            "bg": BLUE,
            "hover_bg": BLUE_LIGHT,
            "active_bg": BLUE_DARK,
            "active_fg": YELLOW,
            "hover_sound": AUDIO["clank"],
            "on_click_sound": AUDIO["laser"],
            "outline": 5,
        }
        params_for_section_button = {
            "font": (FONT["death_star"], 200)
        }
        self.button_battle = Button(self, "Battle", **params_for_all_buttons, **params_for_section_button, command=self.launch_battle)
        self.button_edit = Button(self, "Editor", **params_for_all_buttons, **params_for_section_button, command=self.launch_editor)
        self.button_menu = Button(self, "Menu", **params_for_all_buttons, font=(FONT["death_star"], 80), command=self.stop)

    def place_objects(self):
        self.title.move(centerx=self.centerx, top=10)
        self.button_battle.move(centerx=self.centerx - (self.w // 4), centery=self.centery)
        self.button_edit.move(centerx=self.centerx + (self.w // 4), centery=self.centery)
        self.button_menu.move(centerx=self.centerx, bottom=self.bottom - 100)

    def launch_editor(self):
        Editor(self).mainloop()

    def launch_battle(self):
        Battle(self).mainloop()
Ejemplo n.º 11
0
class LocalPlayingSection(Section):
    def __init__(self, master, gameplay: FourInARowGameplay):
        Section.__init__(self, master, "Local Multiplaying", gameplay)
        self.form = Form(self)
        self.form.add_entry("P1", Text("P1 Name:", theme="form"), Entry(self))
        self.form.add_entry("P2", Text("P2 Name:", theme="form"), Entry(self))
        self.button_play = Button(self,
                                  "Play",
                                  theme=["option", "section"],
                                  callback=self.play)

    def on_start_loop(self) -> None:
        super().on_start_loop()
        self.button_play.focus_set()

    def place_objects(self) -> None:
        Section.place_objects(self)
        self.form.move(left=self.frame.left + 10, top=self.title.bottom + 50)
        self.button_play.move(centerx=self.frame.centerx,
                              bottom=self.frame.bottom - 10)

    def set_grid(self) -> None:
        self.button_back.set_obj_on_side(on_bottom=self.form[0],
                                         on_right=self.form[0])
        self.form.set_obj_on_side(on_top=self.button_back,
                                  on_left=self.button_back,
                                  on_bottom=self.button_play)
        self.button_play.set_obj_on_side(on_top=self.form[-1])

    def play(self) -> None:
        player_1_name = self.form.get("P1") or None
        player_2_name = self.form.get("P2") or None
        self.gameplay.start(LOCAL_PLAYER,
                            player_name=player_1_name,
                            enemy_name=player_2_name)
        self.stop()
Ejemplo n.º 12
0
class Options(Window):
    def __init__(self, master: Window):
        Window.__init__(self, master=master, bg_music=master.bg_music)
        self.frame = RectangleShape(0.60 * self.width,
                                    0.60 * self.height,
                                    GREEN,
                                    outline=3)
        self.title = Text("Options", font=(RESOURCES.FONT["algerian"], 70))

        self.options_font = (RESOURCES.FONT["algerian"], 40)
        self.case_font = (RESOURCES.FONT["algerian"], 30)
        self.control_font = ("calibri", 20)
        params_for_all_scales = {
            "width": 0.45 * self.frame.w,
            "color": TRANSPARENT,
            "scale_color": GREEN_DARK,
            "from_": 0,
            "to": 100,
            "outline": 3,
        }
        params_for_all_buttons = {
            "highlight_color": YELLOW,
            "hover_sound": RESOURCES.SFX["select"],
            "disabled_sound": RESOURCES.SFX["block"]
        }
        params_for_option_buttons = {
            "on_click_sound": RESOURCES.SFX["validate"]
        }
        params_for_buttons = {
            "bg": GRAY_DARK,
            "fg": WHITE,
            "hover_bg": GRAY,
            "active_bg": BLACK
        }
        params_for_reset_button = {
            "bg": RED,
            "fg": WHITE,
            "hover_bg": RED_LIGHT,
            "active_bg": RED_DARK,
        }

        self.button_back = ImageButton(self,
                                       img=RESOURCES.IMG["blue_arrow"],
                                       on_click_sound=RESOURCES.SFX["back"],
                                       callback=self.stop,
                                       **params_for_all_buttons)
        self.button_change_page = Button(self,
                                         ">>",
                                         font=self.case_font,
                                         callback=self.change_page,
                                         **params_for_all_buttons,
                                         **params_for_option_buttons,
                                         **params_for_buttons)
        self.nb_pages = 2
        self.page = 1

        ## PAGE 1 ##
        valid_img = Image(RESOURCES.IMG["green_valid"])
        self.text_music = Text("Music:", self.options_font)
        self.cb_music = CheckBox(self,
                                 30,
                                 30,
                                 TRANSPARENT,
                                 image=valid_img,
                                 value=self.get_music_state(),
                                 callback=self.set_music_state,
                                 **params_for_all_buttons,
                                 **params_for_option_buttons)
        self.scale_music = Scale(
            self,
            **params_for_all_scales,
            **params_for_all_buttons,
            height=self.cb_music.height,
            default=Window.music_volume() * 100,
            callback=lambda value, percent: Window.set_music_volume(percent))
        self.text_sound = Text("SFX:", self.options_font)
        self.cb_sound = CheckBox(self,
                                 30,
                                 30,
                                 TRANSPARENT,
                                 image=valid_img,
                                 value=self.get_sound_state(),
                                 callback=self.set_sound_state,
                                 **params_for_all_buttons,
                                 **params_for_option_buttons)
        self.scale_sound = Scale(
            self,
            **params_for_all_scales,
            **params_for_all_buttons,
            height=self.cb_sound.height,
            default=Window.sound_volume() * 100,
            callback=lambda value, percent: Window.set_sound_volume(percent))
        self.text_fps = Text("FPS:", self.options_font)
        self.cb_show_fps = CheckBox(self,
                                    30,
                                    30,
                                    TRANSPARENT,
                                    image=valid_img,
                                    value=Window.fps_is_shown(),
                                    callback=self.show_fps,
                                    **params_for_all_buttons,
                                    **params_for_option_buttons)
        self.button_reset = Button(self,
                                   "Reset Save",
                                   font=(RESOURCES.FONT["algerian"], 30),
                                   callback=SAVE.reset,
                                   state=Button.DISABLED,
                                   **params_for_all_buttons,
                                   **params_for_option_buttons,
                                   **params_for_reset_button)
        ## PAGE 2 ##
        self.text_acceleration = Text("Accélérer:", self.options_font)
        self.button_auto_acceleration = Button(
            self,
            font=self.case_font,
            callback=lambda: SAVE.update(auto_acceleration=not SAVE[
                "auto_acceleration"]),
            **params_for_all_buttons,
            **params_for_option_buttons,
            **params_for_buttons)
        self.button_acceleration = Button(
            self,
            font=self.control_font,
            callback=lambda: self.choose_key("speed_up"),
            **params_for_all_buttons,
            **params_for_option_buttons,
            **params_for_buttons)
        self.text_brake = Text("Freiner:", self.options_font)
        self.button_brake = Button(self,
                                   font=self.control_font,
                                   callback=lambda: self.choose_key("brake"),
                                   **params_for_all_buttons,
                                   **params_for_option_buttons,
                                   **params_for_buttons)
        self.text_move_up = Text("Aller en haut:", self.options_font)
        self.button_move_up = Button(self,
                                     font=self.control_font,
                                     callback=lambda: self.choose_key("up"),
                                     **params_for_all_buttons,
                                     **params_for_option_buttons,
                                     **params_for_buttons)
        self.text_move_down = Text("Aller en bas:", self.options_font)
        self.button_move_down = Button(
            self,
            font=self.control_font,
            callback=lambda: self.choose_key("down"),
            **params_for_all_buttons,
            **params_for_option_buttons,
            **params_for_buttons)

        self.bind_key(pygame.K_ESCAPE,
                      lambda event: self.stop(sound=RESOURCES.SFX["back"]))
        self.bind_joystick(
            0, "B", lambda event: self.stop(sound=RESOURCES.SFX["back"]))

    def on_quit(self):
        SAVE.dump()

    def change_page(self):
        self.page = (self.page % self.nb_pages) + 1

    def update(self):
        self.hide_all(without=[
            self.frame, self.title, self.button_back, self.button_change_page
        ])
        if self.page == 1:
            self.text_music.show()
            self.text_sound.show()
            for checkbox, scale in [(self.cb_music, self.scale_music),
                                    (self.cb_sound, self.scale_sound)]:
                checkbox.show()
                if checkbox.value is True:
                    scale.show()
                    checkbox.set_obj_on_side(on_right=scale)
                else:
                    checkbox.set_obj_on_side(on_right=self.button_change_page)
            self.text_fps.show()
            self.cb_show_fps.show()
            self.button_reset.show()
            self.button_back.set_obj_on_side(on_bottom=self.cb_music,
                                             on_right=self.cb_music)
            self.button_change_page.set_obj_on_side(on_top=self.cb_show_fps,
                                                    on_left=self.button_reset)
        elif self.page == 2:
            self.text_acceleration.show()
            self.button_auto_acceleration.text = "Automatique" if SAVE[
                "auto_acceleration"] else "Manuel"
            self.button_auto_acceleration.show()
            control_text_format = "Key: {key}\nJoystick: {joy}"
            if not SAVE["auto_acceleration"]:
                self.button_acceleration.text = control_text_format.format(
                    **SAVE["controls"]["speed_up"])
                self.button_acceleration.move(
                    left=self.button_auto_acceleration.right + 10,
                    centery=self.button_auto_acceleration.centery)
                self.button_acceleration.show()
                self.button_auto_acceleration.set_obj_on_side(
                    on_right=self.button_acceleration)
            else:
                self.button_auto_acceleration.set_obj_on_side(
                    on_right=self.button_back)
            fields = [
                (self.text_brake, self.button_brake, "brake"),
                (self.text_move_up, self.button_move_up, "up"),
                (self.text_move_down, self.button_move_down, "down"),
            ]
            for text, button, action in fields:
                text.show()
                button.text = control_text_format.format(
                    **SAVE["controls"][action])
                button.show()
            self.button_back.set_obj_on_side(
                on_bottom=self.button_auto_acceleration,
                on_right=self.button_auto_acceleration)
            self.button_change_page.set_obj_on_side(
                on_top=self.button_move_down, on_left=self.button_move_down)

    def place_objects(self):
        self.frame.move(center=self.center)
        self.title.move(top=self.frame.top + 10, centerx=self.frame.centerx)
        self.button_back.move(top=self.frame.top + 5, left=self.frame.left + 5)
        self.button_change_page.move(bottom=self.frame.bottom - 5,
                                     right=self.frame.right - 5)
        ## PAGE 1 ##
        self.text_music.move(left=self.frame.left + 10,
                             top=self.title.bottom + 10)
        self.text_sound.move(right=self.text_music.right,
                             top=self.text_music.bottom + 5)
        self.cb_music.move(left=self.text_music.right + 10,
                           centery=self.text_music.centery)
        self.cb_sound.move(left=self.text_music.right + 10,
                           centery=self.text_sound.centery)
        self.scale_music.move(centerx=self.frame.centerx,
                              centery=self.cb_music.centery)
        self.scale_music.show_value(Scale.S_RIGHT, font=self.case_font)
        self.scale_sound.move(centerx=self.frame.centerx,
                              centery=self.cb_sound.centery)
        self.scale_sound.show_value(Scale.S_RIGHT, font=self.case_font)
        self.text_fps.move(right=self.text_music.right,
                           top=self.text_sound.bottom + 50)
        self.cb_show_fps.move(left=self.text_fps.right + 10,
                              centery=self.text_fps.centery)
        self.button_reset.move(bottom=self.frame.bottom - 5,
                               left=self.frame.left + 5)
        ## PAGE 2 ##
        self.text_acceleration.move(left=self.frame.left + 10,
                                    top=self.title.bottom + 50)
        self.button_auto_acceleration.move(
            left=self.text_acceleration.right + 10,
            centery=self.text_acceleration.centery)
        self.text_brake.move(left=self.text_acceleration.left,
                             top=self.text_acceleration.bottom + 50)
        self.button_brake.move(left=self.text_brake.right + 10,
                               centery=self.text_brake.centery)
        self.text_move_up.move(left=self.text_acceleration.left,
                               top=self.text_brake.bottom + 50)
        self.button_move_up.move(left=self.text_move_up.right + 10,
                                 centery=self.text_move_up.centery)
        self.text_move_down.move(left=self.text_acceleration.left,
                                 top=self.text_move_up.bottom + 50)
        self.button_move_down.move(left=self.text_move_down.right + 10,
                                   centery=self.text_move_down.centery)

    def set_grid(self):
        ## PAGE 1 ##
        self.cb_music.set_obj_on_side(on_top=self.button_back,
                                      on_left=self.button_back,
                                      on_bottom=self.cb_sound)
        self.scale_music.set_obj_on_side(on_top=self.button_back,
                                         on_left=self.cb_music,
                                         on_bottom=self.scale_sound,
                                         on_right=self.button_change_page)
        self.cb_sound.set_obj_on_side(on_top=self.cb_music,
                                      on_left=self.button_back,
                                      on_bottom=self.cb_show_fps)
        self.scale_sound.set_obj_on_side(on_top=self.scale_music,
                                         on_left=self.cb_sound,
                                         on_bottom=self.cb_show_fps,
                                         on_right=self.button_change_page)
        self.cb_show_fps.set_obj_on_side(on_left=self.button_back,
                                         on_top=self.cb_sound,
                                         on_bottom=self.button_reset,
                                         on_right=self.button_change_page)
        self.button_reset.set_obj_on_side(on_left=self.button_back,
                                          on_top=self.cb_show_fps,
                                          on_right=self.button_change_page)
        ## PAGE 2 ##
        self.button_auto_acceleration.set_obj_on_side(
            on_top=self.button_back,
            on_left=self.button_back,
            on_bottom=self.button_brake)
        self.button_acceleration.set_obj_on_side(
            on_top=self.button_back,
            on_left=self.button_auto_acceleration,
            on_bottom=self.button_brake,
            on_right=self.button_change_page)
        self.button_brake.set_obj_on_side(on_top=self.button_auto_acceleration,
                                          on_left=self.button_back,
                                          on_bottom=self.button_move_up,
                                          on_right=self.button_change_page)
        self.button_move_up.set_obj_on_side(on_top=self.button_brake,
                                            on_left=self.button_back,
                                            on_bottom=self.button_move_down,
                                            on_right=self.button_change_page)
        self.button_move_down.set_obj_on_side(
            on_top=self.button_move_up,
            on_left=self.button_back,
            on_bottom=self.button_change_page,
            on_right=self.button_change_page)

    def choose_key(self, action: str):
        AssignmentPrompt(self, action).mainloop()
Ejemplo n.º 13
0
class LANPlayingP1(Section):
    def __init__(self, master, gameplay: FourInARowGameplay):
        Section.__init__(self, master, "Play as P1", gameplay)
        self.form = Form(self)
        self.form.add_entry("P1", Text("Your Name:", theme="form"),
                            Entry(self))
        self.button_start_server = Button(self, theme=["option", "section"])
        self.text_game_status = Text(font=RESOURCES.font("heavy", 20),
                                     shadow_x=1,
                                     shadow_y=1)
        self.text_server_ip = Text(font=RESOURCES.font("afterglow", 45),
                                   shadow_x=2,
                                   shadow_y=1)
        self.text_server_port = Text(font=RESOURCES.font("afterglow", 45),
                                     shadow_x=2,
                                     shadow_y=1)

    def place_objects(self) -> None:
        Section.place_objects(self)
        self.form.move(left=self.frame.left + 10, top=self.title.bottom + 50)
        self.text_game_status.move(centerx=self.frame.centerx,
                                   top=self.form.bottom + 10)
        self.button_start_server.move(centerx=self.frame.centerx,
                                      top=self.form.bottom + 50)
        self.text_server_ip.move(centerx=self.frame.centerx,
                                 top=self.button_start_server.bottom + 30)
        self.text_server_port.move(centerx=self.frame.centerx,
                                   top=self.text_server_ip.bottom + 10)

    def update(self) -> None:
        if not self.client_socket.connected():
            self.button_start_server.state = Button.NORMAL if self.form.get(
                "P1") else Button.DISABLED
            self.form.get_entry("P1").state = Entry.NORMAL
        else:
            self.button_start_server.state = Button.NORMAL
            self.form.get_entry("P1").state = Entry.DISABLED
            if self.get_server_clients_count() == 2:
                self.set_server_listen(0)
                self.gameplay.start(LAN_PLAYER,
                                    player=1,
                                    player_name=self.form.get("P1"))
                self.stop()

    def on_start_loop(self) -> None:
        super().on_start_loop()
        self.form.get_entry("P1").focus_set()
        self.form.get_entry("P1").start_edit()
        self.stop_server()

    def on_quit(self) -> None:
        super().on_quit()
        self.stop_connection()

    def set_grid(self) -> None:
        self.button_back.set_obj_on_side(on_bottom=self.form[0],
                                         on_right=self.form[0])
        self.form.set_obj_on_side(on_top=self.button_back,
                                  on_left=self.button_back,
                                  on_bottom=self.button_start_server)
        self.button_start_server.set_obj_on_side(on_top=self.form[-1],
                                                 on_left=self.button_back)

    def start_server(self) -> None:
        try:
            ip, port = self.create_server(12800, 1)
        except OSError:
            self.text_game_status.message = "Cannot create server"
        else:
            self.text_game_status.message = "Waiting for player 2 to connect"
            self.text_server_ip.message = "IP: {}".format(ip)
            self.text_server_port.message = "Port: {}".format(port)
            self.text_server_ip.show()
            self.text_server_port.show()
            self.button_start_server.text = "Stop server"
            self.button_start_server.callback = self.stop_server
        self.text_game_status.show()
        self.place_objects()

    def stop_server(self) -> None:
        self.stop_connection()
        self.text_game_status.hide()
        self.text_server_ip.hide()
        self.text_server_port.hide()
        self.button_start_server.text = "Start server"
        self.button_start_server.callback = self.start_server
Ejemplo n.º 14
0
class LANPlayingP2(Section):
    def __init__(self, master, gameplay: FourInARowGameplay):
        Section.__init__(self, master, "Play as P2", gameplay)
        self.form = Form(self)
        self.form.add_entry("name", Text("Your Name:", theme="form"),
                            Entry(self))
        self.form.add_entry("IP", Text("IP address:", theme="form"),
                            Entry(self, width=15))
        self.form.add_entry("port", Text("Port:", theme="form"),
                            Entry(self, width=15))
        self.button_connect = Button(self,
                                     "Connect to P1",
                                     theme=["option", "section"],
                                     callback=self.connection)
        self.text_game_status = Text(font=RESOURCES.font("heavy", 30),
                                     shadow_x=1,
                                     shadow_y=1)

    def place_objects(self) -> None:
        Section.place_objects(self)
        self.form.move(left=self.frame.left + 10, top=self.title.bottom + 50)
        self.text_game_status.move(centerx=self.frame.centerx,
                                   top=self.form.bottom + 10)
        self.button_connect.move(centerx=self.frame.centerx,
                                 bottom=self.frame.bottom - 10)

    def update(self) -> None:
        self.button_connect.state = Button.NORMAL if self.form.get(
            "name") else Button.DISABLED

    def on_start_loop(self) -> None:
        super().on_start_loop()
        self.form.get_entry("name").focus_set()
        self.form.get_entry("name").start_edit()
        self.text_game_status.hide()

    def on_quit(self) -> None:
        super().on_quit()
        self.stop_connection()

    def set_grid(self) -> None:
        self.button_back.set_obj_on_side(on_bottom=self.form[0],
                                         on_right=self.form[0])
        self.form.set_obj_on_side(on_top=self.button_back,
                                  on_left=self.button_back,
                                  on_bottom=self.button_connect)
        self.button_connect.set_obj_on_side(on_top=self.form[-1])

    def connection(self) -> None:
        self.text_game_status.show()
        self.text_game_status.message = "Connection..."
        self.draw_and_refresh()
        try:
            address = self.form.get("IP")
            port = int(self.form.get("port"))
        except ValueError:
            self.text_game_status.message = "The port of connection must be a number."
            return
        if not self.connect_to_server(address, port, 3):
            self.text_game_status.message = "Connection failed. Try again."
        else:
            self.gameplay.start(LAN_PLAYER,
                                player=2,
                                player_name=self.form.get("name"))
            self.stop()
Ejemplo n.º 15
0
class NavySetup(Window):
    def __init__(self):
        Window.__init__(self, bg_color=(0, 200, 255))
        self.gameplay = Gameplay()
        self.enemy_quit_window = EnemyQuitGame(self)
        self.transition = GameSetupTransition()
        self.count_down = CountDown(self,
                                    60,
                                    "Time left: {seconds}",
                                    font=(None, 70),
                                    color=WHITE)
        self.start_count_down = lambda: self.count_down.start(
            at_end=self.timeout) if self.client_socket.connected() else None
        self.button_back = ImageButton(self,
                                       RESOURCES.IMG["arrow_blue"],
                                       rotate=180,
                                       size=50,
                                       callback=self.stop)
        self.navy_grid = Grid(self, bg_color=(0, 157, 255))
        self.__boxes_dict = {(i, j): BoxSetup(self, size=BOX_SIZE, pos=(i, j))
                             for i in range(NB_LINES_BOXES)
                             for j in range(NB_COLUMNS_BOXES)}
        self.__boxes_list = list(self.__boxes_dict.values())
        self.navy_grid.place_multiple(self.__boxes_dict)
        self.ships_list = DrawableListVertical(offset=70, justify="left")
        for ship_name, ship_infos in SHIPS.items():
            ship_line = DrawableListHorizontal(offset=ship_infos["offset"])
            for _ in range(ship_infos["nb"]):
                ship_line.add(ShipSetup(self, ship_name, ship_infos["size"]))
            self.ships_list.add(ship_line)
        option_size = 50
        self.button_restart = Button(self,
                                     img=Image(RESOURCES.IMG["reload_blue"],
                                               size=option_size),
                                     callback=self.reinit_all_ships)
        self.button_random = Button(self,
                                    img=Image(RESOURCES.IMG["random"],
                                              size=option_size),
                                    callback=self.shuffle)
        self.button_play = Button(self,
                                  "Play",
                                  font=(None, 40),
                                  callback=self.play)

    @property
    def ships(self) -> Sequence[ShipSetup]:
        return self.ships_list.drawable

    @property
    def boxes(self) -> Sequence[BoxSetup]:
        return self.__boxes_list

    def start(self, player_id: int) -> None:
        self.gameplay.player_id = player_id
        self.mainloop(transition=self.transition)

    def on_start_loop(self) -> None:
        self.start_count_down()

    def on_quit(self) -> None:
        self.reinit_all_ships()

    def place_objects(self) -> None:
        self.button_back.move(x=20, y=20)
        self.count_down.move(top=20, right=self.right - 20)
        self.navy_grid.move(x=20, centery=self.centery)
        self.ships_list.move(left=self.navy_grid.right + 100,
                             top=self.navy_grid.top + 30)
        self.button_restart.move(left=self.navy_grid.right + 20,
                                 bottom=self.navy_grid.bottom)
        self.button_random.move(left=self.button_restart.right + 20,
                                bottom=self.navy_grid.bottom)
        self.button_play.move(right=self.right - 20, bottom=self.bottom - 20)
        for ship in self.ships:
            ship.default_center = ship.center

    def update(self):
        self.button_play.state = Button.NORMAL if all(
            ship.on_map for ship in self.ships) else Button.DISABLED
        if self.client_socket.recv("quit"):
            self.count_down.stop()
            self.enemy_quit_window.mainloop()
            self.stop()

    def create_setup(self) -> Sequence[dict[str, dict[str, Any]]]:
        setup = list()
        for ship in self.ships:
            setup.append({
                "name": ship.name,
                "orient": ship.orient,
                "boxes": [box.pos for box in ship.boxes_covered]
            })
        return setup

    def timeout(self):
        for ship in filter(lambda ship: not ship.on_map, self.ships):
            self.set_random_position_for_ship(ship)
        self.play()

    def play(self):
        if not all(ship.on_map for ship in self.ships):
            return
        if not self.client_socket.connected():
            ai_navy_setup = NavySetup()
            ai_navy_setup.shuffle()
            ai_setup = ai_navy_setup.create_setup()
        else:
            ai_setup = None
            self.count_down.stop()
            self.client_socket.send("ready")
            WaitEnemy(self).mainloop()
        self.gameplay.start(self.create_setup(), ai_setup=ai_setup)
        self.reinit_all_ships()
        if self.gameplay.restart:
            self.start_count_down()
        else:
            self.stop()

    def reinit_all_ships(self):
        for ship in self.ships:
            ship.center = ship.default_center
            ship.orient = ShipSetup.HORIZONTAL
            ship.clear()

    def get_box(self, line: int, column: float) -> BoxSetup:
        return self.__boxes_dict.get((line, column))

    def remove_boxes_highlight(self):
        for box in self.boxes:
            box.hover = False
            box.state = Button.NORMAL

    def get_valid_highlighted_boxes(self) -> Sequence[BoxSetup]:
        return list(
            filter(lambda box: box.hover and box.state == Button.NORMAL,
                   self.boxes))

    def highlight_boxes(self, ship: ShipSetup) -> None:
        boxes = list()
        for box in self.boxes:
            self.highlight_one_box(ship, box, len(boxes))
            if box.hover is True:
                boxes.append(box)
        if len(boxes) != ship.ship_size or any(not self.valid_box(ship, box)
                                               for box in boxes):
            for box in boxes:
                box.state = Button.DISABLED

    def highlight_one_box(self, ship: ShipSetup, box: BoxSetup,
                          nb_boxes_covered: int) -> None:
        box.hover = False
        box.state = Button.NORMAL
        if nb_boxes_covered == ship.ship_size:
            return
        if ship.orient == ShipSetup.HORIZONTAL:
            if (box.top <= ship.centery <= box.bottom) is False:
                return
            if ship.left > box.centerx or ship.right < box.centerx:
                return
        else:
            if (box.left <= ship.centerx <= box.right) is False:
                return
            if ship.top > box.centery or ship.bottom < box.centery:
                return
        box.hover = True

    def valid_box(self, ship: ShipSetup, box: BoxSetup) -> bool:
        line, column = box.pos
        offsets = [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0),
                   (-1, 1), (0, 1), (1, 1)]
        for u, v in offsets:
            box = self.get_box(line + u, column + v)
            if box is None:
                continue
            if box.ship is not None and box.ship != ship:
                return False
        return True

    def shuffle(self) -> None:
        self.reinit_all_ships()
        for ship in self.ships:
            self.set_random_position_for_ship(ship)

    def set_random_position_for_ship(self, ship: ShipSetup) -> None:
        ship.orient = random.choice([ShipSetup.HORIZONTAL, ShipSetup.VERTICAL])
        first_box = random.choice(self.get_available_boxes(ship))
        boxes = [first_box]
        for i in range(1, ship.ship_size):
            u = first_box.pos[
                0] + i if ship.orient == ShipSetup.VERTICAL else first_box.pos[
                    0]
            v = first_box.pos[
                1] + i if ship.orient == ShipSetup.HORIZONTAL else first_box.pos[
                    1]
            boxes.append(self.get_box(u, v))
        ship.place_ship_on_map(boxes)

    def get_available_boxes(self, ship: ShipSetup):
        available_boxes = list()
        for box in self.boxes:
            if not self.valid_box(ship, box):
                continue
            line, column = box.pos
            valid = True
            for i in range(1, ship.ship_size):
                u = line + i if ship.orient == ShipSetup.VERTICAL else line
                v = column + i if ship.orient == ShipSetup.HORIZONTAL else column
                b = self.get_box(u, v)
                if b is None or (not self.valid_box(ship, b)):
                    valid = False
                    break
            if valid:
                available_boxes.append(box)
        return available_boxes
Ejemplo n.º 16
0
class NavyWindow(MainWindow):
    def __init__(self):
        MainWindow.__init__(self, title=f"Navy - v{__version__}", size=(1280, 720), resources=RESOURCES, config=WINDOW_CONFIG_FILE)

        self.bg = Image(RESOURCES.IMG["menu_bg"], size=self.size)
        self.logo = Image(RESOURCES.IMG["logo"])

        Button.set_default_theme("default")
        Button.set_theme("default", {
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "highlight_color": YELLOW,
            "outline": 3,
        })
        Button.set_theme("title", {
            "font": (None, 100),
        })
        Button.set_theme("option", {
            "font": ("calibri", 30),
        })
        Scale.set_default_theme("default")
        Scale.set_theme("default", {
            "color": TRANSPARENT,
            "scale_color": GREEN,
            "highlight_color": YELLOW,
            "outline": 3
        })

        params_for_dialogs = {
            "outline": 5,
            "hide_all_without": [self.bg, self.logo]
        }

        self.start_game = NavySetup()
        self.multiplayer_server = PlayerServer(self, **params_for_dialogs)
        self.multiplayer_client = PlayerClient(self, **params_for_dialogs)
        self.dialog_credits = Credits(self, **params_for_dialogs)

        self.menu_buttons = ButtonListVertical(offset=30)
        self.menu_buttons.add(
            Button(self, "Play against AI", theme="title", callback=lambda: self.start_game.start(1)),
            Button(self, "Play as P1", theme="title", callback=self.multiplayer_server.mainloop),
            Button(self, "Play as P2", theme="title", callback=self.multiplayer_client.mainloop),
            Button(self, "Quit", theme="title", callback=self.stop)
        )

        self.button_credits = Button(self, "Credits", font=("calibri", 50), callback=self.dialog_credits.mainloop)

    def on_start_loop(self) -> None:
        self.disable_key_joy_focus_for_all_window()
        Button.draw_focus_outline(False)

    def on_quit(self) -> None:
        self.enable_key_joy_focus_for_all_window()
        Button.draw_focus_outline(True)

    def place_objects(self):
        self.bg.center = self.center
        self.logo.centerx = self.centerx
        self.menu_buttons.move(centerx=self.centerx, bottom=self.bottom - 20)
        self.button_credits.move(right=self.right - 10, bottom=self.bottom - 10)
Ejemplo n.º 17
0
class FinishWindow(Window):
    def __init__(self, master, victory: bool):
        Window.__init__(
            self,
            master=master,
            bg_music=None if victory is None else RESOURCES.MUSIC["end"])
        self.master = master
        self.bg = RectangleShape(self.width, self.height, (0, 0, 0, 170))
        self.frame = RectangleShape(0.5 * self.width,
                                    0.5 * self.height,
                                    GREEN_DARK,
                                    outline=2)
        self.victory = victory
        if victory is not None:
            message = "{winner} won".format(
                winner="You" if victory else "Enemy")
        else:
            message = "The enemy has left\nthe game"
        self.text_finish = Text(message, font=(None, 70))
        params_for_all_buttons = {
            "font": (None, 40),
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "highlight_color": YELLOW
        }
        self.button_restart = Button(self,
                                     "Restart",
                                     callback=self.restart,
                                     **params_for_all_buttons)
        self.button_return_to_menu = Button(self,
                                            "Return to menu",
                                            callback=self.stop,
                                            **params_for_all_buttons)
        self.ask_restart = False
        self.bind_key(pygame.K_ESCAPE, lambda event: self.stop())

    def update(self):
        if self.ask_restart:
            if self.master.client_socket.recv("restart"):
                self.master.restart = True
                self.stop()
            elif self.master.client_socket.recv("quit"):
                self.text_finish.message = "The enemy has left\nthe game"

    def place_objects(self):
        self.frame.center = self.center
        self.text_finish.center = self.frame.center
        if self.victory is not None:
            self.button_restart.move(bottom=self.frame.bottom - 20,
                                     centerx=self.frame.centerx -
                                     (self.frame.w // 4))
            self.button_return_to_menu.move(bottom=self.frame.bottom - 20,
                                            centerx=self.frame.centerx +
                                            (self.frame.w // 4))
        else:
            self.button_restart.hide()
            self.button_return_to_menu.move(bottom=self.frame.bottom - 20,
                                            centerx=self.frame.centerx)

    def restart(self):
        if self.master.client_socket.connected():
            self.ask_restart = True
            self.master.client_socket.send("restart")
            self.text_finish.message = "Waiting for\nenemy response"
            self.button_restart.hide()
            self.button_return_to_menu.move(bottom=self.frame.bottom - 20,
                                            centerx=self.frame.centerx)
        else:
            self.master.restart = True
            self.stop()
Ejemplo n.º 18
0
class Infos(RectangleShape):
    def __init__(self, master, *args, **kwargs):
        RectangleShape.__init__(self, *args, **kwargs)
        self.prog_name = Text(str(), (FONT["death_star"], 80),
                              YELLOW,
                              justify="center")
        self.prog_comment = Text(str(), (FONT["death_star"], 80),
                                 YELLOW,
                                 justify="center")
        self.infos_nb_selected = Text(f"0/{MAX_NB_PLAYERS}",
                                      (FONT["death_star"], 80), YELLOW)
        params_button = {
            "bg": BLUE,
            "hover_bg": BLUE_LIGHT,
            "active_bg": BLUE_DARK,
            "active_fg": YELLOW,
            "hover_sound": AUDIO["clank"],
            "on_click_sound": AUDIO["laser"],
            "outline": 5,
        }
        self.button_battle = Button(master,
                                    "Play",
                                    font=(FONT["death_star"], 80),
                                    **params_button,
                                    command=master.launch_game)
        self.default_width = 0

    def draw(self, surface):
        if self.is_shown():
            self.draw_shape(surface)
            self.prog_name.draw(surface)
            self.prog_comment.draw(surface)
            self.infos_nb_selected.draw(surface)
            self.button_battle.draw(surface)

    def hide_all(self):
        for obj in [
                self.prog_name, self.prog_comment, self.infos_nb_selected,
                self.button_battle
        ]:
            obj.hide()

    def update(self, *args, **kwargs):
        self.prog_name.move(centerx=self.centerx, bottom=self.centery - 70)
        self.prog_comment.move(centerx=self.centerx,
                               top=self.prog_name.centery + 70)
        self.infos_nb_selected.move(left=self.left + 10,
                                    bottom=self.bottom - 10)
        self.button_battle.move(centerx=self.centerx, bottom=self.bottom - 10)

    def update_nb_selected(self, nb):
        self.infos_nb_selected.string = f"{nb}/{MAX_NB_PLAYERS}"

    def show_infos(self, name: str, comment: str):
        self.prog_name.string = "Name : " + str(name)
        self.prog_comment.string = comment
        self.default_width = self.width - 30
        for obj in [self.prog_name, self.prog_comment]:
            length = len(obj.string)
            while obj.width > self.default_width:
                length -= 1
                obj.string = textwrap.fill(comment, width=length)

    def clear_frame(self):
        self.prog_name.string = str()
        self.prog_comment.string = str()
Ejemplo n.º 19
0
class Garage(Window):
    def __init__(self):
        Window.__init__(self,
                        bg_color=GRAY,
                        bg_music=RESOURCES.MUSIC["garage"])
        params_for_all_buttons = {
            "bg": GREEN,
            "hover_bg": GREEN_LIGHT,
            "active_bg": GREEN_DARK,
            "highlight_color": YELLOW,
            "hover_sound": RESOURCES.SFX["select"],
        }
        params_for_button_except_back = {
            "on_click_sound": RESOURCES.SFX["validate"],
            "disabled_sound": RESOURCES.SFX["block"],
            "disabled_bg": GRAY_LIGHT,
        }
        params_for_button_except_back.update(params_for_all_buttons)
        params_for_car_viewer = {
            k: params_for_button_except_back[k]
            for k in ["hover_sound", "on_click_sound"]
        }
        self.button_back = ImageButton(self,
                                       RESOURCES.IMG["blue_arrow"],
                                       **params_for_all_buttons,
                                       on_click_sound=RESOURCES.SFX["back"],
                                       callback=self.stop)
        self.car_viewer = CarViewer(self, SAVE["car"], **params_for_car_viewer)

        size_progress_bar = (300, 30)
        self.speed_bar = ProgressBar(*size_progress_bar, TRANSPARENT, GREEN)
        self.maniability_bar = ProgressBar(*size_progress_bar, TRANSPARENT,
                                           GREEN)
        self.braking_bar = ProgressBar(*size_progress_bar, TRANSPARENT, GREEN)

        self.left_arrow = ImageButton(
            self,
            img=RESOURCES.IMG["left_arrow"],
            active_img=RESOURCES.IMG["left_arrow_hover"],
            **params_for_button_except_back,
            callback=self.car_viewer.decrease_id)
        self.right_arrow = ImageButton(
            self,
            img=RESOURCES.IMG["right_arrow"],
            active_img=RESOURCES.IMG["right_arrow_hover"],
            **params_for_button_except_back,
            callback=self.car_viewer.increase_id)
        for arrow in [self.left_arrow, self.right_arrow]:
            arrow.take_focus(False)
        self.button_price = Button(self,
                                   font=(RESOURCES.FONT["algerian"], 40),
                                   img=Image(RESOURCES.IMG["piece"], size=40),
                                   compound="right",
                                   callback=self.buy_car,
                                   **params_for_button_except_back)
        self.button_play = Button(self,
                                  "Play",
                                  font=(RESOURCES.FONT["algerian"], 70),
                                  callback=self.play,
                                  **params_for_button_except_back)
        self.text_money = Text(format_number(SAVE["money"]),
                               (RESOURCES.FONT["algerian"], 50),
                               YELLOW,
                               img=Image(RESOURCES.IMG["piece"], height=40),
                               compound="right")
        self.text_highscore = Text(
            "Highscore: {}".format(format_number(SAVE["highscore"])),
            (RESOURCES.FONT["algerian"], 50), YELLOW)
        self.padlock = Image(RESOURCES.IMG["padlock"])
        self.bind_key(pygame.K_ESCAPE,
                      lambda event: self.stop(sound=RESOURCES.SFX["back"]))
        self.bind_joystick(
            0, "B", lambda event: self.stop(sound=RESOURCES.SFX["back"]))

    def update(self):
        self.left_arrow.set_visibility(self.car_viewer.id > 1)
        self.right_arrow.set_visibility(
            self.car_viewer.id < len(self.car_viewer))
        if not SAVE["owned_cars"][self.car_viewer.id]:
            self.padlock.show()
            price = self.car_viewer["price"]
            if isinstance(price, int):
                self.button_price.show()
                self.button_price.text = format_number(price)
                self.button_price.state = Button.NORMAL if SAVE[
                    "money"] >= price else Button.DISABLED
            else:
                self.button_price.hide()
            self.button_play.state = Button.DISABLED
        else:
            self.padlock.hide()
            self.button_price.hide()
            self.button_play.state = Button.NORMAL
            SAVE["car"] = self.car_viewer.id
        max_s = self.car_viewer.max_speed
        min_a = self.car_viewer.min_acceleration
        max_m = self.car_viewer.max_maniability
        min_b = self.car_viewer.min_braking
        s = self.car_viewer["max_speed"]
        a = self.car_viewer["acceleration"]
        m = self.car_viewer["maniability"]
        b = self.car_viewer["braking"]
        self.speed_bar.percent = (s + min_a) / (max_s + a)
        self.maniability_bar.percent = m / max_m
        self.braking_bar.percent = min_b / b

    def place_objects(self):
        self.button_back.topleft = (5, 5)
        self.car_viewer.move(center=self.center)
        self.padlock.center = self.car_viewer.center

        self.braking_bar.move(bottom=self.car_viewer.top - 40,
                              centerx=self.car_viewer.centerx + 100)
        self.maniability_bar.move(bottom=self.braking_bar.top - 10,
                                  centerx=self.car_viewer.centerx + 100)
        self.speed_bar.move(bottom=self.maniability_bar.top - 10,
                            centerx=self.car_viewer.centerx + 100)

        self.speed_bar.show_label("Speed/Acc.",
                                  ProgressBar.S_LEFT,
                                  font=(RESOURCES.FONT["algerian"], 40))
        self.maniability_bar.show_label("Maniability",
                                        ProgressBar.S_LEFT,
                                        font=(RESOURCES.FONT["algerian"], 40))
        self.braking_bar.show_label("Braking",
                                    ProgressBar.S_LEFT,
                                    font=(RESOURCES.FONT["algerian"], 40))

        self.left_arrow.move(left=self.left + 50, centery=self.centery)
        self.right_arrow.move(right=self.right - 50, centery=self.centery)
        self.button_price.move(centerx=self.centerx,
                               top=self.car_viewer.bottom + 25)
        self.button_play.move(bottom=self.bottom - 50, right=self.right - 10)

        self.text_money.move(top=5, right=self.right - 10)
        self.text_highscore.move(bottom=self.bottom - 50, left=5)

    def set_grid(self):
        self.button_back.set_obj_on_side(on_bottom=self.car_viewer)
        self.car_viewer.set_obj_on_side(on_top=self.button_back,
                                        on_bottom=self.button_price)
        self.button_price.set_obj_on_side(on_top=self.car_viewer,
                                          on_bottom=self.button_play)
        self.button_play.set_obj_on_side(on_top=self.button_price)

    def buy_car(self):
        confirm_window = ConfirmPayement(self)
        confirm_window.mainloop()
        if confirm_window.buyed:
            SAVE["money"] -= self.car_viewer["price"]
            SAVE["owned_cars"][self.car_viewer.id] = True
            self.text_money.message = format_number(SAVE["money"])
            if Clickable.MODE != Clickable.MODE_MOUSE:
                self.car_viewer.focus_set()

    def play(self):
        environment_chooser = EnvironmentChooser(self)
        environment_chooser.mainloop()
        self.text_money.message = format_number(SAVE["money"])
        self.text_highscore.message = "Highscore: {}".format(
            format_number(SAVE["highscore"]))