示例#1
0
    def getLobbies(self):
        HOST, PORT = "localhost", 9999
        data = networking.DataFrame(networking.Header(
            1, "fetchLobbies")).toString()

        # Create a socket (SOCK_STREAM means a TCP socket)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            # Connect to server and send data
            sock.connect((HOST, PORT))
            sock.sendall(data + "\n")

            # Receive data from the server and shut down
            received = sock.recv(1024)
        finally:
            sock.close()
        received = ast.literal_eval(received)
        self.lobbies = []
        if received["header"]["reqtype"] == "sendLobbies":
            i = 0
            for x in received["data"]["lobbies"]:
                x = ast.literal_eval(x)
                l = lobby.Lobby(x["id"], x["name"], self.challenge, x["id"])
                l.setRect(pygame.Rect(0, i * 100, 600, 100))
                self.lobbies.append(l)
                i += 1
            self.error = False
        else:
            self.error = True
示例#2
0
 def __init__(self, ID, Group, ClassServer, GroupConfig, AccountConfig):
     threading.Thread.__init__(self)
     self.ID = ID
     self.Server = ClassServer
     self.Debug = ClassServer.Debug
     self.Debug('INFO', 'Host Init')
     self.Group = Group
     self.GroupConfig = GroupConfig
     self.LogicTest = self.Server.LogicTest
     self.SpringVersion = self.GetSpringVersion()
     self.Lobby = lobby.Lobby(
         self.Debug, self.HandleInput, self.HandleEvent,
         self.HandleLocalEvent,
         dict(
             AccountConfig, **{
                 'LobbyHost': ClassServer.Config['General']['LobbyHost'],
                 'LobbyPort': ClassServer.Config['General']['LobbyPort']
             }))
     self.HostCmds = hostCmds.HostCmds(ClassServer, self)
     self.Spring = spring.Spring(ClassServer, self, self.Lobby,
                                 AccountConfig['UDPPort'])
     self.UserRoles = {}  # [User][Role] = 1
     self.Battle = {
         'Mod': self.GroupConfig['Mod'],
         'Map': self.GroupConfig['Map'],
         'BattleDescription': self.GroupConfig['BattleDescription'],
         'StartPosType': None,
         'MapOptions': {},
         'ModOptions': {},
         'Teams': 2,
     }
     self.CommandThreads = {}
     self.CommandThreadID = 0
     self.CommandSeen = {}
     self.IsMaster = False
示例#3
0
 def addUser(self, user):
     createdLobby = self.getNotFilledLobby()
     if createdLobby is None:
         createdLobby = lobby.Lobby(user)
         createdLobby.onEnd = self.onLobbyEnd
         self.lobbies.append(createdLobby)
         return
     createdLobby.adduser(user)
示例#4
0
 def __init__(self, ClassServer):
     threading.Thread.__init__(self)
     self.Server = ClassServer
     self.Debug = ClassServer.Debug
     self.Debug('Master Init')
     self.Lobby = lobby.Lobby(ClassServer, self.HandleInput,
                              self.HandleEvent,
                              ClassServer.Config['MainAccount'])
	def __init__ (self):
		self.Lobby = lobby.Lobby (self.Debug, self.Debug, self.Debug, self.Debug, {})
		self.Balance = hostCmdsBattleBalance.HostCmdsBattleBalance (self, self.Lobby, self)
		self.Logic = hostCmdsBattleLogic.HostCmdsBattleLogic (self, self.Lobby, self)
		self.Balance.DebugBalanceFunction = self.DisplayBalance
		self.Battle = {'Teams':0}
		self.Lobby.BattleID = 1
		self.Lobby.Battles = {self.Lobby.BattleID:{}}
		self.SetData ()
		self.Balance.LogicBalance ()
示例#6
0
	def __init__ (self, ClassServer, Group, HostAccount):
		threading.Thread.__init__ (self)
		self.Server = ClassServer
		self.Debug = ClassServer.Debug
		self.Debug ('Host Init')
		self.Lobby = lobby.Lobby (ClassServer, self.HandleInput, self.HandleEvent, HostAccount)
		self.Group = Group
		self.HostCmds = hostCmds.HostCmds (ClassServer, self)
		self.Spring = spring.Spring (ClassServer, self.Lobby)
		self.UserRoles = {}		# [User][Role] = 1
示例#7
0
    def __init__(self):
        ServerIo.__init__(self)
        self.lobbyObj = lobby.Lobby()  # create/use single lobby instance
        self.gameObj = game.Game()  # create/use the single game instance
        self.acctObj = None
        self.charObj = None
        self._area = "server"

        self._debugServer = False  # Turn on/off debug logging
        self._startdate = datetime.now()

        if self._debugServer:
            logger.info(str(self) + " New ClientThread")
示例#8
0
文件: game.py 项目: imStudd/BomberMan
    def _start_game(self):
        self._map = map.Map(self._window, self._map, self._scale, self._effect)

        if self._music:
            pygame.mixer.music.load("ressources/audio/music/game.ogg")
            pygame.mixer.music.play(loops=-1)

        pygame.key.set_repeat(1, 50)
        while self._playing:
            # try:
            self._clock.tick(60)

            if not self._recv_q.empty():
                data = self._recv_q.get()
                self._received_data_proccess(data)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self._send_q.put(("QUT", ""))
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self._send_q.put(("QUT", ""))
                        pygame.quit()
                        quit()
                    if event.key == pygame.K_RETURN:
                        self._send_q.put(("RST", ""))
                    if not self._ended:
                        if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                            self._send_q.put(("MOV", "B"))
                        if event.key == pygame.K_UP or event.key == pygame.K_w or event.key == pygame.K_z:
                            self._send_q.put(("MOV", "T"))
                        if event.key == pygame.K_LEFT or event.key == pygame.K_a or event.key == pygame.K_q:
                            self._send_q.put(("MOV", "L"))
                        if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                            self._send_q.put(("MOV", "R"))
                        if event.key == pygame.K_SPACE:
                            self._send_q.put(("BMB", ""))

            self._map.update()
            self._players_list.update()

            if self._ended:
                self._window.blit(self._winner[0], self._winner[1])

            pygame.display.flip()

        pygame.quit()
        lobby.Lobby(self._send_q, self._recv_q, self._players_data, self._num)
示例#9
0
    def getLobbyData(self):
        cnx = mysql.connector.connect(user="******",
                                      password="******",
                                      host="localhost",
                                      port="8080",
                                      database="teleria")
        c = cnx.cursor()
        payload = ("select id, player1, player2 from lobbies;")
        c.execute(payload)
        chats = {}
        lobbies = []
        for ide, player1, player2 in c:
            if player2 == None:
                lobbies.append((ide, player1))
        players = []
        for x in lobbies:
            payload = ("select username from accounts where id = " +
                       str(x[1]) + ";")
            c.execute(payload)
            for username in c:
                print username
                players.append(username[0])

        l = []
        for x in range(len(lobbies)):
            l.append(lobby.Lobby(lobbies[x][0], players[x]))
        c.close()
        cnx.close()
        print l
        return {
            "lobbyCount":
            len(l),
            "lobbies": [
                x.toString().encode('ascii', 'ignore').replace("'", "")
                for x in l
            ]
        }
示例#10
0
 def __init__(self):
     self.game = game.Game(self)
     self.lobby = lobby.Lobby(self)
     self.reg = Registration()
示例#11
0

def handler(signum, frame):
    for t in threading.enumerate():
        signal.pthread_kill(t.ident, signal.SIGUSR1)
        signal.pthread_kill(t.ident, signal.SIGUSR2)


if __name__ == "__main__":
    if sys.platform == "linux":
        signal.signal(signal.SIGINT, handler)

    send_q = queue.Queue()
    recv_q = queue.Queue()

    menu.Menu(send_q)

    data = send_q.get()

    if len(data) == 2:
        server.Server(data[0])
        send_q.put(("LOG", data[1]))
        client.Client("127.0.0.1", data[0], send_q, recv_q)
    elif len(data) == 3:
        send_q.put(("LOG", data[2]))
        client.Client(data[0], data[1], send_q, recv_q)
    else:
        sys.exit()

    lobby.Lobby(send_q, recv_q)
示例#12
0
	def Start (self):
		self.Debug ('INFO')
		self.Lobby = lobby.Lobby (self.Debug, self.Chat, self.Event, self.Debug, self.Config['General'])
		self.Lobby.start ()
示例#13
0
import deck
import lobby

if __name__ == "__main__":
    deck = deck.Deck()
    lobby = lobby.Lobby()
    while(True):

        deck.shuffle()

        lobby.setDealer()

        lobby.handOut(deck.deck)
        lobby.getWinner()
        
        userInput = input('Type "exit" to stop the game. Insert anything else to continue!')

        if (userInput == "exit"):
            exit()
        
        lobby.gatherCards(deck.deck)
        print(deck)
        print(len(deck.deck))
        print(lobby)

示例#14
0
class BattleshipHandler(BaseHTTPRequestHandler):
    battles = {}
    lobby = lobby.Lobby()

    def htmlThis(self, htmlBody):
        return """<!DOCTYPE html>
			<head>
				<meta charset="utf-8"></meta>
				<title>BLOUBLOU</title>
			</head>
			<body>
			""" + htmlBody + """
			</body>
			</html>
		"""

    def returnHtml(self, htmlStr):
        self.wfile.write(bytes(htmlStr.encode(encoding='utf-8')))

    def do_GET(self):
        path = self.path
        if path == '/grid':
            self.sendGridState()
        elif path == '/players':
            self.sendPlayerList()

    def do_POST(self):
        path = self.path
        self.ok()
        if path == '/join':
            self.lobby.join(self.headers['clientName'])
        elif path == '/request':
            response = self.data()
            fromP = self.player()
            toP = self.player(response.get('name'))
            accept = self.lobby.request(fromP, toP)
            if accept:
                self.battles[(fromP.name,
                              toP.name)] = game.Game(fromP.name, toP.name)
            self.wfile.write(
                json.dumps({
                    'accept': accept
                }).encode(encoding='utf-8'))
        elif path == '/touch':
            cell = self.data()
            battle = self.getGame()
            battle.touch(cell, self.headers['clientName'])
        elif path == '/ready':
            battle = self.getGame()
            battle.readyServer(self.headers['clientName'])

    def player(self, name=None):
        if name == None:
            name = self.headers['clientName']
        return self.lobby.fromName(name)

    def ok(self):
        self.send_response(200)
        self.end_headers()

    def sendGridState(self):
        battle = self.getGame()
        # for t in self.battles:
        # 	if (t[0]==name or t[1]==name) && (!self.battles[t].p1.ready or !self.battles[t].p2.ready): content = {}
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(
            json.dumps(battle.getGridState(
                self.headers['clientName'])).encode(encoding='utf-8'))

    def getGame(self):
        p1 = self.headers['clientName']
        p2 = self.headers['opponent']
        p1p2 = self.battles.get((p1, p2))
        p2p1 = self.battles.get((p2, p1))
        if p1p2:
            return p1p2
        if p2p1:
            return p2p1
        return None

    def sendPlayerList(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        g = self.getGame()
        if g:
            self.wfile.write(
                json.dumps({
                    'players': jsonPlayers(self.getGame().getPlayers())
                }).encode(encoding='utf-8'))
        else:
            self.wfile.write(
                json.dumps({
                    'players':
                    jsonPlayers(
                        self.lobby.getPlayers(self.headers['clientName']))
                }).encode(encoding='utf-8'))

    def data(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        return json.loads(post_data)