示例#1
0
 def start_chat(self, contact_id):
     participant = User.getUserById(contact_id)
     if Chat.getChatByParticipants(self.current_user, participant):
         self.current_chat = Chat.getChatByParticipants(self.current_user, participant)
     else:
         chat_id = self.current_user.startChat(participant)
         self.current_chat = Chat.getChatById(chat_id)
示例#2
0
文件: Main.py 项目: Bingo521/IQQ
    def LoginSuccess(self):
        self.count = int(self.LoginPanel.username.GetValue())
        Chat.setMe(User("", self.count))
        self.LoginPanel.Show(False)
        #在此初始化
        self.menuBar = wx.MenuBar()
        self.friendList = wx.Menu()
        self.friendList.Append(100, "好友列表")
        self.menuBar.Append(self.friendList, "好友列表")
        self.msgList = wx.Menu()
        self.msgList.Append(200, "消息列表")
        self.menuBar.Append(self.msgList, "消息列表")
        self.addFriend = wx.Menu()
        self.addFriend.Append(300, "添加好友")
        self.menuBar.Append(self.addFriend, "添加好友")
        self.notifiList = wx.Menu()
        self.notifiList.Append(400, "通知列表")
        self.menuBar.Append(self.notifiList, "通知列表")
        self.friendList = wx.Menu()

        self.friendList.Append(500, "设置")
        self.menuBar.Append(self.friendList, "设置")
        self.SetMenuBar(self.menuBar)

        self.Bind(wx.EVT_MENU, self.ShowFriendList, id=100)
        self.Bind(wx.EVT_MENU, self.ShowMsgPanel, id=200)
        self.Bind(wx.EVT_MENU, self.ShowAddPanel, id=300)
        self.Bind(wx.EVT_MENU, self.ShowInformPanel, id=400)
        self.Bind(wx.EVT_MENU, self.ShowConfigPanel, id=500)
        self.ShowFriendList()

        self.timer = wx.Timer(self)  # 创建定时器
        self.Bind(wx.EVT_TIMER, self.Timer, self.timer)
        self.timer.Start(400)
示例#3
0
    def __init__(self):
        print("Shared Data initializing....", end="")
        self._online = {}
        self._players = {}
        self._all_ufos = {}
        self._all_bases = {}
        self._sessions = {}
        self._chat = Chat()
        self._map = Map(1, 1)
        self._log = Logger('XFF', 'SharedData')
        self._map_actions = {}
        self._skill_queues = []

        self._loop = GeoLoop()
        self.organizations = {}
        self.NPCs = {}
        self.havens = {}

        self.mongo_helper = mongohelper.MongoHelper()
        # Populate UFOs collection with default objects
        if config.BACKSERVER_POPULATE_MONGO:
            self.mongo_helper.add_ufo(UFOs.Probe())
            self.mongo_helper.add_ufo(UFOs.SmallScout())
            self.mongo_helper.add_ufo(UFOs.MediumScout())
            self.mongo_helper.add_ufo(UFOs.LargeScout())
            self.mongo_helper.add_site(GroundSite.BasicSectoidOperation())

        # Load Collections from Mongo
        self._ufos = self.mongo_helper.get_all_ufos()
        self._sites = self.mongo_helper.get_all_sites()

        print("OK")
示例#4
0
文件: Main.py 项目: Bingo521/IQQ
 def SelectFriend(self, event):
     user = self.friendPanel.friendList.li[self.index]
     Chat.setChatWith(user)
     self.chatPanel.username.SetLabel("{0}({1})".format(
         user.username, user.count))
     self.ShowMsgPanel()
     pass
示例#5
0
 def startChat(self, *participants):
     rows = self.getContacts()
     contacts = []
     for row in rows:
         contacts.append(row[0])
     new_chat = Chat(self)
     new_chat.add_participants(contacts)
     return new_chat.id
示例#6
0
 def addChat_id(self, chatid, db):
     if (self.chatList.__contains__(chatid) == False):
         self.chatList.append(chatid)
         print("fatto")
         db.add_chat("chat", chatid)
         chat = Chat()
         chat.chat_id = chatid
         self.lista_chat.append(chat)
示例#7
0
 def startChat(self, *participants):
     new_chat = Chat(self)
     new_chat.add_participants(*participants)
     '''
     if new_chat.participants:
         new_chat.printChat()
     else:
         print("Участники не добавлены")
     '''
     return new_chat.id
示例#8
0
文件: Main.py 项目: Bingo521/IQQ
 def sendMsg(self, event):
     msg = self.chatPanel.sendBox.GetValue()
     self.chatPanel.sendBox.SetValue("")
     print("我说:{0}".format(msg))
     if Chat.chatWith == None:
         wx.MessageBox("请选择一位好友!", "提示", wx.OK, self)
         return
     Chat.send(msg)
     date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
     self.SetWord(Chat.chatWith.count, date, msg, "我说")
示例#9
0
文件: Main.py 项目: Bingo521/IQQ
 def DeleteFriend(self, event):
     user = self.friendPanel.friendList.li[self.index]
     isOk = wx.MessageBox("确定您要删除%s(%d)" % (user.username, user.count),
                          "提示",
                          wx.OK | wx.CANCEL,
                          parent=self)
     if isOk == wx.OK:
         self.friendPanel.friendList.deleteItem1(self.index)
         print("发送删除信息!")
         Chat.deleteFriend(user)
示例#10
0
文件: Main.py 项目: Bingo521/IQQ
    def OnLogin(self, event):
        if not Chat.isConnect:
            wx.MessageBox("服务器未正常运行!", "提示", wx.OK, self)
            return
        #校验登陆成功
        try:
            username = int(self.LoginPanel.username.GetValue())
            password = self.LoginPanel.password.GetValue()
            Chat.toLogIn(username, password)

        except:
            wx.MessageBox("用户名密码不合法", "提示", wx.OK, self)
示例#11
0
文件: Main.py 项目: Bingo521/IQQ
    def AddFriend(self, event=0):
        count = self.addPanel.count.GetValue()

        if len(count) == 0:
            wx.MessageBox("请输入好友账号!", "提示", wx.OK, self)
            return
        count = int(count)
        if count == self.count:
            wx.MessageBox("不能添加自己为好友", "提示", wx.OK, self)
            return
        try:
            count = int(count)
        except:
            wx.MessageBox("输入账号不合法!", "提示", wx.OK, self)
            return
        print("请求发送中...")
        Chat.toAddFriend({POTOCOL.COUNT: count})
示例#12
0
 def new_message(self, message, user_id, chat_id):
     switch_time = {
         'Понедельник': 0,
         'Вторник': 1,
         'Среда': 2,
         'Четверг': 3,
         'Пятница': 4,
         'Суббота': 5,
         'Воскресенье': 6,
     }
     if switch_time.get(self._prev_day) > switch_time.get(self._get_day()):
         self._prev_day = self._get_day()
         request = requests.get(
             'https://itmo.ru/ru/schedule/0/M3206/raspisanie_zanyatiy_M3206.htm'
         )
         self._itmo_schedule = BeautifulSoup(request.text, 'lxml')
     if message.lower() == self._commands[0]:
         return self._get_info()
     if message.lower() == self._commands[1]:
         return self._day_info(1)
     if message.lower() == self._commands[2]:
         return self._day_info(0)
     if message.lower() == self._commands[3]:
         return self._command_info()
     if message.lower() == self._commands[4] or message.lower(
     ) == self._commands[6]:
         return self._update()
     if message.lower() == self._commands[5] or message.lower(
     ) == self._commands[7]:
         self._save_state()
         return "Спасибо за понимание"
     if message == self._commands[8]:
         self._save_state()
         return "зАхАрЕвИч!"
     if message.lower() == self._commands[9]:
         return self._update_all()
     if message.lower() == self._commands[10] or message.lower(
     ) == self._commands[12]:
         self._save_state()
         return self._participation(chat_id, message.lower())
     if message.lower() == self._commands[11]:
         self._save_state()
         return "usachova.gitbook.io"
     if message.lower() == self._commands[13]:
         self._save_state()
         return "Saved"
     if message.lower() == self._commands[14]:
         self._save_state()
         return self._deadlines()
     if message.lower() == self._commands[15]:
         return self.joke()
     if message.lower() == self._commands[16]:
         return "usachova.gitbook.io - сайтик\nbars.itmo.ru - БаРС\nisu.ifmo.ru - ИСУ\nde.ifmo.ru - ЦДО"
     if self._flood.get(chat_id) is None:
         self._flood[chat_id] = Chat()
     self._flood[chat_id].plus(user_id)
     self._flood_amount[chat_id] += 1
     return "no"
示例#13
0
文件: Main.py 项目: Bingo521/IQQ
 def sendFile(self, event):
     if Chat.chatWith == None:
         wx.MessageBox("请选择一位好友", "提示", parent=self)
         return
     dlg = wx.FileDialog(self, u"请选择文件")
     if dlg.ShowModal() == wx.ID_OK:
         path = dlg.GetPath()
         filename = dlg.GetFilename()
         Chat.SendFile(path, filename)
示例#14
0
文件: Main.py 项目: Bingo521/IQQ
 def Fefuse(self, event):
     item = self.informPanel.friendList.li[self.index]
     count = item.data.get(POTOCOL.COUNT)
     if count == None:
         print("Refuse:协议错误...")
     self.DeleteInfo()
     Chat.Fefuse(int(self.count), int(count))
     print("已发送拒绝通知")
     print("删除该行")
示例#15
0
文件: Main.py 项目: Bingo521/IQQ
 def Agree(self, event):
     item = self.informPanel.friendList.li[self.index]
     count = item.data.get(POTOCOL.COUNT)
     if count == None:
         print("Agree:协议错误...")
     Chat.Agree(int(self.count), int(count))
     self.DeleteInfo()
     print("已发送同意请求")
     print("删除该行")
示例#16
0
文件: Main.py 项目: Bingo521/IQQ
 def Recv(self, event):
     data = self.informPanel.friendList.li[self.index]
     data.data[POTOCOL.INFOTIP] = "[1]{0}正在接收...".format(
         data.data[POTOCOL.FILENAME], 0)
     data.data[POTOCOL.COUNT] = ""
     data.type = POTOCOL.INFORECV
     id = data.data[POTOCOL.INFOID]
     self.informPanel.friendList.refresh2()
     path = self.configPanel.pathLabel.GetValue()
     Chat.Recv(id, path)
     pass
示例#17
0
文件: Main.py 项目: Bingo521/IQQ
    def DeleteInfo(self, event=0):
        print("开始删除")
        item = self.informPanel.friendList.li.pop(self.index)
        self.informPanel.friendList.refresh2()

        print("删除完毕")
        id = item.data.get(POTOCOL.INFOID)
        if id == None:
            print("id=====none")
            return
        Chat.DeleteInfo(id)
示例#18
0
文件: Main.py 项目: Bingo521/IQQ
 def ToRegister(self, event):
     username = self.Register.username.GetValue()
     password = self.Register.password.GetValue()
     conform = self.Register.conform.GetValue()
     print("password:{0},conform:{1}".format(password, conform))
     if password != conform:
         wx.MessageBox("密码不一致!", "提示!", wx.OK, self)
         return
     lenu = len(username)
     lenp = len(password)
     if lenu <= 0:
         wx.MessageBox("用户名长度过短,请重新输入!", "提示!", wx.OK, self)
         return
     if lenu > 16:
         wx.MessageBox("用户名长度过长,请重新输入!", "提示!", wx.OK, self)
         return
     if lenp < 4:
         wx.MessageBox("密码长度过短,请重新输入!", "提示!", wx.OK, self)
         return
     if lenp > 20:
         wx.MessageBox("密码长度过长,请重新输入!", "提示!", wx.OK, self)
         return
     Chat.toRegister(username, password)
示例#19
0
 def startChat(self, *participants):
     new_chat = Chat(self)
     new_chat.add_participants(*participants)
     if new_chat.add_participants(*participants):
         all_participants = [x for x in participants]
         all_participants.append(self)
         while True:
             new_chat.printChat()
             curr_participant = 0
             curr_participant = int(
                 input("Введите номер участника: {} для {}\n".format(
                     [x for x in range(len(all_participants))],
                     [x.name for x in all_participants])))
             new_message = input(
                 "Введите сообщение от имени {} или X для выхода из чата\n".
                 format(all_participants[curr_participant].name))
             if new_message != 'X':
                 new_chat.addMessage(all_participants[curr_participant],
                                     new_message)
             else:
                 break
     else:
         print("Участники не добавлены")
示例#20
0
 def _load_state(self):
     file = open('flood.txt', 'r')
     temp_chat = ''
     for line in file:
         if line == '':
             continue
         if line.split()[0] == 'index:':
             temp_chat = int(line.split()[1])
             self._flood[temp_chat] = Chat()
             self._flood_amount[temp_chat] = int(line.split()[2])
             continue
         temp_user = int(line.split()[0])
         for _ in range(0, int(line.split()[1])):
             self._flood[temp_chat].plus(temp_user)
     file.close()
     file = open('id_to_name.txt', 'r')
     for line in file:
         if line == '':
             continue
         self._id_to_name[int(
             line.split()[0])] = line.split()[1] + " " + line.split()[2]
     file.close()
示例#21
0
 def start_chat(self, contact_id):
     participant = User.getUserById(contact_id)
     chat_id = self.current_user.startChat(participant)
     self.current_chat = Chat.getChatById(chat_id)
示例#22
0
    def initWorld(self, playerId, chosenCharId, x, y, h):

        self.keyMap = {"hello":0, "left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "chat":0, "fast":0, "chat0": 0, "chat1": 0, "users": 0}
        base.win.setClearColor(Vec4(0,0,0,1))
		# chat box
        self.chatbox = Chat(self.cManager, self)
        self.activeUsers = Users(self.cManager, self)

        taskMgr.add(self.message, 'message')


        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward")
        self.inst4 = addInstructions(0.75, "[S]: Run Ralph Backward")
        self.inst6 = addInstructions(0.70, "[Left Arrow]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[Right Arrow]: Rotate Camera Right")
        self.inst8 = addInstructions(0.60, "[0]: Toggle Chat Broadcast")
        self.inst9 = addInstructions(0.55, "[1]: Toggle Private Chat - username/")
        self.inst10 = addInstructions(0.50, "[L]: List Connected Users")


        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
      	self.environ.setTexture(self.moon_tex, 1)

        #Collision Code
        # Initialize the collision traverser.
        base.cTrav = CollisionTraverser()
        # Initialize the Pusher collision handler.
        self.pusher = CollisionHandlerPusher()

        self.bTrav = base.cTrav
        # Create the main character, Ralph
        self.mainCharRef = Character(self, chosenCharId, True)
        self.mainCharRef.setPlayerId(playerId)
        self.characters.append(self.mainCharRef)
        self.mainChar = self.mainCharRef.getActor()


        #Create second bike
        self.mainCharRef2 = Character(self, 3, True)
        self.mainCharRef2.setPlayerId(2)
        self.characters.append(self.mainCharRef2)
        self.mainChar2 = self.mainCharRef2.getActor()

        resetPos = True
        if (x == 0 and y == 0):
            resetPos = False
        if resetPos:
            self.mainChar.setPos(x, y, 0)
        self.mainChar.setH(h)

        self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, [playerId,
                                                                    chosenCharId,
                                                                    self.mainChar.getX(),
                                                                    self.mainChar.getY(),
                                                                    self.mainChar.getZ()])


        self.previousPos = self.mainChar.getPos()
        taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')

        # Creating Stationary spheres
        self.spheres = []
        self.sphereCount = 3
        for x in range(self.sphereCount):
            self.spheres.append(StationarySphere(self))
        for sphere in self.spheres:
            taskMgr.add(sphere.rotateForAll, "rotateSphere")

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)


        floorNode = render.attachNewNode("Floor NodePath")
        # Create a collision plane solid.
        collPlane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        # Call our function that creates a nodepath with a collision node.
        floorCollisionNP = self.makeCollisionNodePath(floorNode, collPlane)

        # Accept the control keys for movement and rotation
        self.accept("escape", self.quitGame)
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("lshift", self.setKey, ["fast", 1])
        self.accept("arrow_left", self.setKey, ["cam-left",1])
        self.accept("arrow_right", self.setKey, ["cam-right",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("lshift-up", self.setKey, ["fast", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left",0])
        self.accept("arrow_right-up", self.setKey, ["cam-right",0])
        self.accept("h", self.setKey, ["hello",1])
        self.accept("h-up", self.setKey, ["hello",0])
        self.accept("0", self.setKey, ["chat0", 1])
        self.accept("0-up", self.setKey, ["chat0", 0])
        self.accept("1", self.setKey, ["chat1", 1])
        self.accept("1-up", self.setKey, ["chat1", 0])
        self.accept("l", self.setKey, ["users", 1])
        self.accept("l-up", self.setKey, ["users", 0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.mainChar.getX(),self.mainChar.getY()+10,2)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
示例#23
0
class World(DirectObject):

    currentTime = 0
    idleTime = 0
    mySequence = None
    pandaPace = None
    jumpState = False
    isWalk = False
    previousPos = None #used to store the mainChar pos from one frame to another
    host = ""
    port = 0
    characters = []  #Stores the list of all the others players characters

    def __init__(self):
        # Network Setup
        print "Object Created"
        self.characters = []
    def setConnectionManager(self, connectionManager):
        self.cManager = connectionManager

    def initWorld(self, playerId, chosenCharId, x, y, h):

        self.keyMap = {"hello":0, "left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "chat":0, "fast":0, "chat0": 0, "chat1": 0, "users": 0}
        base.win.setClearColor(Vec4(0,0,0,1))
		# chat box
        self.chatbox = Chat(self.cManager, self)
        self.activeUsers = Users(self.cManager, self)

        taskMgr.add(self.message, 'message')


        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward")
        self.inst4 = addInstructions(0.75, "[S]: Run Ralph Backward")
        self.inst6 = addInstructions(0.70, "[Left Arrow]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[Right Arrow]: Rotate Camera Right")
        self.inst8 = addInstructions(0.60, "[0]: Toggle Chat Broadcast")
        self.inst9 = addInstructions(0.55, "[1]: Toggle Private Chat - username/")
        self.inst10 = addInstructions(0.50, "[L]: List Connected Users")


        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
      	self.environ.setTexture(self.moon_tex, 1)

        #Collision Code
        # Initialize the collision traverser.
        base.cTrav = CollisionTraverser()
        # Initialize the Pusher collision handler.
        self.pusher = CollisionHandlerPusher()

        self.bTrav = base.cTrav
        # Create the main character, Ralph
        self.mainCharRef = Character(self, chosenCharId, True)
        self.mainCharRef.setPlayerId(playerId)
        self.characters.append(self.mainCharRef)
        self.mainChar = self.mainCharRef.getActor()


        #Create second bike
        self.mainCharRef2 = Character(self, 3, True)
        self.mainCharRef2.setPlayerId(2)
        self.characters.append(self.mainCharRef2)
        self.mainChar2 = self.mainCharRef2.getActor()

        resetPos = True
        if (x == 0 and y == 0):
            resetPos = False
        if resetPos:
            self.mainChar.setPos(x, y, 0)
        self.mainChar.setH(h)

        self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, [playerId,
                                                                    chosenCharId,
                                                                    self.mainChar.getX(),
                                                                    self.mainChar.getY(),
                                                                    self.mainChar.getZ()])


        self.previousPos = self.mainChar.getPos()
        taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')

        # Creating Stationary spheres
        self.spheres = []
        self.sphereCount = 3
        for x in range(self.sphereCount):
            self.spheres.append(StationarySphere(self))
        for sphere in self.spheres:
            taskMgr.add(sphere.rotateForAll, "rotateSphere")

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)


        floorNode = render.attachNewNode("Floor NodePath")
        # Create a collision plane solid.
        collPlane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        # Call our function that creates a nodepath with a collision node.
        floorCollisionNP = self.makeCollisionNodePath(floorNode, collPlane)

        # Accept the control keys for movement and rotation
        self.accept("escape", self.quitGame)
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("lshift", self.setKey, ["fast", 1])
        self.accept("arrow_left", self.setKey, ["cam-left",1])
        self.accept("arrow_right", self.setKey, ["cam-right",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("lshift-up", self.setKey, ["fast", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left",0])
        self.accept("arrow_right-up", self.setKey, ["cam-right",0])
        self.accept("h", self.setKey, ["hello",1])
        self.accept("h-up", self.setKey, ["hello",0])
        self.accept("0", self.setKey, ["chat0", 1])
        self.accept("0-up", self.setKey, ["chat0", 0])
        self.accept("1", self.setKey, ["chat1", 1])
        self.accept("1-up", self.setKey, ["chat1", 0])
        self.accept("l", self.setKey, ["users", 1])
        self.accept("l-up", self.setKey, ["users", 0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.mainChar.getX(),self.mainChar.getY()+10,2)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    def makeCollisionNodePath(self, nodepath, solid):
        '''
        Creates a collision node and attaches the collision solid to the
        supplied NodePath. Returns the nodepath of the collision node.
        '''
        # Creates a collision node named after the name of the NodePath.
        collNode = CollisionNode("%s c_node" % nodepath.getName())
        collNode.addSolid(solid)
        collisionNodepath = nodepath.attachNewNode(collNode)

        return collisionNodepath
    #Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value
        #print "In setKey", key, value
        self.cManager.sendRequest(Constants.CMSG_KEY, [key, value])

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def getDist(self):
        mainCharX = self.mainChar.getPos().x
        mainCharY = self.mainChar.getPos().y
        pandaX = self.pandaActor2.getPos().x
        pandaY = self.pandaActor2.getPos().y
        dist = math.sqrt(abs(mainCharX-pandaX)**2 + abs(mainCharY-pandaY)**2)
        return dist

    def move(self, task):
        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        base.camera.lookAt(self.mainChar)
        if (self.keyMap["cam-left"]!=0):
            base.camera.setX(base.camera, -20 * globalClock.getDt())
        if (self.keyMap["cam-right"]!=0):
            base.camera.setX(base.camera, +20 * globalClock.getDt())

        # save mainChar's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.mainChar.getPos()
        starthpr = self.mainChar.getHpr()

        # If left-shift is pressed, speed-up ralph
        ralphSpeed = 1
        if(self.keyMap["fast"]==1):
            ralphSpeed = 3
        # If a move-key is pressed, move ralph in the specified direction.
        if (self.keyMap["left"]!=0):
            self.mainChar.setH(self.mainChar.getH() + 300 * globalClock.getDt() * ralphSpeed)
        if (self.keyMap["right"]!=0):
            self.mainChar.setH(self.mainChar.getH() - 300 * globalClock.getDt() * ralphSpeed)
        if (self.keyMap["forward"] != 0 and self.mainCharRef.type == 2):
            self.mainChar.setY(self.mainChar, -500 * globalClock.getDt() * ralphSpeed)
        elif (self.keyMap["forward"] != 0 and self.mainCharRef.type == 3):
            self.mainChar.setZ(self.mainChar, 25 * globalClock.getDt() * ralphSpeed)
        elif (self.keyMap["forward"] != 0):
            self.mainChar.setY(self.mainChar, -25 * globalClock.getDt() * ralphSpeed)
        if (self.keyMap["backward"] != 0 and self.mainCharRef.type == 2):
            self.mainChar.setY(self.mainChar, 500 * globalClock.getDt() * ralphSpeed)
        elif (self.keyMap["backward"] != 0 and self.mainCharRef.type == 3):
            self.mainChar.setZ(self.mainChar, -25 * globalClock.getDt() * ralphSpeed)
        elif (self.keyMap["backward"] != 0):
            self.mainChar.setY(self.mainChar, 25 * globalClock.getDt() * ralphSpeed)

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if (self.keyMap["forward"] != 0) or (self.keyMap["backward"] != 0) or (self.keyMap["left"] != 0) or (
                    self.keyMap["right"] != 0):
            if self.isMoving is False :
                self.isMoving = True
                if self.mainCharRef.type != 3:
                    self.mainChar.loop("run")

        else:
            if self.isMoving:
                self.isMoving = False
                if self.mainCharRef.type != 3:
                    self.mainChar.stop()
                    self.mainChar.pose("walk",5)

        # Detecting collisions only when ralph is moving
        if self.isMoving:
            # Collision With Spheres
            isCollidingWithSphere = False
            for sphere in self.spheres:
                if self.mainCharRef.isColliding(sphere.actor.getPos(), sphere.boundingRadius):
                    isCollidingWithSphere = True

            if isCollidingWithSphere:
                self.mainChar.setPos(startpos)
                self.mainChar.setHpr(starthpr)
            # Collision With Other Ralphs
            isCollidingWithOtherRalphs = False
            for chacracter in self.characters:
                if not chacracter.isMainChar and self.mainCharRef.isColliding(chacracter.actor.getPos(), chacracter.boundingRadius):
                    isCollidingWithOtherRalphs = True
            if isCollidingWithOtherRalphs:
                self.mainChar.setH(self.mainChar.getH() - 180)

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.mainChar.getPos() - base.camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()
        camvec.normalize()
        if (camdist > 10.0):
            base.camera.setPos(base.camera.getPos() + camvec*(camdist-10))
            camdist = 10.0
        if (camdist < 5.0):
            base.camera.setPos(base.camera.getPos() - camvec*(5-camdist))
            camdist = 5.0

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        self.floater.setPos(self.mainChar.getPos())
        self.floater.setZ(self.mainChar.getZ() + 2.0)
        base.camera.lookAt(self.floater)

        return task.cont

    def startConnection(self):
        """Create a connection to the remote host.

        If a connection cannot be created, it will ask the user to perform
        additional retries.

        """
        if self.cManager.connection == None:
            if not self.cManager.startConnection():
                return False

        return True

    def message(self, task):
        # hide all chatboxes
        if self.keyMap["chat0"] != 0:
            if self.chatbox.getVisible() is False:
                self.chatbox.setVisible(True)
                self.chatbox.show(0)
            else:
                self.chatbox.setVisible(False)
                self.chatbox.hide()
            self.keyMap["chat0"] = 0
        if self.keyMap["chat1"] != 0:
            if self.chatbox.getVisible() is False:
                self.chatbox.setVisible(True)
                self.chatbox.show(1)
            else:
                self.chatbox.setVisible(False)
                self.chatbox.hide()
            self.keyMap["chat1"] = 0
        if self.keyMap["users"] != 0:
            self.activeUsers.toggle()
            self.keyMap["users"] = 0
        return task.cont

    def updateMove(self, task):
      if self.isMoving == True :
#         moving = self.mainChar.getPos() - self.previousPos
        moving = self.mainChar.getPos();
        self.cManager.sendRequest(Constants.CMSG_MOVE, [moving.getX() ,moving.getY(),moving.getZ(), self.mainChar.getH()])
        #self.cManager.sendRequest(Constants.RAND_FLOAT, 1.0)
        self.previousPos = self.mainChar.getPos()
      return task.again

    def quitGame(self):
      self.cManager.closeConnection()

      sys.exit()
示例#24
0
 def startChat(self, *participants):
     contacts = [x for x in participants]
     new_chat = Chat(self)
     new_chat.save()
     new_chat.add_participants(contacts)
     return new_chat.id
示例#25
0
 def __init__(self, appSettings: AppSettings):
     self.appSettings = appSettings
     self.chat = Chat(appSettings)
     self.database = Database(appSettings.mongoUri)
示例#26
0
class Server:
    def __init__(self, appSettings: AppSettings):
        self.appSettings = appSettings
        self.chat = Chat(appSettings)
        self.database = Database(appSettings.mongoUri)

    def handleAppMention(self, payload):
        channel = payload["channel"]
        slackId = payload["user"]
        text = payload["text"]

        displayName = self.chat.getDisplayName(slackId)

        user = self.database.findUser(slackId)

        if not user:
            user = self.database.addUser(slackId, displayName)

        if not user:
            return

        self.parseAppMention(text, user)

        #message     = "Hello " + displayName + ", nice to meet you! Use /musicbotinfo to learn more about me!"
        #status      = self.chat.sendMessage     (channel, message)

    def parseAppMention(self, text: str, user: User) -> None:
        tokenCreate = "create list"
        tokenAdd = "add "
        tokenRemove = "remove "
        tokenToList = "to list "
        tokenFromList = "from list "

        tokenIndex = text.find(tokenCreate)

        if tokenIndex != -1:
            listNameIndex = tokenIndex + len(tokenCreate)
            listName = text[listNameIndex:]

            listName = listName.rstrip()
            listName = listName.lstrip()

            listName = listName.lower()

            self.database.addList(user.id, listName)

            return

        list, item = self.getListAndItem(text, tokenAdd, tokenToList)

        if list is not None and item is not None:
            self.database.addItemToList(item, list)

        list, item = self.getListAndItem(text, tokenRemove, tokenFromList)

        if list is not None and item is not None:
            return

    def getListAndItem(self, text: str, tokenFirst: str,
                       tokenSecond: str) -> Tuple[str, str]:
        tokenFirstIndex = text.find(tokenFirst)

        if tokenFirstIndex != -1:
            tokenSecondIndex = text.find(tokenSecond)

            if tokenSecondIndex != -1:
                listName = text[tokenSecondIndex + len(tokenSecond):]
                itemName = text[tokenFirstIndex +
                                len(tokenFirst):tokenSecondIndex - 1]

                listName = listName.rstrip()
                itemName = itemName.rstrip()

                return listName, itemName

        return None, None
示例#27
0
    def disconnect(self):
        self.connection.close()

    def receive_message(self, message):
        chat.DisplayMsgToUser(message)

    def send_payload(self, data):
        # TODO: Handle sending of a payload
        sendMsg = json.dumps(data)
        rawSendMsg = sendMsg.encode()
        self.connection.send(rawSendMsg)

    def set_Chat(self, chat):
        self.Chat = chat


if __name__ == '__main__':
    """
    This is the main method and is executed when you type "python Client.py"
    in your terminal.

    No alterations are necessary
    """

    client = Client('localhost', 9998)
    chat = Chat(client)
    client.set_Chat(chat)
    chat.start()
    while True:
        pass
from Chat import Chat
import os
import socket

if os.name != "nt":
    import fcntl
    import struct

    def get_interface_ip(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack("256s", ifname[:15]))[20:24])


def get_lan_ip():
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = ["eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0"]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break
            except IOError:
                pass
    return ip


chat = Chat(get_lan_ip())
chat.run()
示例#29
0
 def addChat_id(self, chatid):
     if (self.chatList.__contains__(chatid) == False):
         self.chatList.append(chatid)
         chat = Chat()
         chat.chat_id = chatid
         self.lista_chat.append(chat)
示例#30
0
class SharedData(metaclass=Singleton):
    def __init__(self):
        print("Shared Data initializing....", end="")
        self._online = {}
        self._players = {}
        self._all_ufos = {}
        self._all_bases = {}
        self._sessions = {}
        self._chat = Chat()
        self._map = Map(1, 1)
        self._log = Logger('XFF', 'SharedData')
        self._map_actions = {}
        self._skill_queues = []

        self._loop = GeoLoop()
        self.organizations = {}
        self.NPCs = {}
        self.havens = {}

        self.mongo_helper = mongohelper.MongoHelper()
        # Populate UFOs collection with default objects
        if config.BACKSERVER_POPULATE_MONGO:
            self.mongo_helper.add_ufo(UFOs.Probe())
            self.mongo_helper.add_ufo(UFOs.SmallScout())
            self.mongo_helper.add_ufo(UFOs.MediumScout())
            self.mongo_helper.add_ufo(UFOs.LargeScout())
            self.mongo_helper.add_site(GroundSite.BasicSectoidOperation())

        # Load Collections from Mongo
        self._ufos = self.mongo_helper.get_all_ufos()
        self._sites = self.mongo_helper.get_all_sites()

        print("OK")

    def is_online(self, session_id):
        return session_id in self._online

    def add_online(self, session_id):
        if session_id not in self._online:
            self._online[session_id] = None

    def get_online(self, session_id):
        if session_id not in self._online:
            return None
        else:
            return self._online[session_id]

    def add_action(self, action):
        self._loop.actions.append(action)

    def start_loop(self):
        self._loop.start_loop()

    def add_base(self, b):
        self._all_bases[b.id] = b
        self._map.DefaultSector.add_object(b.map_object)

    def get_default_sector(self):
        return self._map.DefaultSector

    def remove_ufo(self, ufo_id):
        del self._all_ufos[ufo_id]

    def get_online_player(self, session_id):
        if self.is_online(session_id) and self._online[session_id]:
            return self._players[self._online[session_id]]
        return None

    def add_online_player(self, session_id, player):
        self._online[session_id] = player.Token
        self._players[player.Token] = player
        self._chat.subscribe_player_to_channel(player, "local")

    def get_map_object_by_id(self, object_id):
        if object_id in self._map.DefaultSector.objects:
            return self._map.DefaultSector.objects[object_id]
        else:
            return None

    def get_all_map_objects_json(self):
        return self._map.DefaultSector.get_objects_on_map_json()

    def get_players_on_channel(self, channel):
        return self._chat.Channels2Players[channel]

    def get_player_by_token(self, token_id):
        if token_id in self._players:
            return self._players[token_id]
        else:
            return None

    def send_message(self, player, channel, message):
        self._chat.send_message(player, channel, message)

    def get_base(self, base_id):
        if base_id in self._all_bases:
            return self._all_bases[base_id]
        else:
            return None

    def get_combat_site(self, site_id):
        if site_id in self._all_ufos:
            return self._all_ufos[site_id]
        else:
            return None

    def spawn_combat_sites(self, site_constructor):
        probability = random.randint(0, config.EVENTS_MAX_PROBABILITY)
        sites = [e for e in self._sites if e['probability'] > probability]
        for u in sites:
            site = site_constructor(u, SharedData().get_default_sector())
            self._all_ufos[site.map_object.id] = site

    def save_organization(self, o):
        self.mongo_helper.save_organization(o)

    def save_npc_character(self, npc):
        self.mongo_helper.save_npc_character(npc)

    def save_haven(self, haven):
        self.mongo_helper.save_haven(haven)
示例#31
0
    def receive(self):
        while self.running:
            data, address = self.s.recvfrom(BUFFER)

            # if there is data
            if data:
                message = data.decode().split()
                action = message[0]

                # update player count
                if action == 'PLAYERS_READY':
                    self.player_count = int(message[1])

                # check name availability
                if action == 'CHECK_NAME':
                    if message[1] == 'taken':
                        self.name_available = False
                    elif message[1] == 'free':
                        self.name_available = True

                # instantiate all the players in the arena
                elif action == 'START_GAME':
                    if not self.initialized:
                        message.pop(0)
                        message = ' '.join(message)
                        data = json.loads(message)

                        self.players = {}
                        for key, value in data.items():
                            n = key
                            x = float(value['xPos'])
                            y = float(value['yPos'])
                            d = value['direc']
                            h = float(value['health'])
                            w = int(value['walk_c'])
                            m = value['move']
                            pos = [x, y]
                            char = value['character']
                            a = 'alive'

                            if char == MARIO:
                                player = Mario(self, self.curr_player, n, a, h,
                                               pos, d, w, m)
                            elif char == LUIGI:
                                player = Luigi(self, self.curr_player, n, a, h,
                                               pos, d, w, m)
                            elif char == YOSHI:
                                player = Yoshi(self, self.curr_player, n, a, h,
                                               pos, d, w, m)
                            elif char == POPO:
                                player = Popo(self, self.curr_player, n, a, h,
                                              pos, d, w, m)
                            elif char == NANA:
                                player = Nana(self, self.curr_player, n, a, h,
                                              pos, d, w, m)
                            elif char == LINK:
                                player = Link(self, self.curr_player, n, a, h,
                                              pos, d, w, m)

                            self.players[n] = player
                            self.all_sprites.add(player)
                            if self.curr_player != n:
                                self.enemy_sprites.add(player)

                        self.chat_messages.append(
                            '============ GAME START ============')
                        self.chat_messages.append(
                            'Best of luck - may the best player win!')
                        self.chat_messages.append(
                            '======================================')
                        self.status = GAME
                        self.playing = True
                        self.initialized = True

                elif action == 'RESTART_GAME':
                    message.pop(0)
                    message = ' '.join(message)
                    data = json.loads(message)

                    self.players = {}
                    self.enemy_sprites = pg.sprite.Group()
                    self.all_sprites = pg.sprite.Group()
                    self.platforms = pg.sprite.Group()
                    self.loadPlatforms()

                    for key, value in data.items():
                        n = key
                        x = float(value['xPos'])
                        y = float(value['yPos'])
                        d = value['direc']
                        h = float(value['health'])
                        w = int(value['walk_c'])
                        m = value['move']
                        pos = [x, y]
                        char = value['character']
                        a = 'alive'

                        if char == MARIO:
                            player = Mario(self, self.curr_player, n, a, h,
                                           pos, d, w, m)
                        elif char == LUIGI:
                            player = Luigi(self, self.curr_player, n, a, h,
                                           pos, d, w, m)
                        elif char == YOSHI:
                            player = Yoshi(self, self.curr_player, n, a, h,
                                           pos, d, w, m)
                        elif char == POPO:
                            player = Popo(self, self.curr_player, n, a, h, pos,
                                          d, w, m)
                        elif char == NANA:
                            player = Nana(self, self.curr_player, n, a, h, pos,
                                          d, w, m)
                        elif char == LINK:
                            player = Link(self, self.curr_player, n, a, h, pos,
                                          d, w, m)

                        self.players[n] = player
                        self.all_sprites.add(player)
                        if self.curr_player != n:
                            self.enemy_sprites.add(player)

                    self.showed_end = False
                    self.restart_request = False

                    self.chat_messages = []
                    self.chat_messages.append(
                        '=========== GAME RESTART ===========')
                    self.chat_messages.append(
                        'Best of luck - may the best player win!')
                    self.chat_messages.append(
                        '======================================')

                    # reset some game variables
                    self.status = GAME
                    self.playing = True
                    self.initialized = True

                elif action == 'JOIN_CHAT':
                    if not self.created_chat:
                        self.chat = Chat(self)
                        try:
                            self.chat.connectToLobby(message[1],
                                                     self.curr_player)
                            self.chat_thread = Thread(
                                target=self.chat.receiveMessages)
                            self.chat_thread.daemon = True
                            self.chat_thread.start()
                        except:
                            self.chat_messages.append(
                                'CHAT ERROR! Server might be down!')
                            print('CHAT ERROR! Server might be down!')
                        self.created_chat = True

                elif action == 'CHECK_DISCONNECT':
                    if len(message) > 1:
                        if message[1] in self.players:
                            if self.playing:
                                self.all_sprites.remove(
                                    self.players[message[1]])
                                self.enemy_sprites.remove(
                                    self.players[message[1]])
                                self.players.pop(message[1])

                elif action == 'QUIT_GAME':
                    # reset game variables
                    self.status = INTRO
                    self.playing = False
                    self.all_ready = False
                    self.showed_end = False
                    self.initialized = False
                    self.created_chat = False
                    self.name_available = True
                    self.restart_request = False
                    self.player_count = 0
                    self.players = {}

                    # reset player variables
                    self.curr_player = ''
                    self.chat_text = ''
                    self.chatting = False
                    self.chat_once = False
                    self.chat_init = False
                    self.chat_messages = []

                    # reset sprite groups
                    self.enemy_sprites = pg.sprite.Group()
                    self.all_sprites = pg.sprite.Group()
                    self.platforms = pg.sprite.Group()
                    self.loadPlatforms()

                elif action == 'CHECK_WINNER':
                    self.winner = message[1]

                elif action == 'CHECK_READY':
                    if message[1] == 'TRUE':
                        self.all_ready = True
                    elif message[1] == 'FALSE':
                        self.all_ready = False

                elif action == 'UPDATE_ALL_PLAYERS':
                    message.pop(0)
                    message = ' '.join(message)
                    data = json.loads(message)

                    if (len(data) != len(self.players)):
                        continue

                    for player in self.players.values():
                        name = player.name
                        status = data[name]['status']
                        health = float(data[name]['health'])
                        xPos = float(data[name]['xPos'])
                        yPos = float(data[name]['yPos'])
                        direc = data[name]['direc']
                        walk_c = int(data[name]['walk_c'])
                        move = data[name]['move']

                        player.status = status
                        player.health = health
                        player.pos = [xPos, yPos]
                        player.direc = direc
                        player.walk_c = walk_c
                        player.move = move
示例#32
0
class Game:
    # ========================= IMPORTANT METHODS =========================
    def __init__(self):

        # initialize
        pg.init()
        pg.mixer.init()
        pg.display.set_caption(TITLE)
        pg.display.set_icon(ICON)

        # game variables
        self.screen = pg.display.set_mode(BG_SIZE)
        self.clock = pg.time.Clock()
        self.status = INTRO
        self.running = True  # game is running
        self.playing = False  # player is inside the arena
        self.all_ready = False  # checks if everyone is ready
        self.showed_end = False  # checks if end game results have been showed
        self.initialized = False  # initialized game in arena (with players)
        self.created_chat = False  # created chat lobby for everyone to connect
        self.name_available = True  # checks if curr_player text is available
        self.restart_request = False  # checks if player requested for a restart
        self.curr_player = ''  # value during input name screen
        self.player_count = 0  # for the ready screen

        # converted background images for optimized game loop
        self.arena_bg = ARENA_BG.convert()
        self.chat_bg = CHAT_BG.convert()

        # chat variables
        self.chat_text = ''
        self.chatting = False
        self.chat_once = False
        self.chat_init = False
        self.chat_messages = []

        # socket to UDP server
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # multiple threads for the game and chat (chat is in join game)
        self.game_thread = Thread(target=self.receive)
        self.game_thread.daemon = True
        self.game_thread.start()

    def run(self):
        # check for the current menu depending on the status
        while True:
            if self.status == INTRO:
                Intro(self)

            elif self.status == START:
                Start(self)

            elif self.status == GUIDE:
                Other(self, GUIDE, GUIDE_BG)

            elif self.status == ABOUT:
                Other(self, ABOUT, ABOUT_BG)

            elif self.status == GAME:
                self.winner = ''

                if self.initialized and self.playing:
                    self.checkDisconnect()
                    self.checkWinner()
                    self.updateAllPlayers()

                self.clock.tick(FPS)
                self.events()
                self.update()
                self.draw()

    def new(self):
        # the players will be added after starting the game
        # see startGame() below

        self.enemy_sprites = pg.sprite.Group()
        self.all_sprites = pg.sprite.Group()
        self.platforms = pg.sprite.Group()

        self.loadPlatforms()
        self.run()

    def loadPlatforms(self):
        base = Platform('floor', 0, HEIGHT - 30, GAME_WIDTH, 30)
        self.all_sprites.add(base)
        self.platforms.add(base)

        plat1 = Platform('platform', 60, 460, 200, 50)
        self.all_sprites.add(plat1)
        self.platforms.add(plat1)

        plat2 = Platform('platform', 435, 460, 200, 50)
        self.all_sprites.add(plat2)
        self.platforms.add(plat2)

        plat3 = Platform('platform', 250, 260, 200, 50)
        self.all_sprites.add(plat3)
        self.platforms.add(plat3)

    def events(self):
        try:
            keys = pg.key.get_pressed()

            # once player enters game screen - show initial chat
            if not self.chat_init:
                self.chat_text = '<Enter> disables movement!'
                self.chat_init = True

            for event in pg.event.get():
                # check for closing window
                if event.type == pg.QUIT:
                    print("You quit in the middle of the game!")
                    self.disconnectPlayer(self.curr_player,
                                          self.restart_request)

                    if self.playing:
                        self.playing = False

                    self.running = False
                    self.s.close()
                    quit()

                # majority of chat flow + attacks
                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_z:
                        self.players[self.curr_player].weakAttack()

                    elif event.key == pg.K_x:
                        self.players[self.curr_player].heavyAttack()

                    if event.key == pg.K_RETURN:
                        if not self.chatting:
                            self.chatting = True

                            # first enter will replace default text
                            self.chat_once = True
                            self.chat_text = 'Type here!'

                        elif self.chatting:
                            self.chatting = False

                            # send message to server and replace with default text
                            try:
                                self.chat.chatInLobby(self.chat_text)
                            except:
                                self.chat_messages.append(
                                    'CHAT ERROR! Server might be down!')
                                print('CHAT ERROR! Server might be down!')
                            self.chat_text = '<Enter> disables movement!'

                    elif not self.chatting and event.key == pg.K_r:
                        if self.showed_end:
                            if not self.restart_request:
                                self.restartRequest()
                                self.restart_request = True
                                self.chat_messages.append(
                                    'You sent a restart request!')

                    elif not self.chatting and event.key == pg.K_m:
                        if self.showed_end:
                            self.quitGame()

                    elif not self.chatting and event.key == pg.K_q:
                        if self.showed_end:
                            print("Thank you for playing!")
                            self.disconnectPlayer(self.curr_player,
                                                  self.restart_request)
                            self.running = False
                            self.s.close()
                            pg.quit()
                            quit()

                    else:
                        if self.chatting:
                            if self.chat_once:
                                self.chat_once = False
                                self.chat_text = ''

                            # maximum message length is 22 to fit the screen
                            if len(self.chat_text) <= 22:
                                char = event.unicode
                                self.chat_text += char

            if keys[pg.K_BACKSPACE]:

                # self.chat_once just clears 'Type here!' after initial type
                if self.chatting:
                    if self.chat_once:
                        self.chat_once = False
                        self.chat_text = ''
                    else:
                        self.chat_text = self.chat_text[:-1]

        except:
            quit()

    def update(self):
        try:
            self.all_sprites.update()
        except:
            quit()

    # for consistently drawing the background and the sprites
    def draw(self):
        try:
            # show the background
            self.screen.blit(self.arena_bg, ORIGIN)
            self.screen.blit(self.chat_bg, (700, 0))

            # check method below
            self.drawStatsBoard()

            # show all the sprites
            self.all_sprites.draw(self.screen)

            # write the player's name on top of the sprite
            font = pg.font.Font(None, 20)
            for player in self.players.values():
                coors = (player.rect.left, player.rect.top - 15)
                text_surface = font.render((player.name), True, WHITE)
                self.screen.blit(text_surface, coors)

            # show end game results
            if len(self.winner) > 0 and not self.showed_end:
                self.initialized = False
                self.playing = False

                self.chat_messages = []
                self.chat_messages.append(
                    '===== {} won this round! ====='.format(self.winner))
                self.chat_messages.append("-> Press R to restart the game")
                self.chat_messages.append(
                    '   * Everyone must press R to restart')
                self.chat_messages.append('')
                self.chat_messages.append(
                    '-> Press M to go back to the main menu')
                self.chat_messages.append(
                    '   * ONE press of M will put EVERYONE back')
                self.chat_messages.append('')
                self.chat_messages.append('-> Press Q to exit the game')
                self.chat_messages.append('   * We hope you enjoyed playing!')
                self.chat_messages.append(
                    '======================================')

                self.showed_end = True

            # show the input chat
            font = pg.font.Font(None, 30)
            text_surface = font.render(self.chat_text, True, WHITE)
            self.screen.blit(text_surface, (760, 644))

            # show all the messages
            font2 = pg.font.Font(None, 24)
            for i in range(0, len(self.chat_messages)):
                text_surface2 = font2.render(self.chat_messages[i], True,
                                             BLACK)
                self.screen.blit(text_surface2, (730, 95 + (i * 25)))

            pg.display.flip()

        except:
            quit()

    # board with the players' name and life
    def drawStatsBoard(self):
        font = pg.font.Font(None, 22)
        text = font.render('Player - Life', True, WHITE)
        pg.draw.rect(self.screen, BLACK, (10, 10, 140, 20))
        pg.draw.rect(self.screen, GRAY, (10, 30, 140, 30 * len(self.players)))
        self.screen.blit(text, (37, 12))

        i = 0
        for player in self.players.values():
            name = player.name
            stats = name + ' - ' + str(int(player.health))
            diff = 10 - len(player.name)

            # color text according to player's health
            if player.health > 60:
                text = font.render(stats, True, GREEN)
            elif player.health <= 60 and player.health > 20:
                text = font.render(stats, True, ORANGE)
            elif player.health <= 20 and player.health > 0:
                text = font.render(stats, True, RED)
            elif player.health == 0:
                text = font.render(stats, True, BLACK)

            self.screen.blit(text, (12 + (diff * 5), 40 + (i * 30)))
            i += 1

    # ========================= DATA TO AND FROM SERVER =========================
    def receive(self):
        while self.running:
            data, address = self.s.recvfrom(BUFFER)

            # if there is data
            if data:
                message = data.decode().split()
                action = message[0]

                # update player count
                if action == 'PLAYERS_READY':
                    self.player_count = int(message[1])

                # check name availability
                if action == 'CHECK_NAME':
                    if message[1] == 'taken':
                        self.name_available = False
                    elif message[1] == 'free':
                        self.name_available = True

                # instantiate all the players in the arena
                elif action == 'START_GAME':
                    if not self.initialized:
                        message.pop(0)
                        message = ' '.join(message)
                        data = json.loads(message)

                        self.players = {}
                        for key, value in data.items():
                            n = key
                            x = float(value['xPos'])
                            y = float(value['yPos'])
                            d = value['direc']
                            h = float(value['health'])
                            w = int(value['walk_c'])
                            m = value['move']
                            pos = [x, y]
                            char = value['character']
                            a = 'alive'

                            if char == MARIO:
                                player = Mario(self, self.curr_player, n, a, h,
                                               pos, d, w, m)
                            elif char == LUIGI:
                                player = Luigi(self, self.curr_player, n, a, h,
                                               pos, d, w, m)
                            elif char == YOSHI:
                                player = Yoshi(self, self.curr_player, n, a, h,
                                               pos, d, w, m)
                            elif char == POPO:
                                player = Popo(self, self.curr_player, n, a, h,
                                              pos, d, w, m)
                            elif char == NANA:
                                player = Nana(self, self.curr_player, n, a, h,
                                              pos, d, w, m)
                            elif char == LINK:
                                player = Link(self, self.curr_player, n, a, h,
                                              pos, d, w, m)

                            self.players[n] = player
                            self.all_sprites.add(player)
                            if self.curr_player != n:
                                self.enemy_sprites.add(player)

                        self.chat_messages.append(
                            '============ GAME START ============')
                        self.chat_messages.append(
                            'Best of luck - may the best player win!')
                        self.chat_messages.append(
                            '======================================')
                        self.status = GAME
                        self.playing = True
                        self.initialized = True

                elif action == 'RESTART_GAME':
                    message.pop(0)
                    message = ' '.join(message)
                    data = json.loads(message)

                    self.players = {}
                    self.enemy_sprites = pg.sprite.Group()
                    self.all_sprites = pg.sprite.Group()
                    self.platforms = pg.sprite.Group()
                    self.loadPlatforms()

                    for key, value in data.items():
                        n = key
                        x = float(value['xPos'])
                        y = float(value['yPos'])
                        d = value['direc']
                        h = float(value['health'])
                        w = int(value['walk_c'])
                        m = value['move']
                        pos = [x, y]
                        char = value['character']
                        a = 'alive'

                        if char == MARIO:
                            player = Mario(self, self.curr_player, n, a, h,
                                           pos, d, w, m)
                        elif char == LUIGI:
                            player = Luigi(self, self.curr_player, n, a, h,
                                           pos, d, w, m)
                        elif char == YOSHI:
                            player = Yoshi(self, self.curr_player, n, a, h,
                                           pos, d, w, m)
                        elif char == POPO:
                            player = Popo(self, self.curr_player, n, a, h, pos,
                                          d, w, m)
                        elif char == NANA:
                            player = Nana(self, self.curr_player, n, a, h, pos,
                                          d, w, m)
                        elif char == LINK:
                            player = Link(self, self.curr_player, n, a, h, pos,
                                          d, w, m)

                        self.players[n] = player
                        self.all_sprites.add(player)
                        if self.curr_player != n:
                            self.enemy_sprites.add(player)

                    self.showed_end = False
                    self.restart_request = False

                    self.chat_messages = []
                    self.chat_messages.append(
                        '=========== GAME RESTART ===========')
                    self.chat_messages.append(
                        'Best of luck - may the best player win!')
                    self.chat_messages.append(
                        '======================================')

                    # reset some game variables
                    self.status = GAME
                    self.playing = True
                    self.initialized = True

                elif action == 'JOIN_CHAT':
                    if not self.created_chat:
                        self.chat = Chat(self)
                        try:
                            self.chat.connectToLobby(message[1],
                                                     self.curr_player)
                            self.chat_thread = Thread(
                                target=self.chat.receiveMessages)
                            self.chat_thread.daemon = True
                            self.chat_thread.start()
                        except:
                            self.chat_messages.append(
                                'CHAT ERROR! Server might be down!')
                            print('CHAT ERROR! Server might be down!')
                        self.created_chat = True

                elif action == 'CHECK_DISCONNECT':
                    if len(message) > 1:
                        if message[1] in self.players:
                            if self.playing:
                                self.all_sprites.remove(
                                    self.players[message[1]])
                                self.enemy_sprites.remove(
                                    self.players[message[1]])
                                self.players.pop(message[1])

                elif action == 'QUIT_GAME':
                    # reset game variables
                    self.status = INTRO
                    self.playing = False
                    self.all_ready = False
                    self.showed_end = False
                    self.initialized = False
                    self.created_chat = False
                    self.name_available = True
                    self.restart_request = False
                    self.player_count = 0
                    self.players = {}

                    # reset player variables
                    self.curr_player = ''
                    self.chat_text = ''
                    self.chatting = False
                    self.chat_once = False
                    self.chat_init = False
                    self.chat_messages = []

                    # reset sprite groups
                    self.enemy_sprites = pg.sprite.Group()
                    self.all_sprites = pg.sprite.Group()
                    self.platforms = pg.sprite.Group()
                    self.loadPlatforms()

                elif action == 'CHECK_WINNER':
                    self.winner = message[1]

                elif action == 'CHECK_READY':
                    if message[1] == 'TRUE':
                        self.all_ready = True
                    elif message[1] == 'FALSE':
                        self.all_ready = False

                elif action == 'UPDATE_ALL_PLAYERS':
                    message.pop(0)
                    message = ' '.join(message)
                    data = json.loads(message)

                    if (len(data) != len(self.players)):
                        continue

                    for player in self.players.values():
                        name = player.name
                        status = data[name]['status']
                        health = float(data[name]['health'])
                        xPos = float(data[name]['xPos'])
                        yPos = float(data[name]['yPos'])
                        direc = data[name]['direc']
                        walk_c = int(data[name]['walk_c'])
                        move = data[name]['move']

                        player.status = status
                        player.health = health
                        player.pos = [xPos, yPos]
                        player.direc = direc
                        player.walk_c = walk_c
                        player.move = move

    # ========================= METHODS TO MAKE REQUESTS TO SERVER =========================
    def send(self, message):
        self.s.sendto(str.encode(message), SERVER)

    def connectPlayer(self, name):
        message = 'CONNECT '
        message += name
        self.send(message)

    def disconnectPlayer(self, name, restarted):
        message = 'DISCONNECT '
        message += name
        if restarted:
            message += ' TRUE'
        else:
            message += ' FALSE'
        self.send(message)

    def checkDisconnect(self):
        message = 'CHECK_DISCONNECT'
        self.send(message)

    def checkName(self, name):
        message = 'CHECK_NAME '
        message += name
        self.send(message)

    def editPlayerName(self, old_name, new_name):
        message = 'EDIT_NAME '
        message += old_name + ' ' + new_name
        self.send(message)

    def editPlayerCharacter(self, name, character):
        message = 'EDIT_CHARACTER '
        message += name + ' ' + character
        self.send(message)

    def editPlayerStatus(self, name, status):
        message = 'EDIT_STATUS '
        message += name + ' ' + status
        self.send(message)

    def startGame(self):
        message = 'START_GAME'
        self.send(message)

    def updatePlayer(self):
        message = 'UPDATE_PLAYER '
        player = self.players[self.curr_player]
        data = {
            'name': player.name,
            'status': player.status,
            'health': str(player.health),
            'xPos': str(player.pos[0]),
            'yPos': str(player.pos[1]),
            'direc': player.direc,
            'walk_c': str(player.walk_c),
            'move': player.move
        }
        message += json.dumps(data)
        self.send(message)

    def updateAllPlayers(self):
        message = 'UPDATE_ALL_PLAYERS'
        self.send(message)

    def attackPlayer(self, player, damage, move):
        message = 'ATTACK_PLAYER '
        message += player + ' ' + str(damage) + ' ' + move
        self.send(message)

    def restartRequest(self):
        message = 'RESTART_REQUEST'
        self.send(message)

    def quitGame(self):
        message = 'QUIT_GAME'
        self.send(message)

    def checkWinner(self):
        message = 'CHECK_WINNER'
        self.send(message)
示例#33
0
文件: World.py 项目: jaimodha/MMOG
    def __init__(self):

        __builtin__.main = self
        self.cManager = ConnectionManager()
        self.startConnection()
        self.taskMgr = taskMgr
        self.base = base

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0
        }

        self.characters = dict()
        self.cpList = dict()

        base.win.setClearColor(Vec4(0, 0, 0, 1))

        #self.environ = loader.loadModel("models/world")
        self.environ = loader.loadModel("models/land")
        """
        self.swordLeft = loader.loadModel("models/Sword_Left")
        self.swordRight = loader.loadModel("models/Sword_Right")  
        self.shieldLeft = loader.loadModel("models/Shield_Left")  
        self.shieldRight = loader.loadModel("models/Shield_Right")  
        self.money = loader.loadModel("models/Money")
        """

        self.left_atk_tower = loader.loadModel("models/attack_tower")
        self.left_def_tower = loader.loadModel("models/defense_tower")
        self.right_atk_tower = loader.loadModel("models/attack_tower")
        self.right_def_tower = loader.loadModel("models/defense_tower")
        self.money_cp = loader.loadModel("models/money_point")

        self.left_atk_tower.setPos(141.016, 0.440607, 0)
        self.left_def_tower.setPos(210.984, 115.005, 0)
        self.right_atk_tower.setPos(-149.953, 0.674369, 0)
        self.right_def_tower.setPos(-210.771, 113.753, 0)
        self.money_cp.setPos(-0.903916, 11.3765, 0)

        self.left_atk_tower.setScale(2.0)
        self.right_atk_tower.setScale(2.0)
        self.left_def_tower.setScale(2.0)
        self.right_def_tower.setScale(2.0)
        self.money_cp.setScale(2.0)

        self.left_atk_tower.reparentTo(render)
        self.right_atk_tower.reparentTo(render)
        self.left_def_tower.reparentTo(render)
        self.right_def_tower.reparentTo(render)
        self.money_cp.reparentTo(render)

        self.environ.reparentTo(render)
        """
        self.swordLeft.reparentTo(render)
        self.swordRight.reparentTo(render)
        self.shieldLeft.reparentTo(render)
        self.shieldRight.reparentTo(render)
        self.money.reparentTo(render)
        """

        self.environ.setPos(0, 0, 0)
        self.environ.setH(90)
        """
        self.swordLeft.setH(90)
        self.swordRight.setH(90)
        self.shieldLeft.setH(90)
        self.shieldRight.setH(90)
        self.money.setH(90)
        """

        mySound = loader.loadSfx("sound/Retribution.mp3")
        mySound.setLoop(True)
        mySound.play()

        fp = FilterProperties()
        #fp.addReverb(0.6, 0.5, 0.1, 0.1, 0.1)
        base.sfxManagerList[0].configureFilters(fp)

        ## swordsmanStartPos = self.environ.find("**/start_point").getPos()
        ## self.player = Swordsman("Swordsman", 0)
        ## self.player._character.reparentTo(render)
        ## self.player._character.setScale(.1)
        ## self.player._character.setPos(swordsmanStartPos)
        ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10)
        ## self.player._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY(),swordsmanStartPos.getZ())
        ## self.initx = swordsmanStartPos.getX()

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        ## self.characters["Axeman"] = Axeman("Axeman", 1)
        ## self.characters["Axeman"]._character.reparentTo(render)
        ## self.characters["Axeman"]._character.setScale(.1)
        ## self.characters["Axeman"]._character.setPos(swordsmanStartPos)
        ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10)
        ## self.characters["Axeman"]._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY() - 10,swordsmanStartPos.getZ())
        ## self.characters["Axeman"]._character.loop("idle")

        self.accept("a", self.setKey, ["left", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("mouse1", self.attack, [3])
        self.accept("mouse3", self.attack, [4])

        self.username = str(raw_input("Username: "******"Type: ")
        faction = input("Faction: ")
        self.cManager.sendRequest(Constants.CMSG_AUTH,
                                  [self.username, type, faction])

        #taskMgr.add(self.move,"moveTask")
        taskMgr.doMethodLater(.10, self.refresh, "heartbeat")

        base.disableMouse()
        #base.camera.setPos(self.player._character.getX(),self.player._character.getY()+10,2)

        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))

        directionalLight2 = DirectionalLight("directionalLight2")
        directionalLight2.setDirection(Vec3(5, 5, 5))
        directionalLight2.setColor(Vec4(1, 1, 1, 1))
        directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1))

        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
        render.setLight(render.attachNewNode(directionalLight2))

        Chat(self.cManager)

        # Create control points
        self.cpList[1] = ControlPoint(1, 210.984, 115.005, -5, 10, RED)
        self.cpList[2] = ControlPoint(2, 141.016, 0.440607, -5, 10, RED)
        self.cpList[3] = ControlPoint(3, -0.903916, 11.3765, -2, 10, RED)
        self.cpList[4] = ControlPoint(4, -210.771, 113.753, -2, 10, BLUE)
        self.cpList[5] = ControlPoint(5, -149.953, 0.674369, -2, 10, BLUE)

        # Create the control point Bar UI
        self.cp_bar = ControlPointBar()
        # self.resource_bar = ResourceBar()

        taskMgr.doMethodLater(0.1, self.refresh, "heartbeat")
        taskMgr.doMethodLater(1, self.CPHandler, "CPHandler")
        taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler')
        '''NPC Code Additions'''
        #self.isChased =[False,False]
        #self.npcList = [0,0]
        self.isChased = False
        self.npcList = 0
        self.controlNpc = NPCController(render)
        taskMgr.add(self.taskAIUpdate, "AIUpdate")
        taskMgr.add(self.moveNpc, "Move")