Example #1
0
    def start_game(
        self, board, live_id_nums
    ):  # take in live_id_nums ????????????????????????????????????????????????????????????????????????
        # def start_game(self, board):  # take in live_id_nums ????????????????????????????????????????????????????????????????????????

        # live_id_nums = []
        # live_id_nums = server.select_Players_From_Connected_Clients()
        print("sending Welcome messgae to all players")
        print("Adding tiles to each player's hand")
        for i in self.current_players:
            print(
                "----------------------------------------------- HERE 1 ??? ----------------------------------------------- "
            )
            # live_id_nums.append(i.idnum)
            currentConnection = i.connection
            print(
                "----------------------------------------------- HERE 2 ??? ----------------------------------------------- "
            )
            currentConnection.send(tiles.MessageWelcome(i.idnum).pack())
            print(
                "----------------------------------------------- HERE 3 ??? ----------------------------------------------- "
            )
            currentConnection.send(tiles.MessageGameStart().pack())

            #step 4

            for _ in range(tiles.HAND_SIZE):
                print(
                    "----------------------------------------------- HERE 4 ??? ----------------------------------------------- "
                )
                # print("THREE")
                tileid = tiles.get_random_tileid()
                print(
                    "----------------------------------------------- HERE 5 ??? ----------------------------------------------- "
                )
                currentConnection.send(
                    tiles.MessageAddTileToHand(tileid).pack())

            for j in self.all_connected_clients:
                print(
                    "----------------------------------------------- HERE 6 ??? ----------------------------------------------- "
                )
                print("FOUR")
                print(i.name)
                j.connection.send(
                    tiles.MessagePlayerJoined(i.name, i.idnum).pack())

        # for j in self.spectators:
        #     print("FOUR")
        #     print(i.name)
        #     j.connection.send(tiles.MessagePlayerJoined(i.name, i.idnum).pack())

        # started = 1
        self.game_started = True
        #main game loop
        buffer = bytearray()

        while len(live_id_nums) > 1:  #step 5
            # print("start")
            current = self.turn_Queue.get()
            current_idnum = current.idnum
            # print(current_idnum)
            current_connection = current.connection
            current_address = current.client_address
            for i in self.all_connected_clients:
                #step 5 a
                i.connection.send(
                    tiles.MessagePlayerTurn(current_idnum).pack())
            #step 5 b
            chunk = current_connection.recv(4096)

            if not chunk:
                print('client {} disconnected'.format(current_address))
                return

            buffer.extend(chunk)

            #step 5 c
            msg, consumed = tiles.read_message_from_bytearray(buffer)
            if not consumed:
                break

            buffer = buffer[consumed:]

            print('received message {}'.format(msg))

            #step 5 c all
            #can probably combine
            if isinstance(msg, tiles.MessagePlaceTile):

                self.game_message_history.append(msg)

                if board.set_tile(msg.x, msg.y, msg.tileid, msg.rotation,
                                  msg.idnum):
                    for i in self.all_connected_clients:
                        i.connection.send(msg.pack())
                    positionupdates, eliminated = board.do_player_movement(
                        live_id_nums)

                    for msg in positionupdates:

                        self.game_message_history.append(msg)

                        for i in self.all_connected_clients:
                            i.connection.send(msg.pack())

                    for e in eliminated:
                        live_id_nums.remove(e)
                        print("liveid len is" + str(len(live_id_nums)))
                        for i in self.all_connected_clients:
                            i.connection.send(
                                tiles.MessagePlayerEliminated(e).pack())
                        if e == current_idnum:
                            print("You lose!")
                            break
                            #return # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    #                     if current_idnum in eliminated:
    #                         for i in self.all_connected_clients:
    #                             i.connection.send(tiles.MessagePlayerEliminated(current_idnum).pack())
    #                         live_id_nums.remove(current_idnum)
    #                         #eliminated
    #                         print("You lose!")
    #                         return

                    tileid = tiles.get_random_tileid()
                    current_connection.send(
                        tiles.MessageAddTileToHand(tileid).pack())

                self.turn_Queue.put(current)

            elif isinstance(msg, tiles.MessageMoveToken):
                if not board.have_player_position(msg.idnum):
                    if board.set_player_start_position(msg.idnum, msg.x, msg.y,
                                                       msg.position):

                        positionupdates, eliminated = board.do_player_movement(
                            live_id_nums)
                        for msg in positionupdates:
                            for i in self.all_connected_clients:
                                i.connection.send(msg.pack())
                        for e in eliminated:
                            live_id_nums.remove(e)
                            print("liveid len is" + str(len(live_id_nums)))
                            for i in self.all_connected_clients:
                                i.connection.send(
                                    tiles.MessagePlayerEliminated(e).pack())
                            if e == current_idnum:
                                print("You lose!")
                                break
                                #return

                    self.turn_Queue.put(current)

        print("End of start_game()")
        # server.restart()
        self.game_started == False
        return
Example #2
0
    def client_handler(self, connection, address):
        print(f"[NEW CONNECTION] {address} connected to the server.")

        host, port = address
        name = '{}:{}'.format(host, port)

        idnum = 0
        live_idnums = [idnum]

        connection.send(tiles.MessageWelcome(idnum).pack())
        connection.send(tiles.MessagePlayerJoined(name, idnum).pack())
        connection.send(tiles.MessageGameStart().pack())

        for _ in range(tiles.HAND_SIZE):
            tileid = tiles.get_random_tileid()
            connection.send(tiles.MessageAddTileToHand(tileid).pack())

        connection.send(tiles.MessagePlayerTurn(idnum).pack())

        board = tiles.Board()

        buffer = bytearray()

        while True:
            # with lock:
            # connection, msg = self.task_queue.get() # added

            chunk = connection.recv(4096)
            if not chunk:
                print('client {} disconnected'.format(address))
                return

            buffer.extend(chunk)

            while True:
                msg, consumed = tiles.read_message_from_bytearray(buffer)
                if not consumed:
                    break

                buffer = buffer[consumed:]

                print('received message {}'.format(msg))

                # sent by the player to put a tile onto the board (in all turns except
                # their second)
                if isinstance(msg, tiles.MessagePlaceTile):
                    if board.set_tile(msg.x, msg.y, msg.tileid, msg.rotation,
                                      msg.idnum):
                        # notify client that placement was successful
                        connection.send(msg.pack())

                        # check for token movement
                        positionupdates, eliminated = board.do_player_movement(
                            live_idnums)

                        for msg in positionupdates:
                            connection.send(msg.pack())

                        if idnum in eliminated:
                            connection.send(
                                tiles.MessagePlayerEliminated(idnum).pack())
                            return

                        # pickup a new tile
                        tileid = tiles.get_random_tileid()
                        connection.send(
                            tiles.MessageAddTileToHand(tileid).pack())

                        # start next turn
                        connection.send(tiles.MessagePlayerTurn(idnum).pack())

                # sent by the player in the second turn, to choose their token's
                # starting path
                elif isinstance(msg, tiles.MessageMoveToken):
                    if not board.have_player_position(msg.idnum):
                        if board.set_player_start_position(
                                msg.idnum, msg.x, msg.y, msg.position):
                            # check for token movement
                            positionupdates, eliminated = board.do_player_movement(
                                live_idnums)

                            for msg in positionupdates:
                                connection.send(msg.pack())

                            if idnum in eliminated:
                                connection.send(
                                    tiles.MessagePlayerEliminated(
                                        idnum).pack())
                                return

                            # start next turn
                            connection.send(
                                tiles.MessagePlayerTurn(idnum).pack())
                # added:
                self.task_queue.task_done()
Example #3
0
    def client_handler(self, lock, connection, address):
        # def client_handler(self, connection, address):
        # global turn_Queue
        host, port = address
        name = '{}:{}'.format(host, port)
        print(f"{name} has joined")

        idnum = 0
        live_idnums = [idnum]

        with lock:
            connection.send(tiles.MessageWelcome(idnum).pack())
            connection.send(tiles.MessagePlayerJoined(name, idnum).pack())
            connection.send(tiles.MessageGameStart().pack())

            # get a client from the queue:
            # client_socket_id = turn_Queue.get() # is this now idnum???????????????????????????????????

            for _ in range(tiles.HAND_SIZE):
                tileid = tiles.get_random_tileid()
                connection.send(tiles.MessageAddTileToHand(tileid).pack())

            connection.send(tiles.MessagePlayerTurn(idnum).pack())
            board = tiles.Board()
            buffer = bytearray()

            # Don't do the following unless >= 2 clients
            # if num_live_id_nums > 1:
            print("Now the game can START!")

            while True:
                chunk = connection.recv(4096)
                if not chunk:
                    print('client {} disconnected'.format(address))
                    return

                buffer.extend(chunk)

                while True:
                    # with lock:
                    # connection, msg = self.task_queue.get() # added
                    msg, consumed = tiles.read_message_from_bytearray(buffer)
                    if not consumed:
                        break

                    buffer = buffer[consumed:]

                    print('received message {}'.format(msg))

                    # sent by the player to put a tile onto the board (in all turns except
                    # their second)
                    if isinstance(msg, tiles.MessagePlaceTile):
                        if board.set_tile(msg.x, msg.y, msg.tileid,
                                          msg.rotation, msg.idnum):
                            # notify client that placement was successful
                            connection.send(msg.pack())

                            # check for token movement
                            positionupdates, eliminated = board.do_player_movement(
                                live_idnums)

                            for msg in positionupdates:
                                connection.send(msg.pack())

                            if idnum in eliminated:
                                connection.send(
                                    tiles.MessagePlayerEliminated(
                                        idnum).pack())
                                return

                            # pickup a new tile
                            tileid = tiles.get_random_tileid()
                            connection.send(
                                tiles.MessageAddTileToHand(tileid).pack())

                            # start next turn
                            connection.send(
                                tiles.MessagePlayerTurn(idnum).pack())

                    # sent by the player in the second turn, to choose their token's
                    # starting path
                    elif isinstance(msg, tiles.MessageMoveToken):
                        if not board.have_player_position(msg.idnum):
                            if board.set_player_start_position(
                                    msg.idnum, msg.x, msg.y, msg.position):
                                # check for token movement
                                positionupdates, eliminated = board.do_player_movement(
                                    live_idnums)

                                for msg in positionupdates:
                                    connection.send(msg.pack())

                                if idnum in eliminated:
                                    connection.send(
                                        tiles.MessagePlayerEliminated(
                                            idnum).pack())
                                    return

                                # start next turn
                                connection.send(
                                    tiles.MessagePlayerTurn(idnum).pack())
Example #4
0
    def gameStart(self, board, liveIdNums):

        global allClients
        global currentPlayers
        global moves
        global listening
        global started

        #Initializes all current players sends them welcome and their cards
        #Also informs all clients about the current players
        for i in currentPlayers:
            currentConnection = i.connection
            currentConnection.send(tiles.MessageWelcome(i.idnum).pack())

            for _ in range(tiles.HAND_SIZE):
                tileid = tiles.get_random_tileid()
                currentConnection.send(
                    tiles.MessageAddTileToHand(tileid).pack())

            for j in allClients:
                j.connection.send(
                    tiles.MessagePlayerJoined(i.name, i.idnum).pack())

        buffer = bytearray()

        #Loop used to handle the game
        while len(liveIdNums) > 1:

            current = self.turnQueue.get()
            currentIDnum = current.idnum
            #This if statement skips a players turn if they were eliminated
            if currentIDnum not in liveIdNums:
                continue

            currentConnection = current.connection
            currentAddress = current.clientAddress

            #Sends all players the current players turn start
            for i in allClients:
                i.connection.send(tiles.MessagePlayerTurn(currentIDnum).pack())

            chunk = currentConnection.recv(4096)

            if not chunk:
                print('#client {} disconnected'.format(address))
                continue

            buffer.extend(chunk)

            msg, consumed = tiles.read_message_from_bytearray(buffer)
            if not consumed:
                break

            buffer = buffer[consumed:]

            print('received message {}'.format(msg))

            #The two if statements to tell what type of move it was
            if isinstance(msg, tiles.MessagePlaceTile):

                #Moves is an array storing the moves in order to give to spectators
                moves.append(msg)

                if board.set_tile(msg.x, msg.y, msg.tileid, msg.rotation,
                                  msg.idnum):

                    for i in allClients:
                        i.connection.send(msg.pack())

                    positionupdates, eliminated = board.do_player_movement(
                        liveIdNums)

                    for msg in positionupdates:
                        moves.append(msg)
                        for i in allClients:
                            i.connection.send(msg.pack())

                    for e in eliminated:
                        liveIdNums.remove(e)
                        for i in allClients:
                            i.connection.send(
                                tiles.MessagePlayerEliminated(e).pack())

                    tileid = tiles.get_random_tileid()
                    currentConnection.send(
                        tiles.MessageAddTileToHand(tileid).pack())

                self.turnQueue.put(current)

            #This if statement if a player choices his start position
            elif isinstance(msg, tiles.MessageMoveToken):

                if not board.have_player_position(msg.idnum):

                    if board.set_player_start_position(msg.idnum, msg.x, msg.y,
                                                       msg.position):

                        positionupdates, eliminated = board.do_player_movement(
                            liveIdNums)

                        for msg in positionupdates:
                            moves.append(msg)
                            for i in allClients:
                                i.connection.send(msg.pack())

                        for e in eliminated:
                            liveIdNums.remove(e)
                            for i in allClients:
                                i.connection.send(
                                    tiles.MessagePlayerEliminated(e).pack())

                    self.turnQueue.put(current)
        started = 0
        #The game is over and thus started isn't 1
        return
Example #5
0
    def gameStart(self,board):
        global all_clients
        global current_players
        global started
        global started
        live_id_nums = []
        for i in current_players:
            live_id_nums.append(i.idnum)
            currentConnection = i.connection
            currentConnection.send(tiles.MessageWelcome(i.idnum).pack())

            #step 4

            for _ in range(tiles.HAND_SIZE):
                tileid = tiles.get_random_tileid()
                currentConnection.send(tiles.MessageAddTileToHand(tileid).pack())

            for j in all_clients:
                print(i.name)
                j.connection.send(tiles.MessagePlayerJoined(i.name,i.idnum).pack())
        started = 1
        #main game loop
        buffer = bytearray()

        while len(live_id_nums)>1: #step 5
            print("start")
            current = self.turn_Queue.get()
            current_idnum = current.idnum
            print(current_idnum)
            current_connection = current.connection
            current_address = current.client_address
            print("here")
            for i in all_clients:
                #step 5 a
                i.connection.send(tiles.MessagePlayerTurn(current_idnum).pack())
            print("here1")

            #step 5 b
            chunk = current_connection.recv(4096)

            if not chunk:
              print('client {} disconnected'.format(address))
              return


            buffer.extend(chunk)

            #step 5 c
            msg, consumed = tiles.read_message_from_bytearray(buffer)
            if not consumed:
                break

            buffer = buffer[consumed:]

            print('received message {}'.format(msg))

            #step 5 c all
            #can probably combine
            if isinstance(msg, tiles.MessagePlaceTile):
                if board.set_tile(msg.x, msg.y, msg.tileid, msg.rotation, msg.idnum):
                    for i in all_clients:
                        i.connection.send(msg.pack())
                start_game    positionupdates, eliminated = board.do_player_movement(live_id_nums)

                    for msg in positionupdates:
                        for i in all_clients:
                            i.connection.send(msg.pack())
                    print("gothere")
                    for e in eliminated:
                        live_id_nums.remove(e)
                        live_id_nums.remove(e)
                        print("liveid len is"+str(len(live_id_nums)))
                        for i in self.all_connected_clients:
                            i.connection.send(tiles.MessagePlayerEliminated(e).pack())
                        if e == current_idnum:
                            print("You lose!")
                            break
                            #return

#                     if current_idnum in eliminated:
#                         for i in self.all_connected_clients:
#                             i.connection.send(tiles.MessagePlayerEliminated(current_idnum).pack())
#                         live_id_nums.remove(current_idnum)
#                         #eliminated
#                         print("You lose!")
#                         return

                    tileid = tiles.get_random_tileid()
                    current_connection.send(tiles.MessageAddTileToHand(tileid).pack())

                self.turn_Queue.put(current)

            elif isinstance(msg, tiles.MessageMoveToken):
                if not board.have_player_position(msg.idnum):
                    if board.set_player_start_position(msg.idnum, msg.x, msg.y, msg.position):

                        positionupdates, eliminated = board.do_player_movement(live_id_nums)
                        for msg in positionupdates:
                            for i in self.all_connected_clients:
                                i.connection.send(msg.pack())
                        for e in eliminated:
                            live_id_nums.remove(e)
                            print("liveid len is"+str(len(live_id_nums)))
                            for i in self.all_connected_clients:
                                i.connection.send(tiles.MessagePlayerEliminated(e).pack())
                            if e == current_idnum:
                                print("You lose!")
                                break
                                #return

                    self.turn_Queue.put(current)
Example #6
0
def communication_thread(sock):
    buffer = bytearray()

    while True:
        try:
            chunk = sock.recv(4096)
            if chunk:
                # Read a chunk from the socket, and add it to the end of our buffer
                # (in case we had a partial message in the buffer from a previous
                # chunk, and we need the new chunk to complete it)
                buffer.extend(chunk)

                # Unpack as many messages as we can from the buffer.
                while True:
                    msg, consumed = tiles.read_message_from_bytearray(buffer)

                    if consumed:
                        buffer = buffer[consumed:]

                        if isinstance(msg, tiles.MessageWelcome):
                            print('Welcome!')
                            with app.infolock:
                                app.idnum = msg.idnum
                                app.playernames[app.idnum] = 'Me!'

                        elif isinstance(msg, tiles.MessagePlayerJoined):
                            print('Player {} joined, id {}'.format(
                                msg.name, msg.idnum))
                            with app.infolock:
                                app.playernames[msg.idnum] = msg.name

                        elif isinstance(msg, tiles.MessagePlayerLeft):
                            print('Player id {} left'.format(msg.idnum))
                            with app.infolock:
                                if msg.idnum in app.playernames:
                                    del app.playernames[msg.idnum]
                                else:
                                    print(
                                        "...I didn't know they were a player!")

                        elif isinstance(msg, tiles.MessageCountdown):
                            print('Countdown starting...')

                        elif isinstance(msg, tiles.MessageGameStart):
                            print('Game starting...')
                            reset_game_state()

                        elif isinstance(msg, tiles.MessageAddTileToHand):
                            print('Add tile {} to hand'.format(msg.tileid))
                            tileid = msg.tileid

                            if tileid < 0 or tileid >= len(tiles.ALL_TILES):
                                raise RuntimeError(
                                    'Unknown tile index {}'.format(tileid))

                            add_tile_to_hand(tileid)

                        elif isinstance(msg, tiles.MessagePlayerTurn):
                            print('Player turn: {}'.format(msg))

                            with app.infolock:
                                if msg.idnum not in app.playernames:
                                    raise RuntimeError(
                                        'Unknown playerid {}'.format(
                                            msg.idnum))

                            set_player_turn(msg.idnum)

                        elif isinstance(msg, tiles.MessagePlaceTile):
                            print('Place tile: {}'.format(msg))

                            with app.infolock:
                                if msg.idnum not in app.playernames:
                                    raise RuntimeError(
                                        'Unknown playerid {}'.format(
                                            msg.idnum))

                            tile_placed(msg)

                        elif isinstance(msg, tiles.MessageMoveToken):
                            print('Move token: {}'.format(msg))

                            with app.infolock:
                                if msg.idnum not in app.playernames:
                                    raise RuntimeError(
                                        'Unknown playerid {}'.format(
                                            msg.idnum))

                            token_moved(msg)

                        elif isinstance(msg, tiles.MessagePlayerEliminated):
                            print('Player eliminated: {}'.format(msg))

                            with app.infolock:
                                if msg.idnum not in app.playernames:
                                    raise RuntimeError(
                                        'Unknown playerid {}'.format(
                                            msg.idnum))

                            set_player_eliminated(msg.idnum)

                        else:
                            print('Unknown message: {}'.format(msg))
                    else:
                        break
            else:
                break
        except Exception as e:
            print('Error: {}'.format(e))
            break

    print('Server closed connection')

    if not exited:
        app.event_generate('<<CloseConnection>>')