Ejemplo n.º 1
0
 def __client_thread(self, player: Player) -> None:
     """Thread for handling a single client"""
     player.send('id_confirm', str(player.id))
     opponent = None
     # looking for opponent
     while not opponent:
         opponent = self.__search_opponent(player)
         if opponent is None:
             time.sleep(1)
             # if player is no more waiting finish this loop
             if player not in self.waiting_players:
                 player = None
                 break
             continue
         # removing player and his opponent from the waiting list
         self.waiting_players.remove(player)
         self.waiting_players.remove(opponent)
         break
     if player:
         # starting a new game
         new_game = Game(self.logger, player, opponent)
         try:
             new_game.start()
         except Exception as e:
             self.logger.error('Game {} vs {} finished by error'.format(
                 player.id, opponent.id))
Ejemplo n.º 2
0
    def add_player(self,
                   uid,
                   deck_id=None,
                   ai_deck_id=None,
                   inspector=False,
                   websocket=None):
        if uid == "ai":
            player = AIPlayer(game=self, is_ai=True, ai_deck_id=ai_deck_id)
        else:
            db_player = Player.objects.get(pk=uid)
            player = db_player.to_virtual(game=self)
            player.websocket = websocket
            player.inspector = inspector

            player.deck = Deck(player)
            if deck_id:
                deck = db_player.user.decks.get(pk=deck_id)
            else:
                deck = db_player.first_deck

            for db_card in deck.get_cards(randomize=True):
                card = db_card.to_virtual(player)
                player.deck.add(card)

            player.hand = Hand(player)
            player.ground = Ground(player)
            player.graveyard = Graveyard(player)
            player.turn = Turn(player)
            if inspector:
                player.ai = AI(player)
        self.players.append(player)
Ejemplo n.º 3
0
    def execute(self, username, args, admin):
        if not self.authorise(admin):
            return self.not_auth_message
        if len(args) < 2:
            return "Missing argument (username)"

        self.server.write_all_players()
        requested_username = "******".join(args[1:])

        player = self.server.get_player(requested_username)
        if player:
            now = datetime.datetime.now()
            elapsed_time = now - player.session_start
            session_time = elapsed_time.total_seconds()
        else:
            session_time = 0
            player = Player(requested_username, "no-perk")
            self.server.database.load_player(player)

        time = seconds_to_hhmmss(player.total_time + session_time)
        message = "Stats for {}:\n".format(player.username) +\
                  "Total play time: {} ({} sessions)\n"\
                      .format(time, player.total_logins) +\
                  "Total deaths: {}\n".format(player.total_deaths) +\
                  "Total kills: {}\n".format(millify(player.total_kills)) +\
                  "Total dosh earned: {}\n"\
                      .format(millify(player.total_dosh)) +\
                  "Dosh this game: {}".format(millify(player.game_dosh))

        return message
Ejemplo n.º 4
0
    def auth(self, message, address):
        if self.connections.get(address).get('player') is not None:
            return
        serializer = AuthSerializer(data=message)
        if not serializer.is_valid():
            self.send_error(address, serializer.errors)
            return

        state, error = yield defer_to_thread(PlayerState.objects.auth,
                                             serializer.data['name'], address)
        if not state:
            self.send(RESPONSE_AUTH_FAILURE, data=error)
            return

        logged_players = yield defer_to_thread(get_logged_players)
        if state.key in logged_players:
            self.send(RESPONSE_PLAYER_ALREADY_LOGGED,
                      data=serializer.data['name'])

        yield defer_to_thread(add_logged_player, state.key)

        self.connections[address]['player'] = Player(self, state)

        serializer = SendAuthSerializer(state)

        self.send(address, RESPONSE_AUTH_PLAYER, data=serializer.data)
        yield self.game_service.matchmake(self.connections[address]['player'])
Ejemplo n.º 5
0
async def register(websocket):
    """Associates socket with a particular user"""

    PLAYERS[websocket] = Player()
    print(PLAYERS)

    await notify_players()
Ejemplo n.º 6
0
    def add_player(self, username):
        if self.players.has_key(username):
            raise LogicException(
                "There is already someone in this game named {}".format(
                    username))

        if len(self.players.values()) >= self.max_players:
            raise LogicException("Maximum number of players reached!")
        player = Player(username)
        self.players[username] = player
        self.trigger_field_change()
Ejemplo n.º 7
0
    def event_player_join(self, player):
        if player.username not in self.rejects:
            identity = self.web_admin.get_player_identity(player.username)
        else:
            return

        # Reject unidentifiable players
        if not identity['steam_id']:
            debug("Rejected player: {}".format(player.username))
            self.rejects.append(player.username)
            return

        new_player = Player(player.username, player.perk)
        new_player.kills = player.kills
        new_player.dosh = player.dosh

        new_player.ip = identity['ip']
        new_player.country = identity['country']
        new_player.country_code = identity['country_code']
        new_player.steam_id = identity['steam_id']
        new_player.player_key = identity['player_key']

        self.database.load_player(new_player)
        new_player.sessions += 1

        self.players.append(new_player)

        if DEBUG:
            message = _("Player {} ({}) joined {} from {}").format(
                new_player.username, new_player.steam_id, self.name,
                new_player.country)
        else:
            message = _("Player {} joined {} from {}") \
                .format(new_player.username, self.name, new_player.country)

        print(
            colored(
                message.encode("utf-8").decode(sys.stdout.encoding), 'cyan'))
        info("{} (SteamID: {})".format(message, new_player.steam_id),
             display=False)
        self.web_admin.chat.handle_message(
            "internal_command", "!player_join " + new_player.username,
            USER_TYPE_INTERNAL)
Ejemplo n.º 8
0
    def __handle_clients(self) -> None:
        """Accepting client connections and starting client threads"""
        while True:
            connection, client_address = self.server_socket.accept()
            self.logger.info(str(client_address) + ' connected')
            connection = self.__get_ssl_socket(connection)

            # creating player and adding him to waiting list
            new_player = Player(connection, self.logger, self.player_count)
            self.player_count += 1
            self.waiting_players.append(new_player)

            threading.Thread(target=self.__client_thread,
                             args=(new_player, )).start()
Ejemplo n.º 9
0
    async def accept_players(self, stream):
        """ Accepts players and puts them into self.players once
        they are ready for the game loop """
        log.info("New connection")

        player = Player(net.JSONStream(stream))

        try:
            log.debug("Waiting for player name")
            await player.get_username()
        except net.ConnectionClosed:
            log.info(f"{player} connection closed")
        except Exception as e:
            log.exception("Initiater crashed")
        else:
            await self.initiate_player(player)
Ejemplo n.º 10
0
    def event_player_join(self, player):
        identity = self.web_admin.get_player_identity(player.username)

        new_player = Player(player.username, player.perk)
        new_player.kills = player.kills
        new_player.dosh = player.dosh

        new_player.ip = identity['ip']
        new_player.country = identity['country']
        new_player.country_code = identity['country_code']
        new_player.steam_id = identity['steam_id']
        new_player.player_key = identity['player_key']

        self.database.load_player(new_player)
        new_player.sessions += 1

        self.players.append(new_player)
        message = "Player {} joined {} from {}" \
            .format(new_player.username, self.name, new_player.country)
        print(colored(message, 'cyan'))
        self.web_admin.chat.handle_message(
            "internal_command", "!player_join " + new_player.username,
            USER_TYPE_INTERNAL)
Ejemplo n.º 11
0
    def execute(self, username, args, user_flags):
        args, err = self.parse_args(username, args, user_flags)
        if err:
            return err
        elif args.help:
            return self.format_response(self.help_text, args)

        self.server.write_all_players()

        if args.username:
            username = "******".join(args.username)

        print(username)

        player = self.server.get_player_by_username(username)
        if player:
            # TODO: Move this ...
            now = time.time()
            elapsed_time = now - player.session_start
        else:
            elapsed_time = 0
            player = Player(username, "no-perk")
            self.server.database.load_player(player)

        # ... And this
        fmt_time = seconds_to_hhmmss(player.total_time + elapsed_time)

        pos_kills = self.server.database.rank_kills(player.steam_id) or 0
        pos_dosh = self.server.database.rank_dosh(player.steam_id) or 0
        # todo Add pos_time to output
        # pos_time = self.server.database.rank_time(player.steam_id) or 0

        message = "Stats for {}:\n" \
            "Total play time: {} ({} sessions)\n" \
            "Total deaths: {}\n" \
            "Total kills: {} (rank #{}) \n" \
            "Total dosh earned: £{} (rank #{})\n" \
            "Dosh this game: {}".format(
                player.username, fmt_time, player.sessions,
                player.total_deaths, millify(player.total_kills), pos_kills,
                millify(player.total_dosh), pos_dosh, millify(player.game_dosh)
            )

        return self.format_response(message, args)
Ejemplo n.º 12
0
    def register(self, name):
        players = self.players

        id = -1
        for i in range(len(players)):
            if players[i] == None:
                id = i
                break

        if id == -1:
            return (Constants.RESPONSE_FAILURE, "Too many players registered")

        pos = self.startingPos[id]
        rot = self.startingRot[id]
        player = Player(name, pos, rot)

        players[id] = player

        return (Constants.RESPONSE_SUCCESS, id)
    def connection_made(self, transport):
        self.transport = transport
        self.ipAddress = transport.get_extra_info('peername')[0]

        n = self.server.dos.new(self.ipAddress)

        if n == 0:
            self.isDoS = True
        if n == 1 or n == 2:
            self.isDoS = True
            self.close_connection()
        else:
            self.server.clients.append(self)

            self.parse = ParsePackets(self.server.users)
            self.player = Player(self.server, self)

            self.geoIP = GeoIP(self)

            self.lastDummyTime = self.server.getTime()
Ejemplo n.º 14
0
    def _handle_game_join_packet(self, packet: GameJoinPacket) -> None:
        self.send_game_room(packet)
        print("HANDLING GAME JOIN")

        if self.players.get(packet.player_id):
            if self.should_force_start_game():
                self.initialize_level()
            return

        for player_id, player in self.players.items():
            self.send_player(
                GameJoinPacket(player_id, self.game_id, player.get_name(),
                               player.get_color()))

        player = Player(packet.player_id, packet.player_name, packet.color)

        self.players[packet.player_id] = player
        for player_id, player in self.players.items():
            print(f"{player_id} - {player.get_name()}")

        if self.is_ready():
            self.initialize_level()
Ejemplo n.º 15
0
 def setUp(self):
     self.player = Player()
Ejemplo n.º 16
0
 def to_virtual(self, game):
     player = VirtualPlayer(game=game)
     player.uid = self.id
     player.name = self.name
     return player
Ejemplo n.º 17
0
class TestPlayer(TestCase):
    def setUp(self):
        self.player = Player()

    def test_get_score_zero(self):
        self.assertEqual(self.player.get_score(), (0, 0))

    def test_get_score_nonzero(self):
        self.player.correct = 1
        self.player.incorrect = 2

        self.assertEqual(self.player.get_score(), (1, 2))

    def test_increment_correct(self):
        self.player.increment_correct()
        self.assertEqual(self.player.correct, 1)

        self.player.increment_correct()
        self.assertEqual(self.player.correct, 2)

    def test_increment_incorrect(self):
        self.player.increment_incorrect()
        self.assertEqual(self.player.incorrect, 1)

        self.player.increment_incorrect()
        self.assertEqual(self.player.incorrect, 2)

    def test_set_name_empty(self):
        with self.assertRaises(ValueError):
            self.player.set_name("")

    def test_set_name(self):
        self.player.set_name("alice")

        self.assertEqual(self.player.name, "alice")
    def update_players(self, headings, players_table):
        # Remove players that have quit
        for player in self.server.players:
            if player.username not in \
                    [player_row[headings.index("Name")]
                     for player_row in players_table]:
                self.server.player_quit(player)

        for player_row in players_table:
            username = player_row[headings.index("Name")]
            new_perk = player_row[headings.index("Perk")]
            if not new_perk:
                new_perk = "N/A"
            try:
                new_health = int(player_row[headings.index("Health")])
            except TypeError:
                new_health = 0
            new_kills = int(player_row[headings.index("Kills")])
            new_ping = int(player_row[headings.index("Ping")])
            new_dosh = int(player_row[headings.index("Dosh")])

            player = self.server.get_player(username)
            # If the player has just joined, inform the server and skip maths
            if player is None:
                player = Player(username, new_perk)
                player.kills = new_kills
                player.health = new_health
                player.dosh = new_dosh

                detail = self.get_player_details(player.username)
                player.country = detail["country"]
                player.country_code = detail["country_code"]
                player.ip = detail["ip"]
                player.sid = detail["steam_id"]
                player.id = detail["player_id"]
                player.key = detail["player_key"]

                self.server.player_join(player)
                continue

            # Players can also have 0 HP while in lobby, do additional checks
            if new_health == 0 and \
                    new_health < player.health and \
                    new_kills > 0:
                message = "Player {} died on {}"\
                    .format(player.username, self.server.name)
                print(colored(message, 'red'))
                player.total_deaths += 1

            player.perk = new_perk
            player.ping = new_ping

            if "Perk Level" in headings:
                player.perk_level = \
                    int(player_row[headings.index("Perk Level")])

            player.total_kills += new_kills - player.kills
            player.wave_kills += new_kills - player.kills
            player.kills = new_kills

            if new_dosh > player.dosh:
                player.wave_dosh += new_dosh - player.dosh
                player.game_dosh += new_dosh - player.dosh
                player.total_dosh += new_dosh - player.dosh
            else:
                player.total_dosh_spent += player.dosh - new_dosh
            player.dosh = new_dosh

            if new_health < player.health:
                player.total_health_lost += player.health - new_health
            player.health = new_health