示例#1
0
class GameEngine(rm.ProtoModule):
    def __init__(self, addr, port):
        self.subscriptions = [MsgType.PACMAN_LOCATION]
        super().__init__(addr, port, message_buffers, MsgType, FREQUENCY,
                         self.subscriptions)
        self.loop.add_reader(sys.stdin, self.keypress)

        self.game = GameState()

    def _write_state(self):
        full_state = StateConverter.convert_game_state_to_full(self.game)
        self.write(full_state.SerializeToString(), MsgType.FULL_STATE)

        light_state = StateConverter.convert_game_state_to_light(self.game)
        self.write(light_state.SerializeToString(), MsgType.LIGHT_STATE)

    def msg_received(self, msg, msg_type):
        if msg_type == MsgType.PACMAN_LOCATION:
            self.game.pacbot.update((msg.x, msg.y))

    def tick(self):
        # this function will get called in a loop with FREQUENCY frequency
        if self.game.play:
            # update_pacbot_pos
            # This will become asynchronous
            self.game.next_step()
        self._write_state()

    def keypress(self):
        char = sys.stdin.read(1)
        # For some reason I couldn't quite get this to do what I wanted
        # Still it's a bit cleaner than otherwise
        sys.stdout.write("\033[F")
        sys.stdout.write("\033[K")
        sys.stdout.flush()
        if char == "r":
            logging.info("Restarting...")
            self.game.restart()
            self._write_state()
        elif char == "p":
            if (self.game.play):
                logging.info('Game is paused')
                self.game.pause()
            else:
                logging.info('Game resumed')
                self.game.unpause()
        elif char == "q":
            logging.info("Quitting...")
            self.quit()
示例#2
0
class PacEng(rm.ProtoModule):
    def __init__(self, addr, port):
        self.subscriptions = [MsgType.PACMAN_LOCATION]
        super().__init__(addr, port, message_buffers, MsgType, FREQUENCY,
                         self.subscriptions)
        self.game = GameState()
        self.game.unpause()

    def _write_state(self):
        full_state = StateConverter.convert_game_state_to_full(self.game)
        self.write(full_state.SerializeToString(), MsgType.FULL_STATE)

        light_state = StateConverter.convert_game_state_to_light(self.game)
        self.write(light_state.SerializeToString(), MsgType.LIGHT_STATE)

    def msg_received(self, msg, msg_type):
        if msg_type == MsgType.PACMAN_LOCATION:
            self.game.pacbot.update((msg.x, msg.y))

    def tick(self):
        if self.game.lives < 3:
            global GAME_SCORE
            GAME_SCORE = self.game.score
            global GHOST_LOCATIONS
            GHOST_LOCATIONS.extend((self.game.red.pos["current"][0],
                                    self.game.red.pos["current"][1],
                                    self.game.pink.pos["current"][0],
                                    self.game.pink.pos["current"][1],
                                    self.game.orange.pos["current"][0],
                                    self.game.orange.pos["current"][1],
                                    self.game.blue.pos["current"][0],
                                    self.game.blue.pos["current"][1]))
            self.game.respawnagents()
        # this function will get called in a loop with FREQUENCY frequency
        if self.game.play:
            # update_pacbot_pos
            # This will become asynchronous
            self.game.next_step()
        self._write_state()
示例#3
0
class GameEngine(rm.ProtoModule):
    def __init__(self, addr, port):
        self.subscriptions = [
            MsgType.PACMAN_LOCATION, MsgType.FULL_STATE, MsgType.LIGHT_STATE
        ]
        super().__init__(addr, port, message_buffers, MsgType, FREQUENCY,
                         self.subscriptions)
        self.loop.add_reader(sys.stdin, self.keypress)
        self.game = GameState()
        self.pacbot_pos = [pacbot_starting_pos[0], pacbot_starting_pos[1]]
        self.cur_dir = right
        self.next_dir = right
        self.state = PacmanState()
        self.state.mode = PacmanState.PAUSED
        self.lives = starting_lives
        self.clicks = 0
        self.light_state = StateConverter.convert_game_state_to_light(
            self.game)
        # self.J = 0
        # InputModule.main()
        # self.loop.run_until_complete(self.runsim())
        # self.tf = asyncio.new_event_loop()
        # self.tf.run_forever(self.hello())

    def _write_state(self):
        full_state = StateConverter.convert_game_state_to_full(self.game)
        self.write(full_state.SerializeToString(), MsgType.FULL_STATE)

        light_state = StateConverter.convert_game_state_to_light(self.game)
        self.write(light_state.SerializeToString(), MsgType.LIGHT_STATE)
        self.light_state = light_state
        # if (self.game.play):
        #         logging.info('Game is paused')
        #         self.game.pause()
        #     else:
        #         logging.info('Game resumed')
        #         self.game.unpause()
    def msg_received(self, msg, msg_type):
        if msg_type == MsgType.PACMAN_LOCATION:
            self.game.pacbot.update((msg.x, msg.y))
        if msg_type == MsgType.FULL_STATE:
            self.state = msg
            if self.state.lives != self.lives:
                self.lives = self.state.lives
                self.pacbot_pos = [
                    pacbot_starting_pos[0], pacbot_starting_pos[1]
                ]

    def _move_if_valid_dir(self, direction, x, y):
        if direction == right and grid[x + 1][y] not in [I, n]:
            self.pacbot_pos[0] += 1
            self.cur_dir = direction
            return True
        elif direction == left and grid[x - 1][y] not in [I, n]:
            self.pacbot_pos[0] -= 1
            self.cur_dir = direction
            return True
        elif direction == up and grid[x][y + 1] not in [I, n]:
            self.pacbot_pos[1] += 1
            self.cur_dir = direction
            return True
        elif direction == down and grid[x][y - 1] not in [I, n]:
            self.pacbot_pos[1] -= 1
            self.cur_dir = direction
            return True
        return False

    def tick(self):
        # this function will get called in a loop with FREQUENCY frequency
        # print(self.game.play)
        #gotta set speed
        if self.game.play == False:
            if self.game.endofgame == False:
                self.game.unpause()
            else:
                self.game.restart()
                self.game.endofgame = False
                self.game.unpause()

        if self.game.play:
            # update_pacbot_pos
            if not self._move_if_valid_dir(self.next_dir, self.pacbot_pos[0],
                                           self.pacbot_pos[1]):
                self._move_if_valid_dir(self.cur_dir, self.pacbot_pos[0],
                                        self.pacbot_pos[1])
            pos_buf = PacmanState.AgentState()
            pos_buf.x = self.pacbot_pos[0]
            pos_buf.y = self.pacbot_pos[1]
            pos_buf.direction = self.cur_dir
            self.write(pos_buf.SerializeToString(), MsgType.PACMAN_LOCATION)
            self.next_dir = randint(0, 3)
            # print(self.light_state.score)
            # for i in range(0,10000000):
            #     x = i*100
            # print(self.J)
            # self.J+= 1
            # self.state.mode = PacmanState.PAUSED;

            # This will become asynchronous
            self.game.next_step()
        self._write_state()

    def runsim(self):
        print("hello")
        timesteps = 10
        logging.info("Restarsting...")
        self.game.restart()
        self._write_state()
        if (self.game.play):
            logging.info('Game is paused')
            self.game.pause()
        else:
            logging.info('Game resumed')
            self.game.unpause()
        for i in range(0, timesteps):
            # self.game.unpause()
            while True:
                pass

    def packey(self):
        char = sys.stdin.read(1)
        if char == 'a':
            self.next_dir = left
        elif char == 'd':
            self.next_dir = right
        elif char == 'w':
            self.next_dir = up
        elif char == 's':
            self.next_dir = down
        elif char == 'q':
            self.quit()

    def keypress(self):
        char = sys.stdin.read(1)
        # For some reason I couldn't quite get this to do what I wanted
        # Still it's a bit cleaner than otherwise
        sys.stdout.write("\033[F")
        sys.stdout.write("\033[K")
        sys.stdout.flush()
        if char == "r":
            logging.info("Restarting...")
            self.game.restart()
            self._write_state()
        elif char == "p":
            if (self.game.play):
                logging.info('Game is paused')
                self.game.pause()
            else:
                logging.info('Game resumed')
                self.game.unpause()
        elif char == "q":
            logging.info("Quitting...")
            self.quit()
示例#4
0
class GameEngine:
    def __init__(self,
                 addr,
                 port,
                 weight_set=WEIGHT_SET,
                 run_on_clock=None,
                 using_visualizer=None):
        global WEIGHT_SET, USING_VISUALIZER, RUN_ON_CLOCK
        if run_on_clock is not None:
            RUN_ON_CLOCK = run_on_clock
        if using_visualizer is not None:
            USING_VISUALIZER = using_visualizer
        WEIGHT_SET = weight_set
        self.final_state = None
        self.latestPacbotInfo = None
        self.subscriptions = [MsgType.PACMAN_LOCATION]
        # super().__init__(addr, port, message_buffers, MsgType, FREQUENCY, self.subscriptions)
        # self.loop.add_reader(sys.stdin, self.keypress)

        self.game = GameState()
        self.highLevelPacman = HighLevelPacman(
            addr=None,
            port=None,
            game=self,
            returnInfo=NO_PRINT,
            frequency_multiplier=FREQUENCY_MULTIPLIER,
            fear=WEIGHT_SET['FEAR'],
            pellet_weight=WEIGHT_SET['PELLET_WEIGHT'],
            super_pellet_weight=WEIGHT_SET['SUPER_PELLET_WEIGHT'],
            ghost_weight=WEIGHT_SET['GHOST_WEIGHT'],
            frightened_ghost_weight=WEIGHT_SET['FRIGHTENED_GHOST_WEIGHT'],
            proximity_pellet_multiplier=WEIGHT_SET[
                'PROXIMITY_PELLET_MULTIPLIER'],
            anti_corner_weight=WEIGHT_SET['ANTI_CORNER_WEIGHT'],
            runOnClock=RUN_ON_CLOCK)
        if USING_VISUALIZER:
            self.visualize = Visualize(run_on_clock=run_on_clock)

        self.game.unpause()

        if RUN_ON_CLOCK:
            self.loop = asyncio.get_event_loop()
            self.loop.call_soon(self.tick)
        else:
            turn_num = 0
            while self.game.play:
                turn_num += 1
                if VALUE_DEBUG:
                    # export data to debug/visualize the heuristic values
                    self.export_heuristic_debug(f'data/data{turn_num:05}.pkl')

                # INCORRECT CALL TIMING, PACBOT MOVES WAY TOO FAST
                # update_pacbot_pos
                self.highLevelPacman.tick()
                # This will become asynchronous
                for i in range(8):
                    self.game.next_step()
                    if USING_VISUALIZER:
                        self.visualize.visualizer.msg_received(
                            StateConverter.convert_game_state_to_full(
                                self.game), MsgType.FULL_STATE)
                self.highLevelPacman.msg_received(
                    StateConverter.convert_game_state_to_light(self.game),
                    MsgType.LIGHT_STATE)
                # print('gameEngineTickMesg')
                # print('SAVE GAME STATE TO FILE')
                if USING_VISUALIZER:
                    pygame.time.wait(50)
        self.final_state = {'score': self.game.score}

    def export_heuristic_debug(self, filename):
        import botCode.variables as variables

        # compute the heuristic values for the entire grid
        grid = self.highLevelPacman.grid
        value_grid = np.zeros((len(grid[0]), len(grid)))
        pellet_locs = []
        super_pellet_locs = []
        for x in range(0, len(grid)):
            for y in range(0, len(grid[0])):
                try:
                    value = self.highLevelPacman.get_heuristic_value((x, y))
                except:
                    value = None
                value_grid[y][x] = value

                if grid[x][y] == variables.o:
                    pellet_locs.append((x, y))
                elif grid[x][y] == variables.O:
                    super_pellet_locs.append((x, y))

        # collect other game state
        ghost_locs = [
            self.game.red.pos['current'],
            self.game.pink.pos['current'],
            self.game.orange.pos['current'],
            self.game.blue.pos['current'],
        ]
        pacbot_loc = self.game.pacbot.pos

        # write all the data to file
        with open(filename, 'wb') as f:
            pickle.dump((value_grid, pellet_locs, super_pellet_locs,
                         ghost_locs, pacbot_loc), f)

    def _write_state(self):
        full_state = StateConverter.convert_game_state_to_full(self.game)
        self.write(full_state.SerializeToString(), MsgType.FULL_STATE)

        light_state = StateConverter.convert_game_state_to_light(self.game)
        self.write(light_state.SerializeToString(), MsgType.LIGHT_STATE)

    def msg_received(self, msg, msg_type):
        if msg_type == MsgType.PACMAN_LOCATION:
            self.game.pacbot.update((msg.x, msg.y))

    def tick(self):
        # print('GameEngine.tick()')
        # schedule the next tick in the event loop
        self.loop.call_later(1.0 / FREQUENCY, self.tick)

        # this function will get called in a loop with FREQUENCY frequency
        if self.game.play:
            # update_pacbot_pos
            # This will become asynchronous
            self.game.next_step()
            self.highLevelPacman.msg_received(
                StateConverter.convert_game_state_to_light(self.game),
                MsgType.LIGHT_STATE)
            # print('gameEngineTickMesg')
            if USING_VISUALIZER:
                self.visualize.visualizer.msg_received(
                    StateConverter.convert_game_state_to_full(self.game),
                    MsgType.FULL_STATE)
        # self._write_state()

    def run(self):
        if RUN_ON_CLOCK:
            self.loop.run_forever()

    def keypress(self):
        char = sys.stdin.read(1)
        # For some reason I couldn't quite get this to do what I wanted
        # Still it's a bit cleaner than otherwise
        sys.stdout.write("\033[F")
        sys.stdout.write("\033[K")
        sys.stdout.flush()
        if char == "r":
            logging.info("Restarting...")
            self.game.restart()
            self._write_state()
        elif char == "p":
            if (self.game.play):
                logging.info('Game is paused')
                self.game.pause()
            else:
                logging.info('Game resumed')
                self.game.unpause()
        elif char == "q":
            logging.info("Quitting...")
            self.quit()

    def receivePacbotInfo(self, pacbotInfo):
        # print('received info')
        # print(pacbotInfo)
        if not self.game.play:
            # print('I think we should stop the thing')
            self.highLevelPacman.quit()
            if USING_VISUALIZER:
                print('quitting pygame')
                pygame.quit()
                # self.visualize.visualizer.quit()
            self.loop.stop()
            self.final_state = {'score': self.game.score}