예제 #1
0
 def join_player(self, player, key):
     if key in self.waiting_players:
         opponent = self.waiting_players.pop(key)
         room = Room([opponent.nick, player.nick])
         self.rooms.append(room)
         room.add_player(0, opponent)
         room.add_player(1, player)
         room.start_game()
         # save to database, to assign ID
         self.db.save_room(room)
     else:
         player.send('join_failed', 'Opponent not found.')
예제 #2
0
def create_room():
    new_room = Room()
    rooms.append(new_room)

    parsed_req = json.loads(request.data)
    player = Player(parsed_req['name'])
    try:
        new_room.add_player(player)
    except Exception as e:
        return {'error': str(e)}, 422

    return {'id': new_room.id, 'player_id': player.id}
예제 #3
0
class RoomTest(unittest.TestCase):
    ####################################################################
    def setUp(self):
        self.room = Room()
        self.room.type = RoomType.TRAINING_ROOM
        self.room.id = 3
        self.room.description = "Just a plain room"

    ####################################################################
    def test_deserialize_from_dict(self):
        short_sword = item.item_database.find(2)
        leather_armor = item.item_database.find(3)
        healing_potion = item.item_database.find(5)
        room_template_data = {
            "id": 50,
            "name": "Sewage Trench",
            "description":
            "You're in a sewage trench, filled with all sorts of liquid refuse, slowly flowing eastward into the town sewers.",
            "type": "PLAIN_ROOM",
            "data": 0,
            "north": 49,
            "east": 51,
            "south": 0,
            "west": 0,
            "spawn_which_enemy": 9,
            "max_enemies": 1,
            "starting_items": [2, 3],
            "starting_money": 30
        }
        this_room = Room.deserialize_from_dict(room_template_data, {})
        self.assertEqual(this_room.id, 50)
        self.assertEqual(this_room.name, "Sewage Trench")
        self.assertEqual(this_room.type, RoomType.PLAIN_ROOM)
        # self.assertEqual(this_room.data, 0)
        self.assertEqual(len(this_room.connecting_rooms), 2)
        self.assertEqual(this_room.connecting_rooms[Direction.NORTH], 49)
        self.assertEqual(this_room.connecting_rooms[Direction.EAST], 51)
        self.assertEqual(this_room.spawn_which_enemy, 9)
        self.assertEqual(this_room.max_enemies, 1)
        self.assertEqual(this_room.items, [short_sword, leather_armor])
        self.assertEqual(this_room.money, 30)

        room_dynamic_data = {"id": 50, "items": [5], "money": 2}

        this_room = Room.deserialize_from_dict(room_template_data,
                                               room_dynamic_data)
        self.assertEqual(this_room.id, 50)
        self.assertEqual(this_room.name, "Sewage Trench")
        self.assertEqual(this_room.type, RoomType.PLAIN_ROOM)
        # self.assertEqual(this_room.data, 0)
        self.assertEqual(len(this_room.connecting_rooms), 2)
        self.assertEqual(this_room.connecting_rooms[Direction.NORTH], 49)
        self.assertEqual(this_room.connecting_rooms[Direction.EAST], 51)
        self.assertEqual(this_room.spawn_which_enemy, 9)
        self.assertEqual(this_room.max_enemies, 1)
        self.assertEqual(this_room.items, [healing_potion])
        self.assertEqual(this_room.money, 2)

    ####################################################################
    def test_serialize_to_dict(self):
        power_armor = item.item_database.find(55)
        darkness_armor = item.item_database.find(54)
        self.room.add_item(power_armor)
        self.room.add_item(darkness_armor)
        self.room.money = 33

        expected = {"items": [55, 54], "money": 33}
        self.assertEqual(self.room.serialize_to_dict(), expected)

    ####################################################################
    def test_get_adjacent_room(self):
        first_room = room.room_database.find("Town Square")
        self.assertEqual(first_room.id, 1)
        second_room = first_room.get_adjacent_room(Direction.NORTH)
        self.assertEqual(second_room.id, 2)
        self.assertEqual(second_room.name, "Street")

    ####################################################################
    def test_add_player(self):
        self.assertEqual(self.room.players, set())
        p = player.Player(22)
        p.name = "jerry"
        player.player_database.add_player(p)
        self.room.add_player(p)
        self.assertEqual(self.room.players, {p})

    ####################################################################
    def test_remove_player(self):
        p = player.Player(22)
        p.name = "jerry"
        player.player_database.add_player(p)
        self.room.add_player(p)
        self.assertEqual(self.room.players, {p})

        self.room.remove_player(p)
        self.assertEqual(self.room.players, set())

    ####################################################################
    def test_find_item(self):
        power_armor = item.item_database.find(55)
        darkness_armor = item.item_database.find(54)
        self.room.add_item(power_armor)
        self.room.add_item(darkness_armor)
        self.assertEqual(self.room.find_item("darkness"), darkness_armor)
        self.assertEqual(self.room.find_item("power"), power_armor)
        self.assertEqual(self.room.find_item("armor"), power_armor)

    ####################################################################
    def test_add_item(self):
        armor = item.item_database.find(55)
        self.assertEqual(self.room.items, [])
        self.room.add_item(armor)
        self.assertEqual(self.room.items, [armor])

        self.room.remove_item(armor)

        # Test MAX_ITEMS limit
        for i in range(1, room.MAX_ITEMS + 3):
            self.room.add_item(item.item_database.find(i))

        items_ids_left = [x.id for x in self.room.items]
        self.assertEqual(items_ids_left, range(3, room.MAX_ITEMS + 3))

    ####################################################################
    def test_remove_item(self):
        armor = item.item_database.find(55)
        self.room.add_item(armor)
        self.assertEqual(self.room.items, [armor])
        self.room.remove_item(armor)
        self.assertEqual(self.room.items, [])

    ####################################################################
    def test_find_enemy(self):
        self.fail()
        # return utils.double_find_by_name(enemy_name, self.enemies)

    ####################################################################
    def test_add_enemy(self):
        self.fail()
        # self.enemies.add(enemy)

    ####################################################################
    def test_remove_enemy(self):
        self.fail()
예제 #4
0
class SimpleServer(object):
    def __init__(self):
        super(SimpleServer, self).__init__()
        self.id_counter = 0
        self.last_time = datetime.now()
        self.player_count = 0  # 当前连入玩家数
        self.host = SimpleHost()
        self.dispatcher = Dispatcher()
        self.room = None
        self.id2player_info = {}
        self.id2client = {}

    def tick(self):
        self.host.process()
        return

    def dispatch(self, data, owner):
        """
        消息派发
        :param data: 原始数据
        :param owner: 接收的客户端
        """
        # 当用户异常退出时发送FIN,data的长度为0
        if len(data) == 0:
            return
        p = Packet(data)
        opcode = p.get_int16()

        def str_to_hex(s):
            return ":".join("{:02x}".format(ord(c)) for c in s)
        print(str_to_hex(data))
        # print u'获得opcode:%d' % opcode
        if opcode == conf.MSG_JOIN_ROOM:
            self.player_join_room(opcode, p, owner)
        elif opcode == conf.MSG_PLAYER_INPUT:
            self.player_input(opcode, p, owner)
        elif opcode == conf.MSG_QUIT_ROOM:
            self.player_input(opcode, p, owner)
        else:
            raise Exception(u'bad opcode %d' % opcode)

    def player_join_room(self, opcode, packet, client):
        # Todo 从数据库读取用户信息
        msg = MessageJoinRoom()
        msg.deserialize(packet)
        player_name = msg.name + str(self.id_counter)
        info = PlayerInfo(player_name, self.id_counter, self.id_counter)
        print u'玩家:%s连入' % info.name
        self.id_counter += 1
        self.player_count += 1
        self.id2player_info[info.id] = info
        self.id2client[info.id] = client

        client.player_info = info
        if self.player_count >= Room.max_count:
            self.room = Room()
            for info in self.id2player_info.values():
                client = self.id2client[info.id]
                self.room.add_player(info, client)
            self.room.start_game()

    def player_quit_room(self, opcode, packet, client):
        player_info = client.player_info
        if player_info is None:
            return
        self.player_count -= 1
        player_id = player_info.id
        del self.id2client[player_id]
        del self.id2player_info[player_id]
        if self.player_count == 0:
            self.room = None

    def player_input(self, opcode, packet, client):
        if self.room is None:
            return
        msg = MessagePlayerInput()
        msg.deserialize(packet)
        player_info = client.player_info
        self.room.set_input(player_info, msg)

    def update(self):
        """
        每30ms更新一次,主要用于帧同步
        """
        now = datetime.now()
        delta_time = (now - self.last_time).total_seconds()
        if delta_time < 0.03:
            return

        self.last_time = now

        if self.room is None:
            return
        self.room.update()