Ejemplo n.º 1
0
def main():
    WINDOW_WIDTH = 540
    WINDOW_HEIGHT = 540

    pygame.init()
    display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption("SnakeClone")

    clock = pygame.time.Clock()

    state = GameStates.START
    gamedata = None

    while state != GameStates.EXIT:
        display.fill((0, 0, 0))

        if state == GameStates.GAME:
            game = Game(display, clock)
            state = game.run()
            gamedata = game.forwardData
        elif state == GameStates.MENU:
            state = Menu(display, clock).run()
        elif state == GameStates.SETTINGS:
            state = SettingsScreen(display, clock).run()
        elif state == GameStates.SCORE:
            state = ScoreScreen(display, clock, gamedata).run()
        elif state == GameStates.START:
            state = StartScreen(display, clock).run()
Ejemplo n.º 2
0
    def run(self):
        self.logger.info("Room opened, initializing data for the game")

        self.roomClients[0].isPlaying = True
        self.roomClients[1].isPlaying = True
        clients[self.uuid] = []
        clients[self.uuid].append(self.roomClients[0])
        clients[self.uuid].append(self.roomClients[1])

        # Player 0 is always a Inspector and 1 is Fantom : order handled by matchmaking
        players = [
            Player(0, self.roomClients[0], self.uuid, self.logger),
            Player(1, self.roomClients[1], self.uuid, self.logger)
        ]
        scores = []

        # profiling
        pr = cProfile.Profile()
        pr.enable()

        self.logger.info("Starting the game : " + str(self.uuid))

        game = Game(players, self.roomClients, self.logger)
        game.start()

        for c in self.roomClients:
            if c.hasWon:
                csv_manager.insert_success(c.username, c.playerType)
            else:
                csv_manager.insert_failure(c.username, c.playerType)

        self.roomClients[0].disconnect()
        self.roomClients[1].disconnect()

        # profiling
        pr.disable()
        # stats_file = open("{}.txt".format(os.path.basename(__file__)), 'w')
        stats_file = open("./logs/profiling_" + str(self.uuid) + ".txt", 'w')
        sys.stdout = stats_file
        pr.print_stats(sort='time')
        self.logger.warning("Match: " + str(self.uuid) + " has finished")
        self.close_logger()
        roomThreads.pop(self.uuid)
        clients.pop(self.uuid)
Ejemplo n.º 3
0
    async def __start(self):

        if self.__started:  # Player 1 comes here and starts the game,
            await self.__keepConnected(
            )  # Player 2 goes to __keepConnected() to avoid doing all the tasks twice.
        self.__started = True
        logger.info("The game in room #{} has started.".format(str(self.__ID)))

        player1, player2 = self.__players
        game = Game(self.__ID)

        try:
            await game.start(player1, player2)
        except ConnectionClosedOK as e:
            logger.info("{} has disconnected.".format(e.player.getAddress()))
            await self.__onConnectionClose(e.player)  # Ignore these errors.
        except PlayerKickedException as e:
            logger.info("{} has been kicked. Reason: {}.".format(
                e.player.getAddress(), e.reason))
            await self.__onConnectionClose(e.player)
        except ConnectionClosedError as e:
            logger.error(
                "{}: Connection with {} has beed terminated. Reason: {}".
                format(e.code, e.player, e.reason))  # Ignore this error.
            await self.__onConnectionError()

        winner = game.getWinner()
        if (winner == 1):
            await self.__gameOver(player1, player2)
        elif (winner == 2):
            await self.__gameOver(player2, player1)
        elif (winner == 3):
            await self.__onDraw()
        else:
            await self.__onConnectionError(
            )  # Theoretically it will never happen.
Ejemplo n.º 4
0
from pathlib import Path
import sys
from src.game.Game import Game

# TODO: Paths are still retarded
programPath = Path(".").resolve()
game = Game(programPath, sys.argv)
Ejemplo n.º 5
0
    def start():
        global game
        game = Game(len(bots), './maps/' + args.m)
        for bot in bots:
            new_id = game.get_available_id()
            bot.set_player_id(new_id)
            game.set_name(new_id, bot.get_name())

        command_factory = CommandFactory()
        while not game.game_over():
            for bot in bots:
                info = game.get_next_turn_info()
                player_turn = info['player_turn']

                if not game.bot_is_active(player_turn):
                    game.next_player()
                    continue

                players = parse_player_info(info)
                character = get_character(player_turn, players)
                other_players = get_other_players(player_turn, players)

                try:
                    que = Queue()
                    t = threading.Thread(target=run_bot_turn,
                                         args=(que, bot, info['game_state'], character, other_players))
                    t.start()
                    t.join(timeout=1.0)
                    if t.is_alive():
                        raise TimeoutError

                    command = que.get()
                    command = command_factory.create_command(command)
                    game.execute_command(command)
                except Exception as e:
                    print(e)
                    game.disconnect(player_turn)
                    game.next_player()

                emit('next turn', info, broadcast=True)

        print('The winner is {}'.format(game.get_winner()))
Ejemplo n.º 6
0
    args = parser.parse_args()

    bots = []
    for bot in args.p:
        name = 'src.bot.' + bot
        mod = importlib.import_module(name)
        bot = getattr(mod, bot)
        bots.append(bot())

    if args.j:
        gateway = JavaGateway(auto_convert=True)
        java_bots = gateway.entry_point.getBots()
        for bot in java_bots:
            bots.append(java_bots[0])

    game = Game(len(bots), os.path.join(os.getcwd(), 'maps', args.m))

    def get_other_players(player_turn, players):
        other_player = []
        for player in players:
            if player['id'] != player_turn:
                other_player.append(player)
        return other_player

    def run_bot_turn(q, ai, game, character, players):
        try:
            q.put(ai.turn(game, character, players))
        except Exception as e:
            print(e)
            time.sleep(1)