예제 #1
0
    def update(self, surface):
        if pygame.mouse.get_pressed()[0]:
            pos = pygame.mouse.get_pos()
            if self.bounds.collidepoint(pos):
                self.mode = (self.mode + 1) % 5
                if self.mode == 1:
                    self.mode += 1
                self.value = 1
                self.prev = 0
                self.color = (0, 0, 0)
                if self.mode == 3:
                    self.prev = 1
        if pygame.mouse.get_pressed()[2]:
            pos = pygame.mouse.get_pos()
            if self.bounds.collidepoint(pos) and self.mode > 1:
                if self.mode == 2:
                    txtbx = InputBox(self.x + 30, self.y + 30, pygame.font.SysFont("Arial", 20), 6, str(self.value),
                                     'Resistance', 'mOm')
                if self.mode == 4:
                    txtbx = InputBox(self.x + 30, self.y + 30, pygame.font.SysFont("Arial", 20), 6, str(self.value),
                                     'Inductance', 'H')
                if self.mode == 3:
                    txtbx = InputBox(self.x + 30, self.y + 30, pygame.font.SysFont("Arial", 20), 6, str(self.value),
                                     'Capacity', 'F')
                while 1:
                    events = pygame.event.get()

                    pygame.draw.rect(surface, (255, 255, 255), (self.x + 30, self.y + 30, 300, 50), 0)
                    pygame.draw.rect(surface, (0, 0, 0), (self.x + 30, self.y + 30, 300, 50), 2)
                    ans = txtbx.update(events)
                    if ans is not None:
                        self.value = int(ans)
                        break
                    txtbx.draw(surface)
                    pygame.display.flip()
예제 #2
0
class Menu:
    """Ecran dans lequel on a une input_box permettant d'entrer un pseudo puis d'essayer de se connecter à une session.
    """



    def __init__(self, client, message=None):
        self.client = client
        self.inputbox = InputBox(client.window_width / 2 - 100, client.window_height / 2 - 12, self.launch)
        self.inputbox.isWriting = True
        self.logger = Logger()
        if(not message is None):
            self.logger.add_message(message, (255, 0, 0))
        self.logger.add_message("Please enter a username")
        self.main_loop()

    def main_loop(self):
        while(True):
            self.handle_keyboard_input()

            self.draw_frame()

            self.client.clock.tick(REFRESH_TICKRATE)
    
    def handle_keyboard_input(self):
        keys = pygame.key.get_pressed()
        self.inputbox.handle_continuous_pressed_keys(keys)

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

            if(event.type == pygame.KEYDOWN):
                if(event.key == pygame.K_ESCAPE):
                    self.stop()
                self.inputbox.handle_input_event(event)
            
    def draw_frame(self):
        self.client.window.fill((0, 0, 0))
        self.inputbox.draw(self.client.window)
        self.logger.draw(self.client.window)
        pygame.display.update()


    def stop(self):
        pygame.quit()
        exit(0)

    def launch(self, text):
        """Fonction pour lancer une partie multijoueur. On vérifie la validité du pseudo avant de lancer la partie
        """
        if(not re.match('^[a-z]+$', text) or len(text) > 10):
            self.logger.add_message("The username must be composed of only lower case letters and be less than 10 characters")
            pass
        else:
            multiplayer_game.MultiplayerGame(self.client, text)
예제 #3
0
def game(players):
    input_box = InputBox(440, 340, 480, 50)
    quit_button = Button(690, 520, 80, 50, 'QUIT', 'quit')
    start_button = Button(680, 440, 100, 50, 'START', 'start')
    player_text = Player(140, 160, 130, 50)
    play = GuessWord()
    snowman = SnowMan()
    rand_word = play.random_word()
    print_word = [False for i in range(len(rand_word))]
    in_letter = []
    out_letter = []

    done = False
    start_game = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
                pg.quit()
                quit()
            input_box.handle_event(event)
            quit_button.handle_event(event)
            start_game = start_button.handle_event(event)

        SCREEN.fill(PURPLE)
        quit_button.draw(SCREEN)

        if len(out_letter) == 14:
            start_button.draw(SCREEN)
        else:
            if in_letter == list(rand_word):
                if players:
                    won = (len(in_letter) + len(out_letter)) % 2
                    if won:
                        player_text.text = 'Player 2!'
                    else:
                        player_text.text = 'Player 1!'
                    player_text.draw(SCREEN)
                start_button.draw(SCREEN)
            else:
                input_box.draw(SCREEN)
                if input_box.text in rand_word:
                    if input_box.text not in in_letter:
                        in_letter = play.check_in(input_box.text, print_word)
                else:
                    if input_box.text not in out_letter:
                        if len(out_letter) <= 14:
                            out_letter.append(input_box.text)
        play.draw_lines(SCREEN, print_word)
        if start_game:
            done = True
        snowman.wrong_letter = out_letter
        snowman.draw_snowman(SCREEN)

        pg.display.flip()
예제 #4
0
def main():
    clock = pg.time.Clock()
    input_box1 = InputBox(100, 100, 140, 32)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            input_box1.handle_event(event)

        screen.fill((30, 30, 30))
        input_box1.draw(screen)

        input_box1.update()
        pg.display.flip()
        clock.tick(30)
예제 #5
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 450))
    screen.fill(pygame.Color('white'))
    mp = MapParams()
    input_box = InputBox(50, 10, 140, 32)
    im = Image.open('data/search_icon.png')
    im = im.resize((30, 30))
    im.save('data/search_icon.png')
    button = pygame.image.load('data/search_icon.png').convert_alpha()
    b_rect = pygame.Rect(10, 10, 50, 50)
    reset = Button('Сброс поискового результата', 350, 10, 24)
    while True:
        event = pygame.event.wait()
        if event.type == pygame.QUIT:  # Выход из программы
            break
        elif event.type == pygame.KEYUP:  # Обрабатываем различные нажатые клавиши.
            mp.update(event)
        elif event.type == pygame.MOUSEBUTTONUP:  # Выполняем поиск по клику мышки.
            if event.button == 1:  # LEFT_MOUSE_BUTTON
                mp.add_reverse_toponym_search(event.pos)
                if b_rect.collidepoint(event.pos):
                    text = input_box.text
                    toponym = reverse_geocode(text)
                    if toponym:
                        point = toponym['Point']['pos'].split()
                        mp.lon = float(point[0])
                        mp.lat = float(point[1])
                        mp.search_result = SearchResult(
                            point, toponym["metaDataProperty"]
                            ["GeocoderMetaData"]["text"] if toponym else None,
                            toponym["metaDataProperty"]["GeocoderMetaData"]
                            ["Address"].get("postal_code")
                            if toponym else None)
                    else:
                        input_box.text = 'Ничего не найдено'
                if reset.rect.collidepoint(event.pos):
                    mp.search_result = None
            elif event.button == 3:  # RIGHT_MOUSE_BUTTON
                mp.add_reverse_org_search(event.pos)
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN and input_box.active:
                text = input_box.text
                toponym = reverse_geocode(text)
                if toponym:
                    point = toponym['Point']['pos'].split()
                    mp.lon = float(point[0])
                    mp.lat = float(point[1])
                    mp.search_result = SearchResult(
                        point,
                        toponym["metaDataProperty"]["GeocoderMetaData"]["text"]
                        if toponym else None,
                        toponym["metaDataProperty"]["GeocoderMetaData"]
                        ["Address"].get("postal_code") if toponym else None)
                else:
                    input_box.text = 'Ничего не найдено'
        map_file = load_map(mp)
        screen.blit(pygame.image.load(map_file), (0, 0))
        if mp.search_result:
            if mp.use_postal_code and mp.search_result.postal_code:
                text = render_text(mp.search_result.postal_code + ", " +
                                   mp.search_result.address)
            else:
                text = render_text(mp.search_result.address)
            screen.blit(text, (20, 400))
        input_box.handle_event(event)
        input_box.update()
        input_box.draw(screen)
        screen.blit(button, b_rect)
        reset.draw(screen)
        screen.blit(screen, (0, 0))
        pygame.display.flip()
    pygame.quit()
    os.remove(map_file)
예제 #6
0
파일: login.py 프로젝트: mtnkdev/toaruos
class InputWindow(yutani.Window):

    def __init__(self):
        _w = yutani.yutani_ctx._ptr.contents.display_width
        _h = yutani.yutani_ctx._ptr.contents.display_height

        self.logo = cairo.ImageSurface.create_from_png('/usr/share/logo_login.png')

        super(InputWindow, self).__init__(272, self.logo.get_height() + 110 + 50, doublebuffer=True)
        self.update_position(_w,_h)

        self.username = InputBox(placeholder="Username",width=180)
        self.password = InputBox(password=True,placeholder="Password",width=180)
        self.focused_widget = None

        self.username.tab_handler = self.focus_password
        self.password.tab_handler = self.focus_username

        self.username.submit = self.password_or_go
        self.password.submit = self.go

        self.error_font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 11, 0xFFFF0000)
        self.error_font.set_shadow((0xFF000000, 2, 0, 0, 3.0))
        self.error_tr = text_region.TextRegion(0,0,self.width,20,font=self.error_font)
        self.error_tr.set_alignment(2)

        self.error = None

    def focus_changed(self, msg):
        if not msg.focused:
            self.username.focus_leave()
            self.password.focus_leave()

    def update_position(self, w, h):
        self.move(int((w - self.width)/2),int((h - self.height)/2))

    def finish_resize(self, msg):
        pass # lol no

    def draw(self):
        surface = self.get_cairo_surface()
        ctx = cairo.Context(surface)

        # Clear
        ctx.set_operator(cairo.OPERATOR_SOURCE)
        ctx.rectangle(0,0,self.width,self.height)
        ctx.set_source_rgba(0,0,0,0)
        ctx.fill()

        ctx.set_operator(cairo.OPERATOR_OVER)

        ctx.set_source_surface(self.logo, (self.width - self.logo.get_width())/2, 0)
        ctx.paint()

        base = self.height - 110

        rounded_rectangle(ctx, 0, base, self.width, 110, 4)
        ctx.set_source_rgba(0,0,0,0.5)
        ctx.fill()

        if self.error:
            self.error_tr.move(0,base+8)
            self.error_tr.set_text(self.error)
            self.error_tr.draw(self)

        ctx.save()
        ctx.translate(46,base + 30)
        self.username.draw(self,ctx)
        ctx.restore()

        ctx.save()
        ctx.translate(46,base + 60)
        self.password.draw(self,ctx)
        ctx.restore()

        self.flip()

    def keyboard_event(self, msg):
        if self.focused_widget:
            self.focused_widget.keyboard_event(msg)
        else:
            self.focus_username()
            self.focused_widget.keyboard_event(msg)

    def focus_password(self):
        self.username.focus_leave()
        self.password.focus_enter()
        self.focused_widget = self.password
        self.draw()

    def focus_username(self):
        self.password.focus_leave()
        self.username.focus_enter()
        self.focused_widget = self.username
        self.draw()

    def password_or_go(self):
        if self.password.text:
            self.go()
        else:
            self.focus_password()

    def go(self):
        print(f"USER {self.username.text}")
        print(f"PASS {self.password.text}")
        print(f"AUTH",flush=True)
        response = input()
        if response == "FAIL":
            self.error = "Incorrect username or password."
            self.username.update_text("")
            self.password.update_text("")
            self.username.reset_cursor()
            self.password.reset_cursor()
            self.focus_username()
            self.draw()
        elif response == "SUCC":
            sys.exit(0)


    def mouse_event(self, msg):
        if self.username.mouse_event(msg):
            self.focus_username()
        elif self.password.mouse_event(msg):
            self.focus_password()
        elif msg.command == yutani.MouseEvent.DOWN:
            self.password.focus_leave()
            self.username.focus_leave()
            self.focused_widget = None
예제 #7
0
class InputWindow(yutani.Window):
    def __init__(self):
        _w = yutani.yutani_ctx._ptr.contents.display_width
        _h = yutani.yutani_ctx._ptr.contents.display_height

        self.logo = cairo.ImageSurface.create_from_png(
            '/usr/share/logo_login.png')

        super(InputWindow, self).__init__(272,
                                          self.logo.get_height() + 110 + 50,
                                          doublebuffer=True)
        self.update_position(_w, _h)

        self.username = InputBox(placeholder="Username", width=180)
        self.password = InputBox(password=True,
                                 placeholder="Password",
                                 width=180)
        self.focused_widget = None

        self.username.tab_handler = self.focus_password
        self.password.tab_handler = self.focus_username

        self.username.submit = self.password_or_go
        self.password.submit = self.go

        self.error_font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 11,
                                           0xFFFF0000)
        self.error_font.set_shadow((0xFF000000, 2, 0, 0, 3.0))
        self.error_tr = text_region.TextRegion(0,
                                               0,
                                               self.width,
                                               20,
                                               font=self.error_font)
        self.error_tr.set_alignment(2)

        self.error = None

    def focus_changed(self, msg):
        if not msg.focused:
            self.username.focus_leave()
            self.password.focus_leave()

    def update_position(self, w, h):
        self.move(int((w - self.width) / 2), int((h - self.height) / 2))

    def finish_resize(self, msg):
        pass  # lol no

    def draw(self):
        surface = self.get_cairo_surface()
        ctx = cairo.Context(surface)

        # Clear
        ctx.set_operator(cairo.OPERATOR_SOURCE)
        ctx.rectangle(0, 0, self.width, self.height)
        ctx.set_source_rgba(0, 0, 0, 0)
        ctx.fill()

        ctx.set_operator(cairo.OPERATOR_OVER)

        ctx.set_source_surface(self.logo,
                               (self.width - self.logo.get_width()) / 2, 0)
        ctx.paint()

        base = self.height - 110

        rounded_rectangle(ctx, 0, base, self.width, 110, 4)
        ctx.set_source_rgba(0, 0, 0, 0.5)
        ctx.fill()

        if self.error:
            self.error_tr.move(0, base + 8)
            self.error_tr.set_text(self.error)
            self.error_tr.draw(self)

        ctx.save()
        ctx.translate(46, base + 30)
        self.username.draw(self, ctx)
        ctx.restore()

        ctx.save()
        ctx.translate(46, base + 60)
        self.password.draw(self, ctx)
        ctx.restore()

        self.flip()

    def keyboard_event(self, msg):
        if self.focused_widget:
            self.focused_widget.keyboard_event(msg)
        else:
            self.focus_username()
            self.focused_widget.keyboard_event(msg)

    def focus_password(self):
        self.username.focus_leave()
        self.password.focus_enter()
        self.focused_widget = self.password
        self.draw()

    def focus_username(self):
        self.password.focus_leave()
        self.username.focus_enter()
        self.focused_widget = self.username
        self.draw()

    def password_or_go(self):
        if self.password.text:
            self.go()
        else:
            self.focus_password()

    def go(self):
        print(f"USER {self.username.text}")
        print(f"PASS {self.password.text}")
        print(f"AUTH", flush=True)
        response = input()
        if response == "FAIL":
            self.error = "Incorrect username or password."
            self.username.update_text("")
            self.password.update_text("")
            self.username.reset_cursor()
            self.password.reset_cursor()
            self.focus_username()
            self.draw()
        elif response == "SUCC":
            sys.exit(0)

    def mouse_event(self, msg):
        if self.username.mouse_event(msg):
            self.focus_username()
        elif self.password.mouse_event(msg):
            self.focus_password()
        elif msg.command == yutani.MouseEvent.DOWN:
            self.password.focus_leave()
            self.username.focus_leave()
            self.focused_widget = None
예제 #8
0
import pygame
from input_box import InputBox

pygame.init()
window = pygame.display.set_mode((800, 800))

testTextBox = InputBox(40, 100, 200, 50, "enter text here")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        testTextBox.runInputBox(event)

    window.fill((54, 54, 54))
    testTextBox.draw(window)

    pygame.display.update()
예제 #9
0
class MultiplayerGame:
    def __init__(self, client, username):
        self.client = client
        self.logger = Logger()
        self.score_displayer = Score(username)
        self.inputbox = InputBox(5, self.client.window_width - 30,
                                 self.send_message)
        self.username = username
        self.is_socket_connected_to_server = False
        self.session_state = "nosession"  # Indicate whether we not connected, requested connection or in a session
        self.socket = None

        self.arena = Arena(self.client.window_width,
                           self.client.window_height)  # Creation de l'arene
        self.main_player = Player("player.png", self.username, to_display=True)

        self.last_newcom = 0

        self.arena.players[username] = self.main_player
        self.main_loop()

    def main_loop(self):
        while (True):
            self.handle_server_coms()

            self.handle_keyboard_input()

            self.enitities_update()

            self.draw_frame()

            self.client.clock.tick(
                REFRESH_TICKRATE
            )  # Limite le nombre de mise a jour par seconde

    def handle_server_coms(self):
        if (not self.is_socket_connected_to_server):
            self.logger.add_message("Connecting to server...")

            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                self.socket.connect((HOST, PORT))
            except ConnectionRefusedError:
                menu.Menu(self.client, "Connection to server failed")
            self.logger.add_message("Connection successful.")
            self.is_socket_connected_to_server = True

        if (self.session_state == "nosession"):
            self.logger.add_message("Trying to join a session...")
            self.session_state = "request"
            send_serveur.connect(self.socket, self.username)
        elif (self.session_state == "jeu"):
            # send_serveur.newpos(self.socket, self.main_player.pos)

            if (time.time() - self.last_newcom > 1 / SERVER_TICKRATE):
                send_serveur.newcom(self.socket,
                                    self.main_player.command_angle,
                                    self.main_player.command_thrust,
                                    self.main_player.hasShoot)
                self.main_player.hasShoot = False
                self.last_newcom = time.time()

                # Commands sent, reset
                self.main_player.command_angle = 0
                self.main_player.command_thrust = 0

        self.handle_server_responses()

    def handle_server_responses(self):
        try:
            data = self.socket.recv(8192, socket.MSG_DONTWAIT)
        except BlockingIOError:  # Nothing to read
            return

        commands = data.decode().split("\n")
        commands = [cmd.split("/") for cmd in commands]
        # print(commands)

        for cmd in commands:
            if (cmd[0] == "WELCOME"):
                self.apply_command_welcome(cmd)
            elif (cmd[0] == "DENIED"):
                self.apply_command_denied(cmd)
            elif (cmd[0] == "NEWPLAYER"):
                self.apply_command_newplayer(cmd)
            elif (cmd[0] == "PLAYERLEFT"):
                self.apply_command_playerleft(cmd)
            elif (cmd[0] == "SESSION"):
                self.apply_command_session(cmd)
            elif (cmd[0] == "WINNER"):
                self.apply_command_winner(cmd)
            elif (cmd[0] == "TICK"):
                self.apply_command_tick(cmd)
            elif (cmd[0] == "TICK2"):
                self.apply_command_tick2(cmd)
            elif (cmd[0] == "NEWOBJ"):
                self.apply_command_newobj(cmd)
            elif (cmd[0] == "RECEPTION"):
                self.apply_command_reception(cmd)
            elif (cmd[0] == "PRECEPTION"):
                self.apply_command_preception(cmd)

    def apply_command_welcome(self, cmd):
        phase = cmd[1]
        scores = cmd[2]
        coord = cmd[3]
        obs_coords = cmd[4]

        if (phase == "attente"):
            self.logger.add_message("Waiting to start session")
            self.logger.add_message("Type /race to start a race next")
            self.session_state = "attente"
        elif (phase == "jeu" or phase == "ingame_race"):
            self.logger.add_message("Joining a game")
            self.session_state = "jeu"
            goals_coord = coord.split("|")
            goalx, goaly = parse_coord(goals_coord[0])
            if (len(goals_coord) == 2):
                nextgoalx, nextgoaly = parse_coord(goals_coord[1])
                self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)
            else:
                self.arena.next_goal = None
            self.arena.goal = Goal(goalx, goaly)
            self.main_player.to_display = False  # Wait to get coord before displaying
            for s in scores.split("|"):
                [name, score] = s.split(":")
                if (name in self.arena.players):
                    self.arena.players[name].score = int(score)
                else:
                    new_player = Player("enemy.png", name)
                    new_player.score = int(score)
                    self.arena.players[name] = new_player

            if (len(obs_coords) > 0):
                for o in obs_coords.split("|"):
                    pos = parse_coord(o)
                    self.arena.obstacles.append(Obstacle(pos[0], pos[1]))

    def apply_command_denied(self, cmd):
        self.logger.add_message("Joining session failed")
        menu.Menu(self.client,
                  "This username is already taken, please choose another")

    def apply_command_newplayer(self, cmd):
        user = cmd[1]
        self.logger.add_message(user + " joins the game")
        self.arena.players[user] = Player("enemy.png", user)

    def apply_command_playerleft(self, cmd):
        user = cmd[1]
        self.logger.add_message(user + " left the game")
        if (user in self.arena.players):
            del self.arena.players[user]

    def apply_command_session(self, cmd):
        coords = cmd[1]
        coord = cmd[2]
        obs_coords = cmd[3]

        self.logger.add_message("Session starting !")
        players_coords = coords.split("|")
        for p in players_coords:
            [name, pos] = p.split(":")
            pos = parse_coord(pos)
            if (name in self.arena.players):
                self.arena.players[name].reset()
                self.arena.players[name].moveTo(pos[0], pos[1])
                self.arena.players[name].to_display = True
            else:
                self.arena.players[name] = Player("enemy.png", name, pos, True)
        goals_coord = coord.split("|")
        goalx, goaly = parse_coord(goals_coord[0])
        if (len(goals_coord) == 2):
            nextgoalx, nextgoaly = parse_coord(goals_coord[1])
            self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)

        self.arena.goal = Goal(goalx, goaly)

        if (len(obs_coords) > 0):
            for o in obs_coords.split("|"):
                pos = parse_coord(o)
                self.arena.obstacles.append(Obstacle(pos[0], pos[1]))

        self.session_state = "jeu"

    def apply_command_winner(self, cmd):
        scores = cmd[1]
        for s in scores.split("|"):
            [name, score] = s.split(":")
            self.arena.players[name].score = int(score)
            if (int(score) == WIN_CAP):
                winner = name
        if (self.username == winner):
            self.logger.add_message(
                "End of game, congratulations you are the winner !!")
        else:
            self.logger.add_message("End of game, winner is : " + winner)
        self.logger.add_message("A new game will restart soon")
        self.session_state = "attente"
        self.arena.goal = None
        self.arena.obstacles.clear()
        self.arena.attacks.clear()
        # Don't display other player if not ingame
        for p in self.arena.players.values():
            if (not p.username == self.username):
                p.to_display = False

    def apply_command_tick(self, cmd):
        coords = cmd[1]
        self.arena.attacks.clear()
        players_coords = coords.split("|")
        for p in players_coords:
            [name, vals] = p.split(":")
            pos, vector, direction = parse_coord(vals)
            player = self.arena.players[name]
            player.moveTo(pos[0], pos[1])
            player.direction = direction
            player.vector = vector
            player.to_display = True

    def apply_command_tick2(self, cmd):
        self.apply_command_tick(cmd)

        self.arena.attacks.clear()
        coords = cmd[2]
        for a in coords.split("|"):
            pos = parse_coord(a)
            self.arena.attacks.append(Attack(pos[0], pos[1], pos[2]))

    def apply_command_newobj(self, cmd):
        coord = cmd[1]
        scores = cmd[2]
        for s in scores.split("|"):
            [name, score] = s.split(":")
            self.arena.players[name].score = int(score)

        goals_coord = coord.split("|")
        goalx, goaly = parse_coord(goals_coord[0])
        if (len(goals_coord) == 2):
            nextgoalx, nextgoaly = parse_coord(goals_coord[1])
            self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)
        else:
            self.arena.next_goal = None
        self.arena.goal = Goal(goalx, goaly)

    def apply_command_reception(self, cmd):
        message = cmd[1]
        self.logger.add_message(message, (255, 0, 0))

    def apply_command_preception(self, cmd):
        message = cmd[1]
        user = cmd[2]
        self.logger.add_message("From " + user + " : " + message,
                                (255, 105, 180))

    def handle_keyboard_input(self):
        keys = pygame.key.get_pressed()
        if (not self.inputbox.isWriting):
            if (keys[pygame.K_q] or keys[pygame.K_LEFT]):
                self.main_player.anticlock()
            elif (keys[pygame.K_d] or keys[pygame.K_RIGHT]):
                self.main_player.clock()
        else:
            self.inputbox.handle_continuous_pressed_keys(keys)

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

            if (event.type == pygame.KEYDOWN):
                if (not self.inputbox.isWriting):
                    if (event.key == pygame.K_SPACE):
                        self.main_player.thrust()
                    if (event.key == pygame.K_e):
                        self.main_player.shoot()
                    if (event.key == pygame.K_ESCAPE):
                        self.stop()
                self.inputbox.handle_input_event(event)

    def enitities_update(self):
        self.arena.update(
        )  # Updates every players in the arena including the main_player

    def draw_frame(self):
        self.client.window.fill(
            (0, 0, 0))  # Efface tout ce qui est sur la fenetre
        self.arena.draw(self.client.window)  # Dessine toutes les entites
        self.logger.draw(self.client.window)
        self.score_displayer.draw(self.arena.players, self.client.window)
        self.inputbox.draw(self.client.window)
        pygame.display.update()  # Met a jour la fenetre

    def stop(self):
        if (not self.socket is None):
            self.socket.close()
        pygame.quit()
        exit(0)

    def send_message(self, text):
        words = text.split(" ")
        if (len(words) >= 3 and words[0] == "/w" and len(words[1]) > 0
                and len(words[2]) > 0):
            msg = " ".join(words[2:])
            self.logger.add_message("To " + words[1] + " : " + msg,
                                    (255, 105, 180))
            send_serveur.sendpmsg(self.socket, words[1], msg)
        elif (len(words) == 1 and words[0] == "/race"):
            self.logger.add_message("The next session will be a race")
            send_serveur.sendrace(self.socket)
        else:
            self.logger.add_message(text, (255, 0, 0))
            send_serveur.sendmsg(self.socket, text)
예제 #10
0
class ColoradTheGame:
    screen_size = None
    screen = None
    background_color = None
    clock = None
    seed = None

    font_path = None

    # UI
    grid = None
    text_box_score = None
    text_box_score_value = None
    text_box_cur_seed = None
    text_box_cur_seed_value = None
    text_box_seed = None
    input_box_seed = None
    button_generate = None

    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()

        # window
        self.screen_size = (842, 562)
        self.background_color = (222, 213, 200)
        self.screen = pygame.display.set_mode(self.screen_size)
        pygame.display.set_caption('Colorad')
        self.font_path = 'fonts/Quicksand-Bold.ttf'

        # grid
        self.seed = 180603
        self.grid = Grid(size=(32, 32),
                         point_pxl=(20, 20),
                         border_color=(205, 192, 180),
                         border_thickness_pxl=5,
                         cell_size_pxl=(16, 16),
                         spacing_pxl=(0, 0),
                         cell_colors=color_values,
                         random_seed=self.seed)

        # text box score
        self.text_box_score = TextBox(point=(550, 20),
                                      font_path=self.font_path,
                                      font_size=32,
                                      font_color=(100, 92, 85))
        self.text_box_score.set_text("Score:")

        # text box score value
        self.text_box_score_value = TextBox(point=(550, 50),
                                            font_path=self.font_path,
                                            font_size=32,
                                            font_color=(100, 92, 85))
        self.text_box_score_value.set_text(str(self.grid.total_score))

        # text box current seed
        self.text_box_cur_seed = TextBox(point=(550, 150),
                                         font_path=self.font_path,
                                         font_size=32,
                                         font_color=(100, 92, 85))
        self.text_box_cur_seed.set_text("Current seed:")

        # text box current seed value
        self.text_box_cur_seed_value = TextBox(point=(550, 180),
                                               font_path=self.font_path,
                                               font_size=32,
                                               font_color=(100, 92, 85))
        self.text_box_cur_seed_value.set_text(str(self.seed))

        # text box seed
        self.text_box_seed = TextBox(point=(550, 280),
                                     font_path=self.font_path,
                                     font_size=32,
                                     font_color=(100, 92, 85))
        self.text_box_seed.set_text("Enter seed:")

        # input box seed
        self.input_box_seed = InputBox(point=(550, 320),
                                       length=140,
                                       max_char=10,
                                       font_size=32,
                                       text_padding=(4, -4),
                                       font_path=self.font_path)

        # button generate
        self.button_generate = Button(point=(550, 360),
                                      size=(147, 40),
                                      text='Generate',
                                      text_padding=(10, 0),
                                      font_path=self.font_path,
                                      font_size=28,
                                      font_color=(100, 92, 85),
                                      background_color=(205, 192, 180),
                                      callback=self.set_seed)

        # draw the first time!!
        self.draw()

    #_____core_____
    def run(self):
        running = True
        # main loop
        while (running):
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    self.on_mouse_button_down(event)
                elif event.type == pygame.KEYDOWN:
                    self.on_key_down(event)

            if self.is_end_game():
                self.end_game()

            self.clock.tick(30)

        # loop over, quite pygame
        pygame.quit()

    def update(self):
        self.text_box_score_value.set_text(str(self.grid.total_score))
        self.text_box_cur_seed_value.set_text(str(self.seed))

    def draw(self):
        # clear screen
        self.screen.fill(self.background_color)

        self.grid.draw(self.screen)
        self.text_box_score.draw(self.screen)
        self.text_box_score_value.draw(self.screen)
        self.text_box_cur_seed.draw(self.screen)
        self.text_box_cur_seed_value.draw(self.screen)
        self.text_box_seed.draw(self.screen)
        self.input_box_seed.draw(self.screen)
        self.button_generate.draw(self.screen)
        # update screen
        pygame.display.flip()

    #_____events_____
    def on_key_down(self, event):
        self.input_box_seed.on_key_down(event)
        self.update()
        self.draw()

    def on_mouse_button_down(self, event):
        self.grid.on_mouse_button_down(event)
        self.input_box_seed.on_mouse_button_down(event)
        self.button_generate.on_mouse_button_down(event)
        self.update()
        self.draw()

    def is_end_game(self):
        return self.grid.is_empty()

    def end_game(self):
        print("end game!!!")

    #_____logic_____
    def set_seed(self):
        try:
            seed = int(self.input_box_seed.text)
            self.seed = seed
        except:
            pass

        self.grid.reset_seed(self.seed)

        self.update()
        self.draw()
예제 #11
0
class NameScene(SceneBase):
    def __init__(self):
        SceneBase.__init__(self)
        self.FONT = pygame.font.SysFont(FONT_FAMILY, FONT_SIZE)
        self.play_button = pygame.Rect(WIN_WIDTH * 5.5 / 10,
                                       WIN_HEIGHT * 3 / 5, WIN_WIDTH / 5,
                                       WIN_HEIGHT / 10)
        self.back_button = pygame.Rect(WIN_WIDTH * 2.5 / 10,
                                       WIN_HEIGHT * 3 / 5, WIN_WIDTH / 5,
                                       WIN_HEIGHT / 10)
        self.play_text = self.FONT.render('PLAY', False, pygame.Color(WHITE))
        self.back_text = self.FONT.render('back', False, pygame.Color(BLUE))
        self.enter_name_text = self.FONT.render('Enter your name', False,
                                                pygame.Color(BLUE))
        self.name_input_form = InputBox(WIN_WIDTH * 2.5 / 10,
                                        WIN_HEIGHT * 2 / 5, WIN_WIDTH / 2,
                                        WIN_HEIGHT / 10)
        self.hint_text = self.FONT.render('', False, pygame.Color(RED))
        self.blank_from = True

    def process_input(self, events, pressed_keys):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = event.pos

                if self.play_button.collidepoint(mouse_pos):
                    if self.name_input_form.get_text() != '':
                        self.save()
                        self.switch_to_scene(GameScene())
                        self.blank_from = False
                    else:
                        self.hint_text = self.FONT.render(
                            'Enter name!', False, pygame.Color(RED))
                if self.back_button.collidepoint(mouse_pos):
                    from menu_scene import MenuScene
                    self.switch_to_scene(MenuScene())
            self.name_input_form.handle_event(event)

    def update(self):
        pygame.display.update()

    def render(self, screen):
        screen.fill(pygame.Color(BACKGROUND_COLOR))

        # Play button position
        screen.blit(self.play_text, (WIN_WIDTH * 5.5 / 10, WIN_HEIGHT * 3 / 5))

        # Back score button
        screen.blit(self.back_text, (WIN_WIDTH * 2.5 / 10, WIN_HEIGHT * 3 / 5))

        # Enter name text
        screen.blit(self.enter_name_text,
                    (WIN_WIDTH * 2.5 / 10, WIN_HEIGHT * 1 / 5))

        # Hint text
        screen.blit(self.hint_text, (WIN_WIDTH * 2.5 / 10, WIN_HEIGHT * 4 / 5))

        # Draw input form with text
        self.name_input_form.draw(screen)

    def save(self):
        f = open(SCORE_FILE, 'a')
        f.write(self.name_input_form.text + ':')
        f.close()
예제 #12
0
        banner_rect.x = math.ceil(
            (screen.get_width() - banner.get_width()) / 2)
        banner_rect.y = math.ceil((screen.get_height() - title_pos_y -
                                   text_height - banner.get_height()) / 2)
        screen.blit(play_button, (play_button_rect))
        play_button_rect.x = math.ceil(
            (screen.get_width() - play_button.get_width()) / 2)
        play_button_rect.y = screen.get_height() - math.ceil(
            screen.get_height() - box.rect.y - box.rect.h -
            play_button.get_height() / 2)
        if seconds % 2 == 0:
            screen.blit(
                input_info,
                (width / 2 - input_info.get_width() / 2, height / 4 * 2.35))
        box.update()
        box.draw(screen)
        if box.is_error:
            box.error_surface = FONT.render(box.error, True, (255, 255, 255))
        else:
            box.error_surface = FONT.render(box.error, True, (0, 0, 0))
        game.name_player = box.text.strip()
        screen.blit(box.error_surface, (math.ceil(
            (screen.get_width() - box.error_surface.get_width()) /
            2), box.rect.y + box.rect.h + math.ceil(
                (play_button_rect.y - (box.rect.y + box.rect.h) - 32) / 2)))

    pygame.display.flip()

    # si le on ferme la fenetre
    for event in pygame.event.get():
        box.handle_event(event)