コード例 #1
0
 def __init__(self, players_socket):
     with open('setting/setting_hero.json', 'r') as f:
         self.setting_hero = json.loads(f.read(), encoding='utf-8')
     self.players = {}
     self.players_socket = players_socket
     self.rlist = []
     for con in self.players_socket.values():
         self.rlist.append(con)
     self.datapack = DataPack(players_socket)
     self.dataunpack = DataUnPack()
     for player_num in players_socket.keys():
         self.players[player_num] = {}
         self.players[player_num]['equip'] = {}
         self.players[player_num]['equip'] = {
             "horse_add": None,
             "houser_sub": None,
             "armour": None,
             "weapon": None
         }
         self.players[player_num]['identity'] = None
         self.players[player_num]['alive'] = True
     self.players_socket['all'] = None
     self.skill_releaser = SkillReleaser(self.players_socket)
     self.total_card = []
     self.drop_card = []
コード例 #2
0
ファイル: login.py プロジェクト: BearGroysenHe/SanGuoSha
 def __init__(self):
     self.sk = socket.socket()
     self.sk.bind(('127.0.0.1', 8999))
     self.sk.listen(5)
     self.rlist = [self.sk]
     self.game_room = {}
     self.datapack = DataPack(None)
     self.dataunpack = DataUnPack()
コード例 #3
0
 def sendData(self,data,dataid):
     msg=Message()
     msg.setMsgData(data)
     msg.setMsgId(dataid)
     
     datapack=DataPack(msg)
     data=datapack.pack()
     self.transport.write(data)
     print('[Server] write data %r to num %r' % (data, self.peer))
コード例 #4
0
def handleData1(addr, transport):
    msg = Message()
    msg.setMsgData(b'Test msg python')
    msg.setMsgId(0)

    datapack = DataPack(msg)
    data = datapack.pack()
    transport.write(data)
    print('[Server] write data %r to addr %r' % (data, addr))
コード例 #5
0
 def __init__(self):
     self.sk = socket.socket()
     self.sk.connect(('127.0.0.1', 8999))
     self.rlist = [self.sk, sys.stdin]
     self.datapack = DataPack(self.sk)
     self.dataunpack = DataUnPack()
     self.player_numb = '01'
     self.players = None
     self.card = []
     self.status = None
     self.alive_players = None
     self.have_attack = True
     self.__log_in()
コード例 #6
0
 def dataReceived(self, data):
     msg=Message()
     datapack=DataPack(msg)
     msglen,msgid,msgdata=datapack.unpack(data)
     print('[Server] receive data %r from num %r , len:%r , id:%r' % (msgdata, self.peer,msglen,msgid))
     
     #根据包的ID进行router分发处理
     routerID=self.routers.apis.get(msgid,None)
     if routerID:
         #发送数据
         routerID(self.peer,self.transport)
     else:
         self.sendData(b'ping....ping....', 1)
コード例 #7
0
ファイル: client.py プロジェクト: xx0746/zinx
 def connectionMade(self):
     m=Message()
     s=b"Test msg"
     m.setMsgData(s)
     m.setMsgId(1)
     
     d=DataPack(m).pack()
     self.transport.write(d)
コード例 #8
0
ファイル: client.py プロジェクト: xx0746/zinx
 def dataReceived(self, data):
     msg = Message()
     datapack = DataPack(msg)
     msglen, msgid, msgdata = datapack.unpack(data)
     print('[Client] receive data %r from server, len:%r , id:%r' % (msgdata,msglen, msgid))
コード例 #9
0
class GameController():
    def __init__(self, players_socket):
        with open('setting/setting_hero.json', 'r') as f:
            self.setting_hero = json.loads(f.read(), encoding='utf-8')
        self.players = {}
        self.players_socket = players_socket
        self.rlist = []
        for con in self.players_socket.values():
            self.rlist.append(con)
        self.datapack = DataPack(players_socket)
        self.dataunpack = DataUnPack()
        for player_num in players_socket.keys():
            self.players[player_num] = {}
            self.players[player_num]['equip'] = {}
            self.players[player_num]['equip'] = {
                "horse_add": None,
                "houser_sub": None,
                "armour": None,
                "weapon": None
            }
            self.players[player_num]['identity'] = None
            self.players[player_num]['alive'] = True
        self.players_socket['all'] = None
        self.skill_releaser = SkillReleaser(self.players_socket)
        self.total_card = []
        self.drop_card = []

    def run_game(self):
        self.datapack.pack_msg('00', '人数已满,正在进入游戏')
        self.__init()
        for key, value in self.players.items():
            if value['identity'] == '主公':
                player = key
                break
        while True:
            self.__beginning()
            self.__judgment()
            self.__get_card(player)
            self.__push_card(player)
            self.__drop_card(player)
            self.__ending()
            while True:
                player = int(player) + 1
                if player > 5:
                    player -= 5
                player = str(player).zfill(2)
                if self.players[player]['alive'] == True:
                    break

    def __init(self):
        self.__card_creater()
        self.__identity_creater()
        self.__choice_hero()
        self.__send_hero_to_player()
        for con in self.players_socket.values():
            if con != None:
                self.__send_card_to_player(4, con)

    def __card_creater(self):
        type = ('Sha', 'Shan', 'Tao')
        card_color = ('S', 'H', 'C', 'D')
        for i in range(108):
            card = {}
            card['name'] = type[randint(0, 2)]
            card['card_color'] = card_color[randint(0, 3)]
            card['card_numb'] = str(randint(1, 13)).zfill(2)
            card['response'] = None
            self.total_card.append(card)

    def __identity_creater(self):
        identity_pool = ['主公', '忠臣', '内奸', '反贼', '反贼']
        # identity_pool = ['主公']
        for i in range(1, len(self.players.keys()) + 1):
            identity = identity_pool[randint(0, len(identity_pool) - 1)]
            self.players[str(i).zfill(2)]['identity'] = identity
            identity_pool.remove(identity)
            msg = '您的身份是%s' % (identity)
            self.datapack.pack_msg('00', msg,
                                   self.players_socket[str(i).zfill(2)])

    def __choice_hero(self):
        hero_list = []
        for hero in self.setting_hero.keys():
            hero_list.append(hero)
        self.datapack.pack_msg('00', '开始选择英雄')
        self.datapack.pack_msg('00', json.dumps(hero_list, ensure_ascii=False))
        self.datapack.pack_order({'name': '__choice_hero', 'data': ''})
        condition = True
        while True:
            if condition:
                rl, wl, xl = select(self.rlist, [], [])
                for r in rl:
                    data = r.recv(2048).decode()
                    data = self.dataunpack.unpack(data)
                    player = self.__get_player_by_con(r)
                    hero = data[2]
                    if data[0] == 'C' and data[1] == '__choice_hero':
                        if hero in hero_list:
                            self.__add_hero_to_player(player, hero)
                            self.datapack.pack_order(
                                {
                                    'name': '__choice_hero',
                                    'data': 'OK'
                                }, self.players_socket[player])
                        else:
                            self.datapack.pack_order(
                                {
                                    'name': '__choice_hero',
                                    'data': 'filed'
                                }, self.players_socket[player])
                            continue
                    else:
                        self.datapack.pack_order(
                            {
                                'name': '__choice_hero',
                                'data': 'filed'
                            }, self.players_socket[player])
                        continue
                    msg = '玩家%s已选择英雄%s' % (player, hero)
                    self.datapack.pack_msg('00', msg)
                    hero_list.remove(hero)
                    self.datapack.pack_msg(
                        '00', json.dumps(hero_list, ensure_ascii=False))
                    if len(hero_list) == 0:
                        self.datapack.pack_order({
                            'name': '__choice_hero',
                            'data': 'over'
                        })
                        self.datapack.pack_msg('00', '选择英雄结束')
                        condition = False
                        break
            else:
                break

    def __get_player_by_con(self, con):
        for key, value in self.players_socket.items():
            if value == con:
                return key

    def __add_hero_to_player(self, player, hero):
        hero_setting = 'setting/hero/' + self.setting_hero[hero]
        with open(hero_setting, encoding='utf-8') as f:
            hero_setting = json.loads(f.read(), encoding='utf-8')
        self.players[player]['hero'] = hero_setting

    def __send_hero_to_player(self):
        self.datapack.pack_order({'name': 'send_hero', 'data': self.players})

    def __send_card_to_player(self, numb, target):
        for i in range(numb):
            card = self.total_card.pop()
            self.datapack.pack_order({
                'name': 'send_card',
                'data': card
            }, target)

    def __beginning(self):
        pass

    def __judgment(self):
        pass

    def __get_card(self, player):
        self.__send_card_to_player(2, self.players_socket[player])

    def __push_card(self, player):
        self.datapack.pack_order({
            'name': 'push_card',
            'data': None
        }, self.players_socket[player])
        condition = True
        while True:
            if condition:
                rl, wl, xl = select(self.rlist, [], [])
                for r in rl:
                    data = r.recv(2048).decode()
                    data = self.dataunpack.unpack(data)
                    if data[0] == 'C':
                        if data[1] == 'push_card':
                            self.datapack.pack_msg(
                                '00',
                                '玩家%s打出了一张%s' % (player, data[2]['name']))
                            responses = self.skill_releaser.push_card(
                                data[2], self.players)
                            if responses != None:
                                for respone in responses:
                                    if respone[0] == 'msg':
                                        self.datapack.pack_msg(
                                            '00', respone[1],
                                            self.players_socket[respone[2]])
                                    elif respone[0] == 'order':
                                        self.datapack.pack_order(
                                            respone[1],
                                            self.players_socket[respone[2]])
                        elif data[1] == 'drop_card':
                            condition = False
                            break
                        elif data[1] == 'response':
                            responses = self.skill_releaser.push_card(
                                data[2], self.players)
                            if respone != None:
                                for respone in responses:
                                    if respone[0] == 'msg':
                                        self.datapack.pack_msg(
                                            '00', respone[1],
                                            self.players_socket[respone[2]])
                                    elif respone[0] == 'order':
                                        self.datapack.pack_order(
                                            respone[1],
                                            self.players_socket[respone[2]])
                        elif data[1] == 'dying':
                            self.datapack.pack_msg(
                                '00', '玩家%s死了' % self.__get_player_by_con(r))
                            self.players[data[2]]['alive'] = False
                            self.datapack.pack_order({
                                'name': 'send_hero',
                                'data': self.players
                            })

            else:
                break

    def __drop_card(self, player):
        while True:
            data = self.players_socket[player].recv(2048).decode()
            data = self.dataunpack.unpack(data)
            if data[0] == 'C' and data[1] == 'drop_card':
                if data[2] == 'OK':
                    break
                else:
                    self.datapack.pack_msg(
                        '00', '玩家%s弃了一张%s' % (player, data[2]['name']))
                    self.drop_card.append(data[2])

    def __ending(self):
        pass
コード例 #10
0
class Client():
    def __init__(self):
        self.sk = socket.socket()
        self.sk.connect(('127.0.0.1', 8999))
        self.rlist = [self.sk, sys.stdin]
        self.datapack = DataPack(self.sk)
        self.dataunpack = DataUnPack()
        self.player_numb = '01'
        self.players = None
        self.card = []
        self.status = None
        self.alive_players = None
        self.have_attack = True
        self.__log_in()

    def __log_in(self):
        print('欢迎登录三国杀')
        room_numb = input('请输入您要进入的房间号:')
        self.datapack.pack_order({'name': 'room_numb', 'data': room_numb})
        response = self.sk.recv(2048).decode()
        response = self.dataunpack.unpack(response)
        if response[0] == 'C' and response[1] == 'room_numb':
            if response[2] == 'OK':
                print('成功进入房间')
            else:
                print('进入房间失败')
        response = self.sk.recv(2048).decode()
        response = self.dataunpack.unpack(response)
        if response[0] == 'C' and response[1] == 'player_numb':
            self.player_numb = response[2]
        print(self.player_numb)
        self.__choice_hero()
        self.__run_game()

    def __run_game(self):
        while True:
            rl, wl, xl = select(self.rlist, [], [])
            for r in rl:
                if r is self.sk:
                    data = r.recv(2048).decode()
                    data = self.dataunpack.unpack(data)
                    if data[0] == "D":
                        if data[1] == '00':
                            print(data[2])
                        else:
                            print('玩家%s:%s' % (data[1], data[2]))
                    elif data[0] == 'C':
                        if data[1] == 'send_hero':
                            self.__get_hero_setting(data)
                        elif data[1] == 'send_card':
                            self.__send_card(data[2])
                        elif data[1] == 'push_card':
                            self.have_attack = False
                            self.status = 'push_card'
                            print(self.card)
                            print(len(self.card))
                            print('请输入您要出的牌的索引(输入quit进入弃牌阶段)')
                        elif data[1] == 'add_hp':
                            self.__add_hp(data[2])
                        elif data[1] == 'response':
                            self.__response(data[2])
                        elif data[1] == 'sub_hp':
                            self.__sub_hp(data[2])
                else:
                    data = sys.stdin.readline()[:-1]
                    print(data)
                    if data == 'show':
                        print('角色信息')
                        print(self.players[self.player_numb])
                        print('卡牌信息')
                        for card in self.card:
                            print(card)
                        print('存活玩家列表')
                        print(self.alive_players)
                        print('您的编号')
                        print(self.player_numb)
                    elif self.status == 'push_card':
                        self.__push_card(data)
                    elif self.status == 'drop_card':
                        self.__drop_card(data)

    def __choice_hero(self):
        condition = True
        while True:
            if condition:
                rl, wl, xl = select(self.rlist, [], [])
                for r in rl:
                    if r is self.sk:
                        data = r.recv(2048).decode()
                        data = self.dataunpack.unpack(data)
                        if data[0] == "D":
                            if data[1] == '00':
                                print(data[2])
                            else:
                                print('玩家%s:%s' % (data[1], data[2]))
                        elif data[0] == 'C' and data[
                                1] == '__choice_hero' and data[2] == 'OK':
                            print('选择英雄成功')
                        elif data[0] == 'C' and data[
                                1] == '__choice_hero' and data[2] == 'filed':
                            print('选择英雄失败,请重新输入')
                        elif data[0] == 'C' and data[
                                1] == '__choice_hero' and data[2] == None:
                            print('请输入您要选择英雄的名字')
                        elif data[0] == 'C' and data[
                                1] == '__choice_hero' and data[2] == 'over':
                            condition = False
                            break
                    else:
                        hero_name = sys.stdin.readline()[:-1]
                        pack = {'name': '__choice_hero', 'data': hero_name}
                        self.datapack.pack_order(pack)
            else:
                break

    def __get_hero_setting(self, data):
        self.players = data[2]
        self.alive_players = []
        for key, value in self.players.items():
            if value['alive'] == True:
                self.alive_players.append(key)
        self.alive_players.sort()

    def __push_card(self, card_index):
        if card_index == 'quit':
            print('请弃牌至当前血量')
            current_hp = int(self.players[self.player_numb]['hero']['hp'])
            print(current_hp)
            print('请输入您要丢弃的牌的索引')
            self.datapack.pack_order({'name': 'drop_card', 'data': None})
            self.status = 'drop_card'
        else:
            card = self.card[int(card_index)]
            if card['name'] == 'Sha':
                if self.have_attack:
                    print('您本回合已经出过一次杀了')
                else:
                    while True:
                        target = input('请输入目标玩家的编号')
                        card['to'] = target
                        print(target)
                        if self.__check_distance(self.player_numb, target):
                            self.datapack.pack_order({
                                'name': 'push_card',
                                'data': card
                            })
                            self.card.remove(card)
                            self.have_attack = True
                            break
                        else:
                            print('您的攻击距离不够无法出杀')
            elif card['name'] == 'Tao':
                if self.players[
                        self.player_numb]['hero']['hp_max'] == self.players[
                            self.player_numb]['hero']['hp']:
                    print('您的生命值已满,无法出桃')
                else:
                    self.datapack.pack_order({
                        'name': 'push_card',
                        'data': card
                    })
                    self.card.remove(card)
            else:
                print('您不能打出这张牌')

    def __drop_card(self, card_index):
        current_hp = int(self.players[self.player_numb]['hero']['hp'])
        self.datapack.pack_order({
            'name': 'drop_card',
            'data': self.card[int(card_index)]
        })
        self.card.pop(int(card_index))
        if len(self.card) <= current_hp:
            print('弃牌结束')
            self.datapack.pack_order({'name': 'drop_card', 'data': 'OK'})
            self.status = 'response'

    def __send_card(self, card):
        card['from'] = self.player_numb
        card['to'] = None
        self.card.append(card)

    def __check_distance(self, skill_from, skill_to):
        index1 = self.alive_players.index(skill_from)
        index2 = self.alive_players.index(skill_to)
        alive_numb = len(self.alive_players) / 2
        distance = alive_numb - abs(abs(index1 - index2) - alive_numb)
        range = 1
        if distance > range:
            return False
        else:
            return True

    def __add_hp(self, data):
        self.players[data['target']]['hero']['hp'] += 1

    def __response(self, data):
        if data['name'] == 'Sha':
            print('有人对我除了一张杀')
            result = self.__check_card_exist('Shan')
            print(result)
            if result == False:
                data['response'] = 'failed'
                self.datapack.pack_order({'name': 'response', 'data': data})
            else:
                card_index = input('请出一张闪(输入quit放弃)')
                if card_index == 'quit':
                    data['response'] = 'failed'
                    self.datapack.pack_order({
                        'name': 'response',
                        'data': data
                    })
                elif self.card[int(card_index)]['name'] == 'Shan':
                    data['response'] = 'OK'
                    self.datapack.pack_order({
                        'name': 'response',
                        'data': data
                    })
                    self.datapack.pack_order({
                        'name': 'push_card',
                        'data': self.card[int(card_index)]
                    })
                    self.card.remove(self.card[int(card_index)])
                else:
                    print('您只能出闪')

    def __sub_hp(self, data):
        self.players[data]['hero']['hp'] -= 1
        self.__check_alive()

    def __check_alive(self):
        if self.players[self.player_numb]['hero']['hp'] < 1:
            if self.__check_card_exist('tao'):
                self.datapack.pack_order({
                    'name': 'dying',
                    'data': self.player_numb
                })
            else:
                card_index = input('您快要死了,请出桃(输入quit拒绝)')
                if card_index == 'quit':
                    self.datapack.pack_order({
                        'name': 'dying',
                        'data': self.player_numb
                    })
                elif self.card[int(card_index)]['name'] == 'tao':
                    self.datapack.pack_order({
                        'name': 'push_card',
                        'data': self.card[int(card_index)]
                    })
                else:
                    print('您只能出桃')

    def __check_card_exist(self, card_name):
        for card in self.card:
            if card['name'] == card_name:
                return True
        return False
コード例 #11
0
ファイル: login.py プロジェクト: BearGroysenHe/SanGuoSha
class Server():
    def __init__(self):
        self.sk = socket.socket()
        self.sk.bind(('127.0.0.1', 8999))
        self.sk.listen(5)
        self.rlist = [self.sk]
        self.game_room = {}
        self.datapack = DataPack(None)
        self.dataunpack = DataUnPack()

    def log_in(self):
        while True:
            rl, wl, xl = select(self.rlist, [], [])
            for r in rl:
                if r is self.sk:
                    con, addr = r.accept()
                    self.rlist.append(con)
                else:
                    response = r.recv(2048).decode()
                    response = self.dataunpack.unpack(response)
                    if response[0] == 'C' and response[1] == 'room_numb':
                        data = response[2]
                        if data not in self.game_room:
                            self.game_room[data] = {
                                '01': None,
                                '02': None,
                                '03': None,
                                '04': None,
                                '05': None
                            }
                            self.game_room[data]['01'] = r
                            self.datapack.pack_order(
                                {
                                    'name': 'room_numb',
                                    'data': 'OK'
                                }, r)
                            self.datapack.pack_order(
                                {
                                    'name': 'player_numb',
                                    'data': '01'
                                }, r)
                        else:
                            for keys, values in self.game_room[data].items():
                                if values == None:
                                    self.game_room[data][keys] = r
                                    self.datapack.pack_order(
                                        {
                                            'name': 'room_numb',
                                            'data': 'OK'
                                        }, r)
                                    self.datapack.pack_order(
                                        {
                                            'name': 'player_numb',
                                            'data': keys
                                        }, r)
                                    break
                        for con in self.game_room[data].values():
                            if con == None:
                                break
                        else:
                            for con in self.game_room[data].values():
                                self.rlist.remove(con)
                            game_controller = GameController(
                                self.game_room[data])
                            p = Process(target=game_controller.run_game)
                            p.start()