Exemple #1
0
    def handle(self):

        # socketType refers to whether the socket is a speaker 
        # or listener from the _client's_ point of view.
        socketType = n.receive(self.request)

        if socketType == "speak":
            server.clientIDLock.acquire()
            clientID = server.clientIDCounter
            server.clientIDCounter += 1
            server.clientIDLock.release()

            # Tell the client its ID.
            n.send(self.request, serialize(clientID))

            print(  "[" + self.client_address[0] + " connected as client "
                  + str(clientID) + ".]")
            # Create a queue corresponding to this client.
            server.messages.append(Queue.Queue())

            while True:
                serializedMessage = n.receive(self.request)
                if serializedMessage:
                    message = unserialize(serializedMessage)
                    print (  "[" + message.__class__.__name__ 
                           + ": " + str(message) + "]")
                    assignID(message)
                    server.distributionQueue.put(message)
                    newMessageTree = trees.MessageTree(message)
                    server.baseMessageTree.append(newMessageTree)
                else:
                    break
                
            print "[Client " + str(clientID) + " quit.]"

        else:
            assert socketType[0:6] == "listen"
            clientID = int(unserialize(socketType[6:]))

            n.send(self.request, serialize(server.baseMessageTree))

            # While the client is still listening...
            while n.receive(self.request) == "still here":
                # ...send a message from the queue 
                # corresponding to this client.
                n.send(self.request, serialize(
                    server.messages[clientID].get()
                    ))
Exemple #2
0
def bootClient(SERVER_DETAILS):
    client = Client()
    (client.speakSocket, serializedClientID) = n.openSpeakPort(SERVER_DETAILS)
    # Sleep: fudge so that the sender socket
    # definitely gets opened first.
    # Things WON'T break if two clients connect
    # within 0.1 seconds of each other.
    time.sleep(0.1)
    client.listenSocket = n.openListenPort(SERVER_DETAILS, serializedClientID)
    client.ID = unserialize(serializedClientID)

    # "In" = "in from server"; "Out" = "out to GUI"
    client.messageIn = Queue.Queue()
    client.messageTreeOut = Queue.Queue()

    client.baseMessageTree = unserialize(n.receive(client.listenSocket))
    client.baseMessageTree.message.ID = 0

    client.messageTreeOut.put(client.baseMessageTree)

    speakThread = threading.Thread(target=speak, args=(client.speakSocket, client))
    speakThread.daemon = True
    speakThread.start()

    listenThread = threading.Thread(target=listen, args=(client.listenSocket, client))
    listenThread.daemon = True
    listenThread.start()

    return client
Exemple #3
0
def listen(sock, client):
    while True:
        n.send(sock, "still here")
        newMessage = unserialize(n.receive(sock))
        newMessageTree = trees.MessageTree(newMessage)
        client.baseMessageTree.append(newMessageTree)
        client.messageTreeOut.put(newMessageTree)
Exemple #4
0
def bootClient(SERVER_DETAILS):
    client = Client()
    (client.speakSocket, serializedClientID) = n.openSpeakPort(SERVER_DETAILS)
    # Sleep: fudge so that the sender socket
    # definitely gets opened first.
    # Things WON'T break if two clients connect
    # within 0.1 seconds of each other.
    time.sleep(0.1)
    client.listenSocket = n.openListenPort(SERVER_DETAILS, serializedClientID)
    client.ID = unserialize(serializedClientID)

    # "In" = "in from server"; "Out" = "out to GUI"
    client.messageIn = Queue.Queue()
    client.messageTreeOut = Queue.Queue()

    client.baseMessageTree = unserialize(n.receive(client.listenSocket))
    client.baseMessageTree.message.ID = 0

    client.messageTreeOut.put(client.baseMessageTree)

    speakThread = threading.Thread(target=speak,
                                   args=(client.speakSocket, client))
    speakThread.daemon = True
    speakThread.start()

    listenThread = threading.Thread(target=listen,
                                    args=(client.listenSocket, client))
    listenThread.daemon = True
    listenThread.start()

    return client
Exemple #5
0
def listen(sock, client):
    while True:
        n.send(sock, "still here")
        newMessage = unserialize(n.receive(sock))
        newMessageTree = trees.MessageTree(newMessage)
        client.baseMessageTree.append(newMessageTree)
        client.messageTreeOut.put(newMessageTree)
Exemple #6
0
    def handle(self):

        # socketType refers to whether the socket is a speaker
        # or listener from the _client's_ point of view.
        socketType = n.receive(self.request)

        if socketType == "speak":
            server.clientIDLock.acquire()
            clientID = server.clientIDCounter
            server.clientIDCounter += 1
            server.clientIDLock.release()

            # Tell the client its ID.
            n.send(self.request, serialize(clientID))

            print("[" + self.client_address[0] + " connected as client " +
                  str(clientID) + ".]")
            # Create a queue corresponding to this client.
            server.messages.append(Queue.Queue())

            while True:
                serializedMessage = n.receive(self.request)
                if serializedMessage:
                    message = unserialize(serializedMessage)
                    print("[" + message.__class__.__name__ + ": " +
                          str(message) + "]")
                    assignID(message)
                    server.distributionQueue.put(message)
                    newMessageTree = trees.MessageTree(message)
                    server.baseMessageTree.append(newMessageTree)
                else:
                    break

            print "[Client " + str(clientID) + " quit.]"

        else:
            assert socketType[0:6] == "listen"
            clientID = int(unserialize(socketType[6:]))

            n.send(self.request, serialize(server.baseMessageTree))

            # While the client is still listening...
            while n.receive(self.request) == "still here":
                # ...send a message from the queue
                # corresponding to this client.
                n.send(self.request,
                       serialize(server.messages[clientID].get()))
Exemple #7
0
def main():

    session_collection, first_sample = clear_session_collection()
    last_receive_results = None
    end_program = False
    new_state = dr2specific.GameState.race_not_running
    last_state = dr2specific.GameState.race_not_running
    config = configparser.ConfigParser()
    read_config(config)

    print(intro_text)
    print(commands_hint)

    udp_socket = networking.open_port(config['general']['ip_in'], int(config['general']['port_in']))
    if udp_socket is not None:
        print('Listening on socket {}\n'.format(udp_socket.getsockname()))
    else:
        print('Invalid input socket. Resetting...')
        init_config_input_socket(config)
        write_config(config)
        udp_socket = networking.open_port(config['general']['ip_in'], int(config['general']['port_in']))
        print('Listening on socket {}\n'.format(udp_socket.getsockname()))

    message_queue = queue.Queue()
    input_thread = threading.Thread(target=add_input, args=(message_queue,))
    input_thread.daemon = True
    input_thread.start()
    raw_data, _ = clear_session_collection() if log_raw_data else (None, None)

    if debug:  # start with plots
        # npz_file = np.load('C:/Users/Philipp/Desktop/dr2_logger/m1_ar_3.npz')
        # npz_file = np.load('C:/Users/pherl/Desktop/dr2logger_1_6/races_auto_save/2019-12-26 16_11_35 - Unknown car (0.0, 0.0, 0.0) - Verbundsring - 216.9s.npz')
        npz_file = np.load('C:/Users/pherl/Desktop/2020-03-18 21_22_14 - Peugeot 208 R2 - Kakaristo - 451.7s.npz')
        session_collection = npz_file['arr_0']
        message_queue.put('a')
    else:  # start with recording
        pass

    while not end_program:

        receive_results, datagram = networking.receive(udp_socket)
        # forward_datagram(udp_socket=udp_socket, datagram=datagram, config=config)

        if receive_results is not None:
            if log_raw_data:
                receive_results_raw = np.expand_dims(receive_results, 1)
                if raw_data.size == 0:
                    raw_data = receive_results_raw
                else:
                    raw_data = np.append(session_collection, receive_results_raw, axis=1)

            new_state = dr2specific.get_game_state(receive_results, last_receive_results)
            last_sample = receive_results
            print_current_state(dr2specific.get_game_state_str(
                new_state, last_sample, session_collection.shape[1]))
            has_new_data = dr2specific.accept_new_data(new_state)
            if has_new_data:
                if session_collection.size == 0:
                    session_collection = np.expand_dims(receive_results, 1)
                else:
                    session_collection = np.append(session_collection, np.expand_dims(receive_results, 1), axis=1)
        else:
            new_state = last_state
            has_new_data = False

        while not message_queue.empty():
            command = message_queue.get()

            if command == 'e':
                print('Exit...\n')
                end_program = True
            elif command == 'c':
                print('Cleared {} data points\n'.format(session_collection.shape[1]))
                session_collection, first_sample = clear_session_collection()
                last_receive_results = None
            elif command == 'a':
                print('Plotting {} data points\n'.format(session_collection.shape[1]))
                if debug:
                    plots.plot_main(session_data=session_collection)
                else:
                    try:
                        plots.plot_main(session_data=session_collection)
                    except Exception:
                        print('Error during plot: {}'.format(sys.exc_info()))
            elif command == 's':
                save_run(session_collection, config)
            elif command == 'l':
                loaded_session_collection = load_run(config)
                if loaded_session_collection is not None and loaded_session_collection.size > 0:
                    session_collection = loaded_session_collection
                    last_sample = session_collection[:, -1]
                    print_current_state(dr2specific.get_game_state_str(
                        new_state, last_sample, session_collection.shape[1]))
            elif command == '':
                pass  # just ignore empty inputs
            else:
                print('Unknown command: "{}"'.format(command))
                print(commands_hint + '\n')

        # simply ignore state changes through duplicates
        if new_state == dr2specific.GameState.ignore_package:
            new_state = last_state

        if debug and last_state != new_state:
            print('State changed from {} to {}'.format(last_state, new_state))

        if last_state == dr2specific.GameState.race_running and \
                new_state == dr2specific.GameState.race_not_running:
            print('Race finished. ')
            save_run(session_collection, config, automatic_name=True)

            if log_raw_data:
                save_run(raw_data, config, automatic_name=False)
        elif last_state == dr2specific.GameState.race_not_running and \
                new_state == dr2specific.GameState.race_running:
            print('Race starting')
            if session_collection.shape[1] > 10:  # should only be less than 100 at the first race after startup
                print('Cleared {} data points'.format(session_collection.shape[1]))
            session_collection, first_sample = clear_session_collection()

            # debug, data mining
            max_rpm = receive_results[networking.Fields.max_rpm.value]
            idle_rpm = receive_results[networking.Fields.idle_rpm.value]
            max_gears = receive_results[networking.Fields.max_gears.value]
            car_name = dr2specific.get_car_name(max_rpm, idle_rpm, max_gears)
            if car_name.startswith('Unknown'):
                with open('unknown cars.txt', 'a+') as f:
                    f.write('[{}, {}, {}, \'Unknown car\'],\n'.format(max_rpm, idle_rpm, max_gears))

            track_length = receive_results[networking.Fields.track_length.value]
            pos_z = receive_results[networking.Fields.pos_z.value]
            track_name = dr2specific.get_track_name(track_length, pos_z)
            if track_name.startswith('Unknown'):
                with open('unknown tracks.txt', 'a+') as f:
                    f.write('[{}, {}, \'Unknown track\'],\n'.format(track_length, pos_z))

        last_state = new_state
        if has_new_data:
            last_receive_results = receive_results.copy()

    input_thread.join()
    udp_socket.close()
Exemple #8
0
# stuff to run the game
active = False
game_countdown = -1

# main loop
while True:
    # do socket shit
    read_sockets, _, exception_sockets = select.select(socket_list, [],
                                                       socket_list,
                                                       1 / SERVER_RATE)

    for notified_socket in read_sockets:
        if notified_socket == server_socket:
            client_socket, client_address = server_socket.accept()

            rec = receive(client_socket)
            if rec is False:
                continue
            else:
                username = rec['username']

            socket_list.append(client_socket)
            clients[client_socket] = username
            client_data[client_socket] = []

            print(
                f"{username} connected - {client_address[0]}:{client_address[1]}"
            )
        else:
            rec = receive(notified_socket)
Exemple #9
0
def main():
    username = input("enter username: "******"connected to server {IP}:{PORT}")

    # send username
    send(client_socket, {'username': username})

    server_data = []

    action = None
    placing = False
    active_game = False

    # main loop
    while True:
        # receive things
        try:
            while True:
                rec = receive(client_socket)
                if rec == False:
                    break
                server_data.append(rec)
        except IOError as e:
            if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
                print('reading error', str(e))
                continue
        except Exception as e:
            print('general error', str(e))

        # process server data
        for rec in server_data:
            if 'game_state' in rec.keys():
                game_state = rec['game_state']
                if not active_game:
                    screen, clock, tile_images, tile_lookup, king_images = start_game(
                        WINDOW_W, WINDOW_H)
                    active_game = True
            if 'message' in rec.keys():
                print(rec['message'])

        # all server data processed, clear the queue
        server_data = []

        # do game stuff
        if active_game:
            # check if closed
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            # check if game over
            if game_state['game_over']:
                active_game = False
                pygame.quit()
                action = None
                continue

            # actions
            if 'action' in game_state.keys() and (
                    game_state['action'][0] == "pick"
                    or game_state['action'][0] == 'place'):
                if game_state['action'][0] == "pick":
                    placing = False

                    # see if the mouse is pressed
                    if pygame.mouse.get_pressed()[0]:
                        if not mouse_was_down:
                            # see if you hit a tile todo dont hard code these, do along with better drawing
                            # get the options
                            pick_options = list(game_state['action'][1])
                            for n, tile in enumerate(
                                    game_state['tiles_to_pick']):
                                if tile[1] is None:
                                    pick_options.append(n)

                            mousePos = pygame.mouse.get_pos()

                            for n, tile in enumerate(
                                    game_state['tiles_to_pick']):
                                tile_x = 300 + 600 + 150
                                tile_y = 0 + 50 + n * 75
                                tile_h = 50
                                tile_w = 100
                                if in_rect(mousePos, tile_x, tile_y, tile_w,
                                           tile_h):
                                    if n in pick_options:  # if the tile has not been picked
                                        print(f"picked tile {n+1}")
                                        send(
                                            client_socket, {
                                                'action': game_state['action'],
                                                "resp": n
                                            })
                                        del game_state['action']
                                        break
                            mouse_was_down = True
                    else:
                        mouse_was_down = False

                elif game_state['action'][0] == "place":
                    for tile in game_state['you']['tiles']:
                        if game_state['action'][1] == tile[0]:
                            print('already have this tile!')

                    if not placing:
                        placing = True
                        placing_number = game_state['action'][1]
                        placing_direction = 'W'
                        dragging = False
                        placing_x = 550
                        placing_y = 700

                        if placing_number is None:
                            print(f"tile duplication glitch")
                            send(client_socket, {
                                'action': game_state['action'],
                                'resp': None
                            })
                            placing = False
                            del game_state['action']
                        elif not can_place(game_state['you']['tiles'],
                                           placing_number, tile_lookup):
                            print(f"impossible to place tile, discarding")
                            send(client_socket, {
                                'action': game_state['action'],
                                'resp': None
                            })
                            placing = False
                            del game_state['action']

                    if pygame.mouse.get_pressed()[0]:  # if mouse down
                        mousePos = pygame.mouse.get_pos()
                        if dragging:  # if currently dragging
                            placing_x = mousePos[0] - dragging_offset_x
                            placing_y = mousePos[1] - dragging_offset_y
                        else:
                            # see if we hit it
                            if placing_direction == 'W' or placing_direction == 'E':
                                w = 50 * 2
                                h = 50
                            else:
                                w = 50
                                h = 50 * 2
                            if in_rect(mousePos, placing_x, placing_y, w, h):
                                # setup dragging
                                dragging_offset_x = mousePos[0] - placing_x
                                dragging_offset_y = mousePos[1] - placing_y
                                dragging = True

                    else:
                        # check if we were dragging
                        if dragging:
                            dragging = False
                            # check if we can place it here
                            grid_coords = get_grid_coords(
                                placing_x + 25, placing_y + 25, 500, 500, 350,
                                150)
                            grid_x = grid_coords[0]
                            grid_y = grid_coords[1]
                            if placing_direction == 'W':
                                pass
                            elif placing_direction == 'N':
                                pass
                            elif placing_direction == 'E':
                                grid_x += 1
                            elif placing_direction == 'S':
                                grid_y += 1

                            if test_new_tile(game_state['you']['tiles'], [
                                    placing_number, grid_x, grid_y,
                                    placing_direction
                            ], tile_lookup):
                                game_state['you']['tiles'].append([
                                    placing_number, grid_x, grid_y,
                                    placing_direction
                                ])
                                send(
                                    client_socket, {
                                        'action':
                                        game_state['action'],
                                        'resp': [
                                            placing_number, grid_x, grid_y,
                                            placing_direction
                                        ]
                                    })
                                placing = False

                                # remove actoin
                                del game_state['action']

                        # check for rotation
                        if pygame.key.get_pressed()[pygame.K_a]:

                            if rotation is None:
                                rotation = 'l'
                            else:
                                rotation = 'held'
                        elif pygame.key.get_pressed()[pygame.K_d]:
                            if rotation is None:
                                rotation = 'r'
                            else:
                                rotation = 'held'
                        elif pygame.key.get_pressed()[pygame.K_LEFT]:
                            if rotation is None:
                                rotation = 'l'
                            else:
                                rotation = 'held'
                        elif pygame.key.get_pressed()[pygame.K_RIGHT]:
                            if rotation is None:
                                rotation = 'r'
                            else:
                                rotation = 'held'
                        else:
                            rotation = None

                        if rotation is not None and rotation != 'held':  # if there is a key down
                            if rotation == 'l':
                                if placing_direction == 'N':
                                    placing_direction = 'W'
                                elif placing_direction == 'W':
                                    placing_direction = 'S'
                                elif placing_direction == 'S':
                                    placing_direction = 'E'
                                elif placing_direction == 'E':
                                    placing_direction = 'N'
                            elif rotation == 'r':
                                if placing_direction == 'N':
                                    placing_direction = 'E'
                                elif placing_direction == 'E':
                                    placing_direction = 'S'
                                elif placing_direction == 'S':
                                    placing_direction = 'W'
                                elif placing_direction == 'W':
                                    placing_direction = 'N'

                else:
                    placing = False

            # draw
            screen.fill((255, 255, 255))

            # draw your board
            draw_board(screen, 500, 500, 350, 150, game_state['you']['tiles'],
                       tile_images, 2, game_state['you']['color'], king_images)

            # draw other boards
            for n, other in enumerate(game_state['others']):
                draw_board(screen, 200, 200, 50, 50 + 250 * n, other['tiles'],
                           tile_images, 1, other['color'], king_images)

            # draw tiles
            # to pick
            for n, tile in enumerate(game_state['tiles_to_pick']):
                if tile[0] is not None:
                    draw_tile(screen, tile[0], 300 + 600 + 150,
                              0 + 50 + n * 75, 50, 'W', tile_images)
                if tile[1] is not None:
                    draw_king(screen, tile[1], 300 + 600 + 50, 0 + 50 + n * 75,
                              50, king_images)
            # picked
            for n, tile in enumerate(game_state['tiles_picked']):
                if tile[0] is not None:
                    draw_tile(screen, tile[0], 300 + 600 + 150,
                              400 + 50 + n * 75, 50, 'W', tile_images)
                if tile[1] is not None:
                    draw_king(screen, tile[1], 300 + 600 + 50,
                              400 + 50 + n * 75, 50, king_images)

            # draw placing tile
            if placing:
                draw_tile(screen, placing_number, placing_x, placing_y, 50,
                          placing_direction, tile_images)

            # update display
            pygame.display.update()

            # limit framerate
            clock.tick(FRAMERATE)
Exemple #10
0
screen = pygame.display.set_mode((400, 300))

quit = False
networking.join('127.0.0.1')
x = 0
y = 0

while not quit:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit = True

    pressed = pygame.key.get_pressed()
    networking.send_input([
        0, 0, 0, 0, pressed[pygame.K_w], pressed[pygame.K_s],
        pressed[pygame.K_a], pressed[pygame.K_d]
    ])
    recv = networking.receive()
    print(recv)
    if recv != 0:
        x = recv[0]
        y = recv[1]
        pygame.draw.rect(screen, (0, 0, 255), pygame.Rect(x, y, 10, 10))
        for i in range(recv[2]):
            pygame.draw.rect(
                screen, (255, 0, 0),
                pygame.Rect(recv[3 + i * 2], recv[4 + i * 2], 10, 10))

    pygame.display.flip()