示例#1
0
    def __init__(self):
        # tiles and pixels
        self._tile_width = ConstantVariables.TILE_WIDTH
        self._nb_tile_x = ConstantVariables.NB_COLUMN
        self._nb_tile_y = ConstantVariables.NB_ROW
        self._width_px = ConstantVariables.WINDOW_WIDTH
        self._height_px = ConstantVariables.WINDOW_HEIGHT

        # elements
        # screen - textures
        self._screen = pygame.display.set_mode(
            (self._width_px, self._height_px))
        self._background = pygame.image.load('../assets/grass.jpg')
        self._background = pygame.transform.scale(
            self._background, (self._width_px, self._height_px))
        self._apple_image = pygame.image.load('../assets/apple.png')
        self._apple_image = pygame.transform.scale(
            self._apple_image, (self._tile_width, self._tile_width))

        # game
        self._game = GameServer()

        # socket
        self._socket = ClientSocket()

        # other
        self._running = True
        self._my_direction = "not_set"
示例#2
0
    def start(self):
        """ Begins the primary loop for the server."""
        outboundData = {"gameServer host": None, "gameServer port": None}

        counter = 0
        while True:
            # Each time a person joins, iterates over the current list of active games.
            # If any of the games has finished, removes that game and re-opens the port.
            for thread in self.activeGames:
                if thread.isAlive() == False:
                    self.activeGames.remove(thread)

            print("CONNECTOR: Active port number is", self.activePort,
                  "Iteration", counter)
            counter += 1

            print('CONNECTOR: Trying to recieve data...')
            inboundData = self.socket.recvfrom(
                1024)  # Gets bundle of data from clients
            data = inboundData[0]  # Separates data from address
            address = inboundData[1]  # Separates address from data
            data = pickle.loads(data)  # Unpickles data back into a python dict

            print("CONNECTOR: Message:", data, "From:", address)

            self.waitingList.append(address)

            # Creates a new Game server here
            if len(self.waitingList) >= 2:
                print("CONNECTOR: Someone wants to play, creating a game...")
                g = GameServer(self.activePort)  # Creates game
                print(g.start())  # Starts game
                self.activeGames.append(g)  # Adds the game a list

                # Tells the first person to start the game where it's being hosted
                outboundData["gameServer host"] = self.HOST
                outboundData["gameServer port"] = self.activePort

                # Keeps track of how many people have successfully connected
                self.connected += 1
                print(
                    "CONNECTOR: Keeping track of the number of people who have connected:",
                    self.connected)

                # Connects players to the new game
                for x in range(2):
                    address = self.waitingList[x]
                    # Packages up data and sends it back to the player
                    out = pickle.dumps(outboundData)
                    self.socket.sendto(out, address)
                    print("CONNECTOR: Sent data out to", address)

                self.waitingList = self.waitingList[
                    2:]  # Removes players from waiting list once they're in a game
 def __init__(self):
     self._header_length = ConstantVariables.NETWORK_HEADER_LENGTH
     self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self._server_socket.bind((ConstantVariables.NETWORK_IP, ConstantVariables.NETWORK_PORT))
     self._server_socket.listen()
     self._sockets_list = [self._server_socket]
     self._clients = {}
     self._game = GameServer()
     self._client_count = 0
     print(f'Listening for connections on {ConstantVariables.NETWORK_IP}:{ConstantVariables.NETWORK_PORT}...')
示例#4
0
    def createServer(self, connection, address):
        self.removeEmptyServers()  # a lil extra here: remove empty servers.

        self.console(f"[{address}] wants to create a server")
        # create server object. get its key. server should have a STATUS var tbh.
        self.SERVER_COUNTER += 1
        s = GameServer(self.SERVER,
                       self.PORT + self.SERVER_COUNTER)  # this halts. how not?
        k = s.returnKey()
        # self.SERVERS.append(s)
        self.SERVERS[k] = s
        # return key to client.
        self.send_to_client(connection, f"{self.JOINSERVER_MSG} {k}")
示例#5
0
    def __init__(self, parent=None):    
        super(AdminGui, self).__init__(parent)
        self.game = GameServer(self, 'jeopardy')

        self.loadRules()

        """
        Setup the player table, and wait for players to login before
        the game may be started.
        """
        self.playerAdmin = PlayerAdminDialog(self)        
        self.playerAdmin.startGame.connect(self.startGame)
        self.playerAdmin.show() # does not block thread, __init__ continues
        
        # starts the GameServer thread
        self.game.start()
        
        # prepare to tell the time elapsed since the game started
        self.time = QTime(0, 0, 0)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.displayTime)
    def start_game_by_json(self, req):
        field = self.get_int_field((req['arena'])['field'])
        temp_pos = self.get_position_for(field, 1)

        temp = req['robot1']
        bot_stat1 = BotMapper(temp['charge'], temp['weight'], temp['speed'],
                              temp['tiredness'], temp['damage'], temp['range'],
                              temp_pos[0], temp_pos[1], field)
        bot1_string = (temp['botAlgorithm'])['algorithm']

        temp_pos = self.get_position_for(field, 2)
        temp = req['robot2']
        bot_stat2 = BotMapper(temp['charge'], temp['weight'], temp['speed'],
                              temp['tiredness'], temp['damage'], temp['range'],
                              temp_pos[0], temp_pos[1], field)
        bot2_string = (temp['botAlgorithm'])['algorithm']

        game = GameServer(bot1_string, bot2_string, bot_stat1, bot_stat2,
                          field)
        res = game.start()

        return jsonify({"winner": res[0], "fight_map": res[1]})
示例#7
0
#!/usr/bin/python3

from GameServer import GameServer

gs = GameServer()

示例#8
0
def HostTheGame():
    print("HOST TIME")
    GameServer()
示例#9
0
Created on Thu Mar 12 13:15:34 2020

@author: simed
"""

from GameServer import GameServer
from game import Game

initial_pop = {
    2: [[(5, 5), 2], [(6, 6), 5]],
    1: [[(0, 0), 10]],
    0: [[(9, 9), 10]]
}
g = Game(10, 10, initial_pop)

gs = GameServer(g, '', '', True)

# test get_valid_mov
tests = {
    (0, 0): [(0, 1), (1, 0), (1, 1)],
    (5, 5): [(4, 4), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (6, 6)],
    (9, 9): [(8, 8), (8, 9), (9, 8)]
}

for inp, out in tests.items():
    if gs.get_valid_move(inp) != out:
        print(
            f'error on get_valid_mov with input {inp}, received = {gs.get_valid_mov(inp)} instead of {out}'
        )
#Testing end detection
if gs.is_game_ended()[0] == True:
示例#10
0
host = 'localhost'
port = 50000
backlog = 5
maxsize = 1024

# Start listening on our socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
server.listen(backlog)
input = [server, ]  # List of all connections we want to check for data

running = 1

# New game server instance which will help manage ongoing games
gameServer = GameServer()
# Map of socket connections to players
socketsToPlayers = {}


# Helper function to send status codes with messages to a socket
def sendStatus(soc, code, message=None):
    codeStr = "STATUS " + str(code)

    if message is not None:
        # print("The message is" + message)
        codeStr += "\n" + str(message)

    codeStr += "\r\n\r\n"

    soc.send(codeStr.encode())
示例#11
0
def main(args):
    server = GameServer(2, argv[1], int(argv[2]))
    server.start_server()