Example #1
0
    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
Example #2
0
    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
Example #3
0
 def __init__(self):
     """ Creating a new application """
     pygame.init()
     self.screen = pygame.display.set_mode(self.SCREEN_SIZE)
     pygame.display.set_caption("PyGraph")
     pygame.display.set_icon(pygame.image.load("icon.png").convert_alpha())
     self.graph = Graph()
     self.input_box = InputBox()
     self.loop()
Example #4
0
 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()
Example #5
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()
Example #6
0
    def _change_port(self, s):
        if s:
            Logger.info('MainWindow: Selected port {}'.format(s))

            if s.startswith('network'):
                mb = InputBox(
                    title='Network address',
                    text='Enter network address as "ipaddress[:port]"',
                    cb=self._new_network_port)
                mb.open()

            else:
                self.config.set('General', 'serial_port', s)
                self.config.write()
Example #7
0
def create_input_box(ap_settings, stats):
    """Creates the input box for urns and places it"""
    x = 20
    y = stats.button_height_max * 6
    w = 140
    h = 32
    InputBox(x, y, w, y)
Example #8
0
 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
Example #9
0
    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()
Example #10
0
class Application:
    """ Graphing application that draws given input """
    SCREEN_SIZE = (Graph.SIZE[0], Graph.SIZE[1] + InputBox.SIZE[1])

    def __init__(self):
        """ Creating a new application """
        pygame.init()
        self.screen = pygame.display.set_mode(self.SCREEN_SIZE)
        pygame.display.set_caption("PyGraph")
        pygame.display.set_icon(pygame.image.load("icon.png").convert_alpha())
        self.graph = Graph()
        self.input_box = InputBox()
        self.loop()

    def loop(self):
        """ Event and draw loop """
        while True:
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 4:
                        self.graph.zoom_in()
                    elif event.button == 5:
                        self.graph.zoom_out()
            self.input_box.handle_events(events)
            self.graph.update(self.function)
            self.screen.blit(self.graph.image, (0, 0))
            self.screen.blit(self.input_box.image, (0, self.graph.SIZE[1]))
            pygame.display.flip()

    def function(self, x):
        """ To be passed to the graph """
        try:
            return eval(self.input_box.input)
        except (NameError, SyntaxError, ValueError):
            return None
Example #11
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)
Example #12
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()
Example #13
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)
def run_program():
    # Initialize the program and create a screen object.
    pygame.init()

    ap_settings = Settings()

    screen = pygame.display.set_mode(
        (ap_settings.screen_width, ap_settings.screen_height))
    pygame.display.set_caption("Synthesizer (beta)")
    screen.fill(ap_settings.bg_color)

    #initialize the stats
    stats = SynthStats(ap_settings)

    #initialize URN
    stats.urn = 'random'

    # Create the group of buttons
    buttons = scf.create_buttons(ap_settings, screen, stats)

    #initialize the playmode display
    playmode = PlayMode(ap_settings, screen, stats)
    playmode.prep_play_mode()
    playmode.prep_playing_output()

    #initialize the input box
    stats.ip_y = stats.button_height_max * 5
    input_box = InputBox(stats.ip_x, stats.ip_y, stats.ip_w, stats.ip_h)

    # Create the group of piano keys
    piano_keys = scf.create_keys(ap_settings, screen, stats)

    # Initialize the Note Player, create notes if needed,
    nplayer = NotePlayer(ap_settings)
    apf.createNotes(ap_settings, nplayer, stats)

    #start the main loop for the program
    while True:
        #check for events
        scf.check_events(ap_settings, screen, buttons, nplayer, stats,
                         playmode, piano_keys, input_box)

        #redraw the screen
        scf.update_screen(ap_settings, screen, buttons, playmode, piano_keys,
                          input_box)
Example #15
0
background = pygame.image.load(
    "assets/background/futurCity.jpg").convert_alpha()
# background = pygame.transform.scale(background, (width, height))

# importer charger notre bannière
banner = pygame.image.load("assets/home/ship.png").convert_alpha()
banner_rect = banner.get_rect()

# importer charger le bouton pour la partie
play_button = pygame.image.load(
    "assets/home/playNowButton1.png").convert_alpha()
play_button_rect = play_button.get_rect()

input_info = myfont2.render("Entrez votre pseudo", True, (250, 250, 250))

box = InputBox(math.ceil((width - 200) / 2),
               math.ceil((height - title_pos_y) + 32) + 20, 200, 32)

# instance d'avion
game = Game(box, width, height)

# on crée un boucle infini pour que la fenetre apparaisse tout le temps
running = True

# on regle l'image par seconde
clock = pygame.time.Clock()
pygame.mixer.music.load("assets/sounds/retro.ogg")
pygame.mixer.music.set_volume(0.05)
pygame.mixer.music.play(3, 1)
while running:

    clock.tick(FPS)
Example #16
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)
Example #17
0
    def spawn_gains(self):
        elem = []
        for item in ITEMS_POWER:
            elem.append(item)
        my_projectil = numpy.random.choice(elem, 1)[0]
        select = ITEMS_POWER[my_projectil]
        load = pygame.image.load(select["load"])
        spawn_gain = pygame.transform.scale(load, (60, 60))
        self.qte = random.randint(select["min"], select["max"])
        self.name = select["name"]
        self.spawn_gain_rect = spawn_gain.get_rect()
        self.spawn_gain_rect.x = self.rect.x
        self.spawn_gain_rect.y = self.rect.y
        self.all_gains.append(spawn_gain)


if __name__ == '__main__':
    # Attention, __mro__ est un attribut special de classe.
    # Il doit donc etre recupere depuis la classe
    print(Monster.__mro__)
    from game import Game
    from input_box import InputBox
    box = InputBox(200, 100, 200, 32)
    game = Game(box, 600, 700)
    monster_one = Monster(game, 600, 700)
    print(monster_one.ship_image)
    monster = Monster(game, 600, 700, "ship3")
    print(monster.ship_image)
    print(monster.image)
Example #18
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
Example #19
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()
Example #20
0
    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()
Example #21
0
File: main.py Project: refom/glbb
def main():
	pygame.init()

	window = Window((1000, 640))
	bola = Bola((400, 450), 0.5, COLORS.deepskyblue)

	# Font
	FontText.title = os.path.join(os.getcwd(), "data", "font", "Kenney Blocks.ttf")
	FontText.normal = os.path.join(os.getcwd(), "data", "font", "Kenney Mini Square.ttf")
	FontText.update()

	si_teks = FontText.font_semi_normal.render(f"Show info >", False, COLORS.black)
	si_rect = si_teks.get_rect(x=20, y=20)
	show_info = False

	stat_teks = FontText.font_semi_normal.render(f"< Bola stats :", False, COLORS.black)
	stat_rect = stat_teks.get_rect(x=20, y=20)

	custom_vel = InputBox((0, 0), (100, 30), 0, text_color=COLORS.black)
	custom_vel.font = FontText.font_small

	btn_right = Button((0,0), (50,50), COLORS.black)
	btn_left = Button((0,0), (50,50), COLORS.black, left=True)

	while window.run:
		events = pygame.event.get()
		dt = window.clock.tick(120) * 0.001 * window.fps / 1.5
		window.update()

		for event in events:
			if event.type == QUIT:
				pygame.quit()
				sys.exit()
			if event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					pygame.quit()
					sys.exit()
			if event.type == MOUSEBUTTONDOWN:
				if not show_info:
					if event.button == 1 and collision_test(si_rect.x, si_rect.y, si_rect.w, si_rect.h, event.pos):
						show_info = True
				else:
					if event.button == 1 and collision_test(stat_rect.x, stat_rect.y, stat_rect.w, stat_rect.h, event.pos):
						show_info = False

		# Input handle
		custom_vel.pos.x = window.size[0] - 120
		custom_vel.pos.y = (window.size[1]/2) - 100

		btn_right.pos.x = window.size[0] - 60
		btn_right.pos.y = (window.size[1]/2) - 60

		btn_left.pos.x = window.size[0] - 120
		btn_left.pos.y = (window.size[1]/2) - 60

		InputBox.handle_event(events)
		Button.handle_event(events)

		if btn_right.get_click():
			bola.velocity.x = custom_vel.value
		elif btn_left.get_click():
			bola.velocity.x = -custom_vel.value


		# Bola handle
		bola.get_input(events)
		bola.grab()
		bola.update(dt, window)

		# Bola
		bola.render(window.surface)
		if bola.selected:
			bola.render_string(window.surface)

		# Custom Velocity
		custom_vel.render(window.surface)
		btn_right.render(window.surface)
		btn_left.render(window.surface)

		# # Tanah
		# pygame.draw.line(window.surface, COLORS.black, (0, 600), (window.size[0], 600))

		teks = FontText.font_small.render(f"fps = {int(window.clock.get_fps())}", False, COLORS.black)
		window.surface.blit(teks, (window.size[0] - 100, 20))
		teks = FontText.font_small.render(f"Elastis = {bola.can_bounce}", False, COLORS.black)
		window.surface.blit(teks, (20, 610))
		teks = FontText.font_small.render(f"Konstan = {bola.constant}", False, COLORS.black)
		window.surface.blit(teks, (220, 610))
		teks = FontText.font_small.render(f"Dalam box = {bola.in_box}", False, COLORS.black)
		window.surface.blit(teks, (420, 610))
		teks = FontText.font_small.render("Custom", False, COLORS.black)
		window.surface.blit(teks, (custom_vel.pos.x, custom_vel.pos.y - 50))
		teks = FontText.font_small.render("Velocity X", False, COLORS.black)
		window.surface.blit(teks, (custom_vel.pos.x, custom_vel.pos.y - 30))

		# info
		if not show_info:
			window.surface.blit(si_teks, si_rect)
		else:
			window.surface.blit(stat_teks, stat_rect)

			teks = [
				f"radius (r)",
				f"angle degrees",
				f"keliling",
				f"massa",
				f"friction",
				f"vel x",
				f"vel y",
				f"koefisien",
			]
			value = [
				f"= {bola.size/2}",
				f"= {bola.angle_degrees:.2f}",
				f"= {int(bola.keliling)}",
				f"= {int(bola.massa)}",
				f"= {bola.friction:.3f}",
				f"= {bola.velocity.x:.3f}",
				f"= {bola.velocity.y:.3f}",
				f"= {bola.koef:.2f}",
			]

			# Teks
			y = 50
			x = render_teks(window.surface, teks, 20, y, get_x=True)
			x += 40

			# Value
			y = render_teks(window.surface, value, x, y, get_y=True)

			# Keys
			y += 20
			teks = FontText.font_small.render("- Keys :", False, COLORS.black)
			window.surface.blit(teks, (20, y))
			y += 20

			teks = [
				"A/D",
				"W",
				"E/Q",
				"S/C",
				"2/1",
				"F/G",
				"B",
			]
			value = [
				"= bergerak kiri/kanan",
				"= lompat",
				"= Besar/Kecilin bola",
				"= Elastis/Konstan",
				"= naik/turunin friction",
				"= pasang/hapus titik",
				"= dalam/luar box",
			]

			# Teks
			x = render_teks(window.surface, teks, 20, y, True)
			x += 40

			# Value
			render_teks(window.surface, value, x, y)

			
		pygame.display.flip()
Example #22
0
adom = adom_room(screen_main, (20, 40), 40)

# ============== Input ===================================
para_1_boxes_l = []
para_2_boxes_l = []
button_box = None
para_3_boxes_l = []
reset_button_box = None

button_box = ButtonBox(1200, 400)
reset_button_box = ButtonBox(1200, 300, str1='RESET', str2='RESET')

for i in range(len(para_1)):
    box = InputBox(1100,
                   100 + 50 * i,
                   70,
                   32,
                   text=str(para_1[i]),
                   label=para_1_labels[i])
    para_1_boxes_l.append(box)
    box2 = InputBox(1100 + 80,
                    100 + 50 * i,
                    70,
                    32,
                    text=str(para_2[i]),
                    label=para_1_labels[i],
                    draw_label=False)
    para_2_boxes_l.append(box2)

for i in range(len(para_3)):
    box3 = InputBox(1100,
                    350 + 50 * i,
Example #23
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
Example #24
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()
Example #25
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()
    def main_menu(self):
        # clear the GUI
        self.menu.empty()
        self.titles.empty()

        font = {"family": "Arial", "size": int(self.width / 80 * 2)}

        colors = {
            "background": (225, 225, 225),
            "selected": (250, 250, 200),
            "hover": (200, 250, 200),
            "error": (250, 200, 200),
            "text": (75, 75, 75)
        }

        xpos = self.padding
        input_caption_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            self.height / 8 * 3, self.buttonheight)
        input_caption = InputBox(font, colors, input_caption_rect, self.fps, 0)

        xpos += self.height / 8 * 3 + self.padding
        input_value_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            font["size"] * 3, self.buttonheight)
        input_value = InputBox(font, colors, input_value_rect, self.fps, 1)

        button_colors = {
            "background": (205, 205, 205),
            "selected": (200, 200, 150),
            "hover": (150, 200, 150),
            "error": (200, 150, 150),
            "text": (25, 25, 25)
        }

        xpos += font["size"] * 3 + self.padding
        button_submit_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            font["size"] * 3, self.buttonheight)
        button_submit = Button(font, button_colors, button_submit_rect, "Add",
                               "submit_values")

        xpos += font["size"] * 3 + self.padding
        button_save_rect = pygame.Rect(
            xpos, self.height - self.buttonheight - self.padding,
            self.bbarheight, self.buttonheight)
        button_save = Button(font,
                             button_colors,
                             button_save_rect,
                             "Save image",
                             "save_image",
                             id=3)

        self.menu.add(input_caption)
        self.menu.add(input_value)
        self.menu.add(button_submit)
        self.menu.add(button_save)

        self.titles.add(
            Title(font, colors,
                  (self.padding, self.width - self.bbarheight + self.padding),
                  "Caption:"))
        self.titles.add(
            Title(font, colors, (self.height / 8 * 3 + self.padding * 2,
                                 self.width - self.bbarheight + self.padding),
                  "Value:"))
Example #27
0
def main():
    print(getcwd())
    screen = pg.display.set_mode(SCREEN_SIZE)
    screen.fill(BACKGROUND_COLOR)
    pg.display.set_caption("GPR Robot GUI Controller")
    clock = pg.time.Clock()
    run = True

    # first screen elements
    input_x = InputBox(400, 100, 100, 32, text="x = ")
    input_y = InputBox(400, 133, 100, 32, text="y = ")
    manual_button = Button(325, 200, 275, 32, text="Enter Manual Mode")
    user_entry_boxes = [input_x, input_y]
    dimensions = [None, None]
    entries_accepted = [False, False]
    screen_transition_complete = False
    manual_mode = False

    # second screen elements
    info_box = InfoBox(
        int((1 / 16) * SCREEN_SIZE[0]),
        50,
        int((7 / 8) * SCREEN_SIZE[0]),
        32,
        text=INSTRUCTIONS,
    )
    console = Console(
        int((1 / 16) * SCREEN_SIZE[0]),
        info_box.rect.y + info_box.rect.h + 10,
        int((7 / 8) * SCREEN_SIZE[0]),
        32,
    )

    # robot class
    # gpr_robot = Robot()
    gpr_robot = 0
    counter = 0
    while run:
        clock.tick(FRAMERATE)
        counter += 1
        if all(entries_accepted):
            if not screen_transition_complete:
                pg.display.update()
                screen.fill(BACKGROUND_COLOR)
                screen_transition_complete = True

            draw_second_header(screen, dimensions, manual_mode=manual_mode)
            info_box.draw(screen)
        else:
            draw_first_window(screen)

        for event in pg.event.get():  # Check for any events
            if event.type == pg.QUIT:  # Check if user quit the program
                run = False  # Terminate While Loop
            if all(entries_accepted):
                try:
                    auto_move(dimensions[0], dimensions[1])
                except:
                    pass
            else:
                button_clicked = manual_button.handle_event(event)
                if button_clicked:
                    entries_accepted = [True, True]
                    manual_mode = True
                for index, box in enumerate(user_entry_boxes):
                    ret = box.handle_event(event)
                    if ret:
                        try:
                            ret = float(ret)
                            dimensions[index] = ret
                            entries_accepted[index] = True
                            box.accepted_value = True
                            box.color = COLOR_ACCEPTED
                            if index == 0:
                                screen.blit(
                                    CHECK_MARK_IMG,
                                    (box.text_pos_x + 300,
                                     box.text_pos_y - 10),
                                )
                            else:
                                screen.blit(
                                    CHECK_MARK_IMG,
                                    (box.text_pos_x + 300,
                                     box.text_pos_y - 42),
                                )
                        except:
                            box.color = COLOR_REJECTED
                            warning_msg = (
                                f"The value must be a number. User entered: {ret}"
                            )
                            warning_text = MSG_FONT.render(warning_msg, 1, RED)
                            screen.blit(warning_text, (90, 250))
                            warn(warning_msg)
                            dimensions[index] = USER_ENTRY_ERROR_CODE

        if all(entries_accepted):
            keys_pressed = pg.key.get_pressed()
            command = manual_move(gpr_robot, keys_pressed)
            if counter % 2 == 0:
                console.update(command)
                console.draw(screen)
        else:
            draw_dimension_text(screen, dimensions)

            for box in user_entry_boxes:
                box.update()

            for box in user_entry_boxes:
                box.draw(screen)

            manual_button.draw(screen)

        draw_bottom_banner(screen)
        pg.display.flip()

    pg.quit()
Example #28
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)