Example #1
0
 def parse_character(self, pos, char) -> MapPart:
     h = int(self.h)
     if char == PLAYER_VISUAL:
         p = Pacman(pos, h, char)
         self.pacman.append(p)
         return p
     elif char == BLINKY_VISUAL:
         self.Blinky = Blinky(pos, h, char)
         return self.Blinky
     elif char == CLYDE_VISUAL:
         self.Clyde = Clyde(pos, h, char)
         return self.Clyde
     elif char == INKY_VISUAL:
         self.Inky = Inky(pos, h, char)
         return self.Inky
     elif char == SPEEDY_VISUAL:
         self.Speedy = Speedy(pos, h, char)
         return self.Speedy
     elif char == WALL_VISUAL:
         return Obstacle(pos, h, char)
     elif char == WALL2_VISUAL:
         return Obstacle(pos, h, char)
     elif char == COIN_VISUAL:
         self.bonuses_cnt += 1
         return Coin(pos, h, char)
     elif char == CHERRY_VISUAL:
         self.bonuses_cnt += 1
         return Cherry(pos, h, char)
     elif char == SPACE_VISUAL:
         return Space(pos, h, char)
     raise IndentationError
Example #2
0
 def add_pacman(self):
     speed = self.level.pacman_speed
     if not self.AI_playing:
         self.pacman = [Pacman.Pacman(9, 15, block_size, speed)]
     else:
         self.pacman = []
         self.networks = []
         for i in range(len(self.genomes)):
             self.pacman.append(Pacman.Pacman(9, 15, block_size, speed))
             net = neat.nn.FeedForwardNetwork.create(
                 self.genomes[i], config)
             self.networks.append(net)
     self.scores = [0] * len(self.pacman)
     self.num_alive = len(self.pacman)
     for p in self.pacman:
         self.screen.blit(p.get_cur_image(),
                          (p.get_screen_x(), p.get_screen_y()))
     pygame.display.update()
Example #3
0
 def __init__(self, size):
     pygame.init()
     self.size = size
     self.screen = pygame.display.set_mode(size, 0, 32)
     self.color = black
     pygame.display.set_caption('PACMAN FOREVER YOUNG')
     self.run = True
     self.frame = Frame((50, 50, 1100, 800), cyan, 4)
     self.pacman = Pacman(self.frame)
     # game speed = number of operations per sec
     self.game_speed = 60
     self.lines = []
Example #4
0
def game_loop(win, mapa, neural_net, train):
    pacman = Pacman(mapa, neural_net)
    blinky = Blinky(mapa, pacman)
    pinky = Pinky(mapa, pacman)
    clyde = Clyde(mapa, pacman)
    inky = Inky(mapa, pacman)
    clock = pygame.time.Clock()

    while pacman.isAlive:
        events = pygame.event.get()
        handle_quit(events)

        win.fill((0, 0, 0))

        up = 0
        down = 0
        left = 0
        right = 0

        input_data = np.array([[calcDist(pacman.getPos(), blinky.getPos()), calcDist(pacman.getPos(), pinky.getPos()), calcDist(pacman.getPos(), inky.getPos()), calcDist(pacman.getPos(), clyde.getPos())]])

        np.interp(input_data, (0, 36), (-1, +1))

        if(mapa.map[pacman.getPos()[1] - 1][pacman.getPos()[0]] != 1):
            up = 1
        if(mapa.map[pacman.getPos()[1] + 1][pacman.getPos()[0]] != 1):
            down = 1
        if(mapa.map[pacman.getPos()[1]][pacman.getPos()[0] + 1] != 1):
            right = 1
        if(mapa.map[pacman.getPos()[1]][pacman.getPos()[0] - 1] != 1):
            left = 1
        
        input_data = np.append(np.array([[up, right, down, left]]), input_data, axis=1)

        pacman.update(input_data)
        blinky.update()
        pinky.update()
        clyde.update()
        inky.update(blinky.getPos())

        if train == False: 
            mapa.draw(win) 
            pacman.draw(win)
            blinky.draw(win)
            pinky.draw(win)
            clyde.draw(win)
            inky.draw(win)
            textsurface = pygame.font.SysFont('Comic Sans MS', 25).render('Score: {}'.format(pacman.score), False, (255, 255, 255))
            win.blit(textsurface,(240,300))
            pygame.display.update()
            clock.tick(FPS)
    return (pacman.score, pacman.count2)
Example #5
0
    def __init__(self, width=580, height=700):
        '''
        initializes the controller class and sets up the window
        inputs: width and height of window
        outputs: pacman screen
        '''
        pygame.init()
        self.maze = Maze.Maze(width, height)

        self.width = width
        self.height = height

        self.screen = pygame.display.set_mode((self.width, self.height))
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.pacman = Pacman.Pacman(self.maze, 21, 21)
        self.pgroup = pygame.sprite.GroupSingle(self.pacman)
        self.maze_image = pygame.image.load('empty_maze.png')
        self.resized = pygame.transform.smoothscale(self.maze_image,
                                                    self.maze.size)

        self.mgroup = pygame.sprite.Group()
        wall_image = self.maze.make_image('blue_down_1.png')
        for coord in self.maze.wall_positions():
            self.mgroup.add(Walls.Walls(coord[0], coord[1], wall_image))
        #self.maze_image
        #self.pacman_rect = ?????????????
        self.sgroup = pygame.sprite.Group()
        self.taken_pos = set([(self.pacman.start_pos)])

        self.sgroup = pygame.sprite.Group()
        self.scgroup = pygame.sprite.Group()
        self.ghosts = pygame.sprite.Group()

        self.add_sprite(6, Cookies.OrangeCookies, self.sgroup)
        self.add_sprite(4, Cookies.PinkCookies, self.scgroup)
        self.add_sprite(4, Ghost.Ghost, self.ghosts)

        Ghost
        #self.ghosts.add(Ghost.Ghost('red_up_2.png', 539, 106))
        #self.ghosts.add(Ghost.Ghost('red_up_2.png', 33, 35))
        #self.ghosts.add(Ghost.Ghost('red_up_2.png', 261, 89))
        #self.ghosts.add(Ghost.Ghost('red_up_2.png', 510, 500))
        #self.ghost=(Ghost.Ghost('pink_up_2.png', 300, 300))
        self.cookiescollected = 0
        self.lives = 3
Example #6
0
def reinitialise(new_life_count):
    '''
    Re-initialises the game with the given life count.
    Parameters-
        life_count - the new life_count.
    '''

    global pacman , ghosts_in_maze , ghosts_not_in_maze , game_running , life_count , game_start_time

    pacman = Pacman.Pacman(336 , 504)
    ghosts_not_in_maze = [ Ghost.Ghost(
                        os.path.join(os.getcwd() , 'res' , 'tiles' , 'ghost-{}.gif'.format(ghost_name)),
                         13 * 24 , 13 * 24) for ghost_name in [ "sue",
                                                                "inky",
                                                                "pinky",
                                                                "blinky"]]
    ghosts_in_maze = []
    game_running = False
    life_count = new_life_count
    game_start_time = float('inf')
Example #7
0
    def level_1(self):
        """
        Level 1: Pac-man know the food’s position in map and monsters do not appear in map.
        There is only one food in the map.
        """
        graph_map, pacman_pos, food_pos = Map.read_map_level_1(
            MAP_INPUT_TXT[self.current_level - 1][self.current_map_index])
        path = GraphSearchAStar.search(graph_map, pacman_pos, food_pos)

        pacman = Pacman.Pacman(self, pacman_pos)
        pacman.appear()

        food = Food.Food(self, food_pos)
        food.appear()

        if self.ready():
            if path is not None:
                back_home = False
                goal = path[-1]
                path = path[1:-1]

                for cell in path:
                    pacman.move(cell)
                    self.update_score(SCORE_PENALTY)
                    pygame.time.delay(
                        int(SPEED // self.speed_list[self.cur_speed_index][1]))

                    if self.launch_game_event():
                        back_home = True
                        break

                if not back_home:
                    pacman.move(goal)
                    self.update_score(SCORE_PENALTY + SCORE_BONUS)
                    self.state = STATE_VICTORY
                    pygame.time.delay(2000)
            else:
                self.state = STATE_GAMEOVER
                pygame.time.delay(2000)
Example #8
0
 def __init__(self, width=580, height=700):
     '''
     initializes the controller class and sets up the window
     inputs: width and height of window
     outputs: pacman screen
     '''
     pygame.init()
     self.width = width
     self.height = height
     self.screen = pygame.display.set_mode((self.width, self.height))
     self.background = pygame.Surface(self.screen.get_size()).convert()
     self.pacman = Pacman.Pacman(275, 460)
     self.maze_image = pygame.image.load('empty_maze.png')
     self.resized = pygame.transform.smoothscale(self.maze_image,
                                                 (580, 620))
     #self.maze_image
     #self.pacman_rect = ?????????????
     self.ghosts = pygame.sprite.Group()
     self.ghosts.add(Ghost.Ghost('red_left_2.png', 170, 80, 6))
     self.ghosts.add(Ghost.Ghost('blue_up_2.png', 190, 80, 6))
     self.ghosts.add(Ghost.Ghost('pink_down_2.png', 210, 80, 6))
     self.ghosts.add(Ghost.Ghost('orange_up_2.png', 230, 80, 6))
     self.pacman.lives = len(self.ghosts)
Example #9
0
    def setup_level(self):
        w = len(MAP[0])
        h = len(MAP) + 1  # We add a bit of space for the text at the bottom
        self.barriers = []
        self.ghosts = []
        self.foods = []
        self.stage_width, self._stage_height = w, h - 1
        self.size = (w * ICON_SIZE, h * ICON_SIZE)

        for i in range(len(MAP)):
            for j in range(len(MAP[i])):
                key = MAP[i][j]
                if key == 'P':
                    self.set_player(Pacman(i, j, 24, 24, {}))
                elif key == 'G':
                    self.add_ghost(Ghost(i, j, 24, 24, {}))
                elif key == 'O':
                    self.add_food(Food(i, j, 10, 10, {}))
                elif key == 'X':
                    self.add_barrier(Barrier(i, j, 24, 24, {}))

        self.goal_CGPA = 3.0
        self.current_CGPA = 0.0
        self.goal_message = "Objective: Collect good marks to meet your CGPA!"
Example #10
0
 def __init__(self, width = 580, height = 700):
     '''
     initializes the controller class and sets up the window
     inputs: width and height of window
     outputs: pacman screen
     '''
     pygame.init()
     self.width = width
     self.height = height
     self.screen = pygame.display.set_mode((self.width, self.height))
     self.background = pygame.Surface(self.screen.get_size()).convert()
     self.pacman = Pacman.Pacman(337, 520, 'pacman_whole.png')
     self.maze_image = pygame.image.load('empty_maze.png')
     self.resized = pygame.transform.smoothscale(self.maze_image, (580,620))
     #self.maze_image
     #self.pacman_rect = ?????????????
     self.sgroup = pygame.sprite.Group()
     self.sgroup.add(Cookies.Cookies(332, 462,'orange_down_1.png'))
     self.sgroup.add(Cookies.Cookies(54, 531,'orange_down_1.png'))
     self.sgroup.add(Cookies.Cookies(307, 350,'orange_down_1.png'))
     self.sgroup.add(Cookies.Cookies(125, 354,'orange_down_1.png'))
     self.sgroup.add(Cookies.Cookies(370, 240,'orange_down_1.png'))
     self.sgroup.add(Cookies.Cookies(470, 410,'orange_down_1.png'))
     self.scgroup = pygame.sprite.Group()
     self.scgroup.add(Cookies.Cookies(539, 106,'pink_down_1.png'))
     self.scgroup.add(Cookies.Cookies(33, 35,'pink_down_1.png'))
     self.scgroup.add(Cookies.Cookies(261, 89,'pink_down_1.png'))
     self.scgroup.add(Cookies.Cookies(510, 500,'pink_down_1.png'))
     self.ghosts = pygame.sprite.Group()
     self.ghosts.add(Ghost.Ghost('blue_up_2.png', 539, 106))
     self.ghosts.add(Ghost.Ghost('blue_up_2.png', 33, 35))
     self.ghosts.add(Ghost.Ghost('blue_up_2.png', 261, 89))
     self.ghosts.add(Ghost.Ghost('blue_up_2.png', 510, 500))
     #self.ghost=(Ghost.Ghost('pink_up_2.png', 300, 300))
     self.cookiescollected=0
     self.lives = 3
Example #11
0
    def level_5(self):
        """
        Level 5: Pac-man cannot see the foods if they are outside Pacman’s nearest threestep.
        It means that Pac-man just only scan all the adjacent him (8 tiles x 3).
        There are many foods in the map.
        Monsters just move one step in any valid direction.
        Each step Pacman go, each step Monsters move.
        """
        # Read map.
        cells, graph_map, pacman_cell, food_cell_list, monster_cell_list = Map.read_map_level_3(
            MAP_INPUT_TXT[self.current_level - 1][self.current_map_index])

        # Initialize Pacman, Foods and Monsters.
        food_list = [
            Food.Food(self, food_cell.pos, food_cell)
            for food_cell in food_cell_list
        ]
        for food in food_list:
            food.appear()

        monster_list = [
            Monster.Monster(self, monster_cell.pos, monster_cell)
            for monster_cell in monster_cell_list
        ]
        for monster in monster_list:
            monster.appear()

        pacman = Pacman.Pacman(self, pacman_cell.pos, pacman_cell)
        pacman.appear()

        # Game.
        if self.ready():
            back_home = False
            pacman_is_caught = False

            while True:
                is_backtracking = False
                pacman_old_cell = pacman.cell

                # Pacman observes all of Cells in its sight then decide the direction to move.
                pacman.cell.pacman_leave()
                pacman.observe(graph_map, 3)

                if not pacman.empty_brain(
                ) and not pacman.have_food_in_cur_sight(
                ) and not pacman.have_monster_in_cur_sight():
                    # Pacman tracks the peas which leads to one of Food that Pacman saw in the past.
                    pacman.cell = pacman.back_track(graph_map)
                    is_backtracking = True
                else:
                    # Pacman moves with heuristic.
                    pacman.cell = HeuristicLocalSearch.local_search(
                        cells, graph_map, pacman.cell)

                pacman.cell.pacman_come()
                pacman.move(pacman.cell.pos)
                self.update_score(SCORE_PENALTY)

                # Spread the peas.
                if not is_backtracking:
                    pacman.spread_peas(pacman_old_cell)

                # Pacman went through Monsters?
                for monster in monster_list:
                    if pacman.cell.pos == monster.cell.pos:
                        self.state = STATE_GAMEOVER
                        pacman_is_caught = True
                        break
                if pacman_is_caught:
                    break

                # Pacman ate a Food?
                pre_food_list_len = len(food_list)
                for food in food_list:
                    if food.cell.pos == pacman.cell.pos:
                        food_list.remove(food)

                if pre_food_list_len != len(food_list):
                    self.update_score(SCORE_BONUS)

                    for i in range(len(pacman.food_cell_in_brain_list)):
                        if pacman.food_cell_in_brain_list[i] == pacman.cell:
                            pacman.food_cell_in_brain_list.remove(
                                pacman.food_cell_in_brain_list[i])
                            pacman.path_to_food_cell_in_brain_list.remove(
                                pacman.path_to_food_cell_in_brain_list[i])
                            break

                # Monsters move randomly.
                for monster in monster_list:
                    old_cell = monster.cell
                    monster.cell.monster_leave()

                    around_cell_list = monster.get_around_cells(graph_map)
                    next_cell_index = random.randint(0,
                                                     len(around_cell_list) - 1)
                    next_cell = around_cell_list[next_cell_index]
                    monster.cell = next_cell

                    monster.cell.monster_come()

                    monster.move(monster.cell.pos)

                    if old_cell.exist_food():
                        temp_food = Food.Food(self, old_cell.pos, old_cell)
                        temp_food.appear()

                # Monsters caught Pacman up?
                for monster in monster_list:
                    if pacman.cell.pos == monster.cell.pos:
                        self.state = STATE_GAMEOVER
                        pacman_is_caught = True
                        break
                if pacman_is_caught:
                    break

                # Pacman ate all of Foods?
                if len(food_list) == 0:
                    self.state = STATE_VICTORY
                    break

                # Graphic: "while True" handling.
                pygame.time.delay(
                    int(SPEED // self.speed_list[self.cur_speed_index][1]))
                if self.launch_game_event():
                    back_home = True
                    break

            if not back_home:
                pygame.time.delay(2000)
Example #12
0
    def level_4(self):
        """
        Level 4 (difficult): map is opened.
        Monsters will seek and kill Pac-man.
        Pac-man want to get food as much as possible.
        Pacman will die if at least one monster passes him.
        It is ok for monsters go through each other.
        Each step Pacman go, each step Monsters move.
        The food is so many.
        """
        # Read map.
        cells, graph_cell, pacman_cell, graph_map, food_cell_list, monster_cell_list = Map.read_map_level_4(
            MAP_INPUT_TXT[self.current_level - 1][self.current_map_index])

        # Initialize Pacman, Foods and Monsters.
        food_list = [
            Food.Food(self, food_cell.pos, food_cell)
            for food_cell in food_cell_list
        ]
        for food in food_list:
            food.appear()

        monster_list = [
            Monster.Monster(self, monster_cell.pos, monster_cell)
            for monster_cell in monster_cell_list
        ]
        for monster in monster_list:
            monster.appear()

        pacman = Pacman.Pacman(self, pacman_cell.pos, pacman_cell)
        pacman.appear()

        if self.ready():
            back_home = False
            pacman_is_caught = False

            while True:
                is_backtracking = False
                pacman_old_cell = pacman.cell

                # Pacman observes all of Cells in its sight then decide the direction to move.
                pacman.cell.pacman_leave()
                pacman.observe(graph_cell, 3)

                if not pacman.empty_brain(
                ) and not pacman.have_food_in_cur_sight(
                ) and not pacman.have_monster_in_cur_sight():
                    # Pacman tracks the peas which leads to one of Food that Pacman saw in the past.
                    pacman.cell = pacman.back_track(graph_cell)
                    is_backtracking = True
                else:
                    # Pacman moves with heuristic.
                    pacman.cell = HeuristicLocalSearch.local_search(
                        cells, graph_cell, pacman.cell)

                pacman.cell.pacman_come()
                pacman.move(pacman.cell.pos)
                self.update_score(SCORE_PENALTY)

                # Spread the peas.
                if not is_backtracking:
                    pacman.spread_peas(pacman_old_cell)

                # Pacman went through Monsters?
                for monster in monster_list:
                    if pacman.cell.pos == monster.cell.pos:
                        self.state = STATE_GAMEOVER
                        pacman_is_caught = True
                        break
                if pacman_is_caught:
                    break

                # Pacman ate a Food :) ?
                pre_food_list_len = len(food_list)
                for food in food_list:
                    if food.cell.pos == pacman.cell.pos:
                        food_list.remove(food)

                if pre_food_list_len != len(food_list):
                    self.update_score(SCORE_BONUS)

                # Monsters try to seek and kill Pacman.
                for monster in monster_list:
                    old_cell = monster.cell
                    monster.cell.monster_leave()

                    path = GraphSearchAStar.search(graph_map, monster.cell.pos,
                                                   pacman.cell.pos)
                    next_cell = cells[path[1][1]][path[1][0]]
                    monster.cell = next_cell

                    monster.cell.monster_come()
                    monster.move(monster.cell.pos)

                    if old_cell.exist_food():
                        temp_food = Food.Food(self, old_cell.pos, old_cell)
                        temp_food.appear()

                # Monster caught Pacman up :( ?
                for monster in monster_list:
                    if pacman.cell.pos == monster.cell.pos:
                        self.state = STATE_GAMEOVER
                        pacman_is_caught = True
                        break
                if pacman_is_caught:
                    break

                # Pacman ate all of Foods?
                if len(food_list) == 0:
                    self.state = STATE_VICTORY
                    break

                # Graphic: "while True" handling.
                pygame.time.delay(
                    int(SPEED // self.speed_list[self.cur_speed_index][1]))
                if self.launch_game_event():
                    back_home = True
                    break

            if not back_home:
                pygame.time.delay(2000)
Example #13
0
    def level_2(self):
        """
        Level 2: monsters stand in the place ever (never move around).
        If Pac-man pass through the monster or vice versa, game is over.
        There is still one food in the map and Pac-man know its position.
        """
        graph_map, pacman_pos, food_pos, monster_pos_list = \
            Map.read_map_level_2(MAP_INPUT_TXT[self.current_level - 1][self.current_map_index], monster_as_wall=True)

        path = GraphSearchAStar.search(graph_map, pacman_pos, food_pos)

        pacman = Pacman.Pacman(self, pacman_pos)
        pacman.appear()

        food = Food.Food(self, food_pos)
        food.appear()

        monster_list = [
            Monster.Monster(self, monster_pos)
            for monster_pos in monster_pos_list
        ]
        for monster in monster_list:
            monster.appear()

        if self.ready():
            back_home = False
            if path is None:
                graph_map, pacman_pos, food_pos, monster_pos_list = \
                    Map.read_map_level_2(MAP_INPUT_TXT[self.current_level - 1][self.current_map_index],
                                         monster_as_wall=False)

                path = GraphSearchAStar.search(graph_map, pacman_pos, food_pos)

                if path is not None:
                    path = path[1:]

                    for cell in path:
                        pacman.move(cell)
                        self.update_score(SCORE_PENALTY)

                        if cell in monster_pos_list:
                            break

                        pygame.time.delay(
                            int(SPEED //
                                self.speed_list[self.cur_speed_index][1]))

                        if self.launch_game_event():
                            back_home = True
                            break

                if not back_home:
                    self.state = STATE_GAMEOVER
                    pygame.time.delay(2000)
            else:
                goal = path[-1]
                path = path[1:-1]

                for cell in path:
                    pacman.move(cell)
                    self.update_score(SCORE_PENALTY)
                    pygame.time.delay(
                        int(SPEED // self.speed_list[self.cur_speed_index][1]))

                    if self.launch_game_event():
                        back_home = True
                        break

                if not back_home:
                    pacman.move(goal)
                    self.update_score(SCORE_PENALTY + SCORE_BONUS)
                    self.state = STATE_VICTORY
                    pygame.time.delay(2000)
Example #14
0
def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT, SCORE_SURF, SCORE_RECT, SOLVE_SURF, SOLVE_RECT
    global walls, pacmanPos, capsulePos, game, pacman, score, scoreText
    score = 0
    filename = ".\\layouts\\smallestMaze.lay"
    game = PacGame(filename)

    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode(
        (game.WINDOWWIDTH, game.WINDOWHEIGHT))
    pygame.display.set_caption('PacMan')
    BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)
    BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)

    # Store the option buttons and their rectangles in OPTIONS.
    scoreText = 'SCORE:' + str(score)
    SCORE_SURF, SCORE_RECT = makeText(scoreText, TEXTCOLOR, BGCOLOR, 10,
                                      game.WINDOWHEIGHT - 40)
    DISPLAYSURF.blit(SCORE_SURF, SCORE_RECT)
    game.genMaze()
    pacmanPos = game.pacmanPos

    walls = game.walls
    allMoves = []  # list of moves made from the solved configuration
    game.drawWall(DISPLAYSURF)
    pacman = Pacman(pacmanPos, 0, PACCOLOR, PAC_SIZE, 0, walls,
                    game.MAZE_WIDTH, game.MAZE_HEIGHT)
    pacman.drawPacman(DISPLAYSURF)
    game.drawCapsule(DISPLAYSURF)
    p_graph = build_graph(game)
    pygame.time.wait(2000)
    slideTo = None  # the direction, if any, a tile should slide
    scores = 0
    pygame.display.update()

    if (len(sys.argv) <= 1):
        while True:  # main game loop
            for event in pygame.event.get():  # event handling loop
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYUP:
                    # check if the user pressed a key to slide a tile
                    if event.key in (K_LEFT, K_a):
                        slideTo = 'West'
                    elif event.key in (K_RIGHT, K_d):
                        slideTo = 'East'
                    elif event.key in (K_UP, K_w):
                        slideTo = 'North'
                    elif event.key in (K_DOWN, K_s):
                        slideTo = 'South'
                    if slideTo and len(game.capsulePos) > 0:
                        slideAnimation(slideTo, "Ok", 8)  #
                        scores += 1
                        pygame.display.update()
                        FPSCLOCK.tick(FPS)
                        scoreText = 'SCORE:' + str(scores)
                        SCORE_SURF, SCORE_RECT = makeText(
                            scoreText, TEXTCOLOR, BGCOLOR, 10,
                            game.WINDOWHEIGHT - 40)
                        DISPLAYSURF.blit(SCORE_SURF, SCORE_RECT)
                    pygame.display.update()
                    FPSCLOCK.tick(FPS)
    else:
        if (sys.argv[1] == 'auto'):
            choices = ['East', 'West', 'North', 'South']
            while True:  # main game loop
                for event in pygame.event.get():  # event handling loop
                    if event.type == QUIT:
                        pygame.quit()
                        sys.exit()
                #scores=0
                while (game.capsulePos):
                    pac_actions = []
                    #Q6) add a simple reflex agent:It randomly choose an action,
                    # and append it to the list pac_actions
                    # you may need nextDirectionIsValid(direction, pacman.pos[0]) in pacmanGame.py

                    pac_actions = find_solution(p_graph)
                    game.pacmanPos.pop(0)
                    game.pacmanPos.append(game.capsulePos[0])
                    while (pac_actions):
                        slideTo = pac_actions.pop(0)
                        if slideTo:
                            slideAnimation(slideTo, "Ok", 8)  #
                        scores += 1
                        FPSCLOCK.tick(FPS)
                        scoreText = 'SCORE:' + str(scores)
                        SCORE_SURF, SCORE_RECT = makeText(
                            scoreText, TEXTCOLOR, BGCOLOR, 10,
                            game.WINDOWHEIGHT - 40)
                        DISPLAYSURF.blit(SCORE_SURF, SCORE_RECT)

                pygame.display.update()
                FPSCLOCK.tick(FPS)
Example #15
0
import Pacman as p
import Map as m
import Ghost as g

pacman = p.Pacman()
ghost = g.Ghost()

#--- map representation ---#

table = [[0 for i in range(28)] for j in range(31)]
table_representation = \
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
[1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1], 
[1, 8, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 8, 1], 
[1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1], 
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
[1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1], 
[1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1], 
[1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 6, 1, 1, 6, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 6, 1, 1, 6, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 6, 6, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1, 1, 0, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
Example #16
0
maxTime = float(input('Maximum time for player to make a move? '))

if input('Text player (0) or your player (1) ') == '0':
    player = TextPlayer(maxTime)
else:
    player = MyPlayer(maxTime)

mapId = int(input('What map do you want to use (0-3): '))
if mapId == 0:  # Wide ope\n, o\ne ghost
    gameMap = '###############\n#.............#\n#.P.........O.#\n#.............#\n#.............#\n#...........G.#\n#.............#\n###############'.split(
        '\n')
elif mapId == 1:  #   Trapped!
    gameMap = '########\n#   P G#\n#G######\n#......#\n########'.split('\n')
elif mapId == 2:  # Classic
    gameMap = '############################\n#............##............#\n#.####.#####.##.#####.####.#\n#O####.#####.##.#####.####O#\n#.####.#####.##.#####.####.#\n#..........................#\n#.####.##.########.##.####.#\n#.####.##.########.##.####.#\n#......##....##....##......#\n######.##### ## #####.######\n######.##### ## #####.######\n######.#            #.######\n######.# ####  #### #.######\n#     .  #G  GG  G#  .     #\n######.# ########## #.######\n######.#            #.######\n######.# ########## #.######\n#............##............#\n#.####.#####.##.#####.####.#\n#.####.#####.##.#####.####.#\n#O..##.......  .......##..O#\n###.##.##.########.##.##.###\n###.##.##.########.##.##.###\n#......##....##....##......#\n#.##########.##.##########.#\n#.............P............#\n############################'.split(
        '\n')
elif mapId == 3:  # Small
    gameMap = '####################\n#......#G  G#......#\n#.##...##  ##...##.#\n#.#O.#........#.O#.#\n#.##.#.######.#.##.#\n#........P.........#\n####################'.split(
        '\n')
gameMap = Map(gameMap)

size = int(input('Size of graphics screen (0 for text): '))
if size > 0:
    from GraphicsDisplay import *
    display = GraphicsDisplay(gameMap, size)
else:
    display = TextDisplay(gameMap)

p = Pacman(gameMap, 500, maxTime, player, display)
p.play()
Example #17
0
    life_count = new_life_count
    game_start_time = float('inf')






# Initialising the screen.
window_surface = pygame.display.set_mode( ( WINDOW_WIDTH , WINDOW_HEIGHT) )
pygame.display.set_caption(CAPTION)

# Game Objects.
clock = pygame.time.Clock()
maze = Maze.Maze( os.path.join(os.getcwd() , "res" , "levels" , "{}.json".format(LEVEL)))
pacman = Pacman.Pacman(336 , 504)
ghosts_not_in_maze = [ Ghost.Ghost(
                        os.path.join(os.getcwd() , 'res' , 'tiles' , 'ghost-{}.gif'.format(ghost_name)),
                         13 * 24 , 13 * 24) for ghost_name in [ "sue",
                                                                "inky",
                                                                "pinky",
                                                                "blinky"]]
# Setting AI level of the ghosts.
ghosts_not_in_maze[0].AI_level = 50
ghosts_not_in_maze[1].AI_level = 15
ghosts_not_in_maze[2].AI_level = 5
ghosts_not_in_maze[3].AI_level = 0

ghosts_in_maze = []

Example #18
0
    def __runGame(self):
        self.__openingTheme = pygame.mixer.Sound('pacman_beginning.wav')
        self.__openingTheme.play()
        #plays intro music
        #http://www.pygame.org/docs/ref/mixer.html

        self.__pelletList = pygame.sprite.Group()
        self.__allSprites = pygame.sprite.Group()
        self.__wallList = pygame.sprite.Group()
        self.__ghostsList = pygame.sprite.Group()
        #In pygame, Group is a class containing objects created by the Sprite
        #class
        #http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group

        #creates an instance of the pacman sprite
        self.__direction = "right"
        self.__pacman = Pacman(self.__direction, 216, 216, window)
        #http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.add
        #adds a sprite to a group
        self.__allSprites.add(self.__pacman)

        #initializes all variables
        self.__moveX = 0
        self.__moveY = 0
        self.__score = 0
        self.__compare = 0
        self.__changeGhost = 0
        self.__die = 0
        self.__timeDelay = 0

        # creates the walls
        self.__wallX1 = [#row1
                         0,24,48,72,96,120,144,168,192,216,240,264,288,312,
                         336,360,384,408,432,\
                         #row2

                         0,216,432,\
                         #row3

                         0,48,72,96,144,168,216,264,288,336,360,384,432,\
                         #row4

                         0,432,\
                         #row5

                         0,24,72,120,168,192,216,240,264,312,360,408,432,\
                         #row6

                         0,120,216,312,432,\
                         #row7

                         0,24,48,72,120,192,240,312,360,384,408,432,\
                         #row8

                         0,24,48,72,120,312,360,384,408,432,\
                         #row9

                         0,24,48,72,120,168,192,240,264,312,360,384,408,432,\
                         #row10

                         0,168,264,432,\
                         #row11

                         0,48,72,120,168,192,216,240,264,312,360,384,432,\
                         #row12

                         0,48,72,360,384,432,\
                         #row13

                         0,48,72,120,168,192,216,240,264,312,360,384,432,\
                         #row14

                         0,216,432,\
                         #row15

                         0,48,72,120,144,168,216,264,288,312,360,384,432,\
                         #row16

                         0,72,360,432,\
                         #row17

                         0,24,72,120,168,192,216,240,264,312,360,408,432,\
                         #row18

                         0,120,216,312,432,\
                         #row19

                         0,48,96,120,144,168,264,288,312,336,384,432,\
                         #row20

                         0,432,
                         #row21
                         0,24,48,72,96,120,144,168,192,216,240,264,288,312,\
                         336,360,384,408,432]

        self.__wallY1 = [  #row1
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            #row2
            24,
            24,
            24,
            #row3
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            48,
            #row4
            72,
            72,
            #row5
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            96,
            #row6
            120,
            120,
            120,
            120,
            120,
            #row7
            144,
            144,
            144,
            144,
            144,
            144,
            144,
            144,
            144,
            144,
            144,
            144,
            #row8
            168,
            168,
            168,
            168,
            168,
            168,
            168,
            168,
            168,
            168,
            #row9
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            192,
            #row10
            216,
            216,
            216,
            216,
            #row11
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            240,
            #row12
            264,
            264,
            264,
            264,
            264,
            264,
            #row13
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            288,
            #row14
            312,
            312,
            312,
            #row15
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            336,
            #row16
            360,
            360,
            360,
            360,
            #row17
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            384,
            #row18
            408,
            408,
            408,
            408,
            408,
            #row19
            432,
            432,
            432,
            432,
            432,
            432,
            432,
            432,
            432,
            432,
            432,
            432,
            #row20
            456,
            456,
            #row21
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480,
            480
        ]
        #goes through wall coordinate lists and spawns each square wall
        for i in range(len(self.__wallX1)):
            self.__wall = Walls(self.__wallX1[i], self.__wallY1[i])
            self.__wallList.add(self.__wall)

        #creates the pellets
        # X-coordinates for the pellets
        self.__x1 = [#row1
                     36,60,84,108,132,156,180,204,252,276,300,\
                     324,348,372,396,420,\
                     #row2

                     36,132,204,252,324,420,\
                     #row3

                     36,60,84,108,132,156,180,204,228,252,276,300,\
                     324,348,372,396,420,\
                     #row4

                     60,108,156,300,348,396,\
                     #row5

                     36,60,84,108,156,180,204,252,276,300,348,372,396,420,\
                     #row6

                     108,156,180,228,276,300,348,\
                     #row7

                     108,156,180,204,228,252,276,300,348,\
                     #row8

                     108,156,300,348,\
                     #row9

                     36,60,84,108,132,156,300,324,348,372,396,420,\
                     #row10

                     36,108,156,300,348,420,\
                     #row11

                     36,108,132,156,180,204,228,252,276,300,324,348,420,\
                     #row12

                     36,108,156,300,348,420,\
                     #row13

                     36,60,84,108,132,156,180,204,252,276,300,324,348,372,\
                     396,420,\
                     #row14

                     36,108,204,252,348,420,\
                     #row15

                     36,60,108,132,156,180,204,228,252,276,300,324,348,396,420,\
                     #row16

                     60,108,156,300,348,396,\
                     #row17

                     36,60,84,108,156,180,204,252,276,300,348,372,396,420,\
                     #row18

                     36,84,204,228,252,372,420,\
                     #row19

                     36,60,84,108,132,156,180,204,228,252,276,300,324,348,\
                     372,396,420]

        # Y-cooridnates for the pellets
        self.__y1 = [#row1
                     36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,\
                     #row2

                     60,60,60,60,60,60,\
                     #row3

                     84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,\
                     #row4

                     108,108,108,108,108,108,\
                     #row5

                     132,132,132,132,132,132,132,132,132,132,132,132,132,132,\
                     #row6

                     156,156,156,156,156,156,156,\
                     #row7

                     180,180,180,180,180,180,180,180,180,\
                     #row8

                     204,204,204,204,\
                     #row9

                     228,228,228,228,228,228,228,228,228,228,228,228,\
                     #row10

                     252,252,252,252,252,252,\
                     #row11

                     276,276,276,276,276,276,276,276,276,276,276,276,276,\
                     #row12

                     300,300,300,300,300,300,\
                     #row13

                     324,324,324,324,324,324,324,324,324,324,324,324,324,324,\
                     324,324,\
                     #row14

                     348,348,348,348,348,348,\
                     #row15

                     372,372,372,372,372,372,372,372,372,372,372,372,372,\
                     372,372,\
                     #row16

                     396,396,396,396,396,396,\
                     #row17

                     420,420,420,420,420,420,420,420,420,420,420,420,420,420,\
                     #row18

                     444,444,444,444,444,444,444,\
                     #row19

                     468,468,468,468,468,468,468,468,468,\
                     468,468,468,468,468,468,468,468]

        #goes through pellet coordinate lists and spawns each pellet
        for i in range(len(self.__x1)):
            self.__pellet = Pellets(white, 5, 5)
            self.__pellet.rect.x = self.__x1[i]
            self.__pellet.rect.y = self.__y1[i]
            self.__pelletList.add(self.__pellet)
            self.__allSprites.add(self.__pellet)

        # creates an instance of each ghost
        self.__victoria = Ghosts("victoria.png", 0, 0, window)
        self.__margie = Ghosts("margie.png", 408, 0, window)
        self.__nick = Ghosts("nick.png", 0, 456, window)
        self.__ryan = Ghosts("ryan.png", 408, 456, window)

        #adds each ghost to ghost list
        self.__ghostsList.add(self.__victoria)
        self.__ghostsList.add(self.__margie)
        self.__ghostsList.add(self.__nick)
        self.__ghostsList.add(self.__ryan)

        #loop to run the game
        self.__gameLoop = True
        while self.__gameLoop == True:
            # http://www.pygame.org/docs/ref/event.html#pygame.event.get
            # gets event from the queue
            for event in pygame.event.get():
                if (event.type == pygame.QUIT):
                    gameLoop = False

                # http://www.pygame.org/docs/ref/key.html
                # checks the event type based on certain key presses
                elif (event.type == pygame.KEYDOWN):
                    if (event.key == pygame.K_LEFT):
                        self.__moveX = -1
                        self.__moveY = 0
                        self.__direction = "left"
                    elif (event.key == pygame.K_RIGHT):
                        self.__moveX = 1
                        self.__moveY = 0
                        self.__direction = "right"
                    elif (event.key == pygame.K_UP):
                        self.__moveX = 0
                        self.__moveY = -1
                        self.__direction = "up"
                    elif (event.key == pygame.K_DOWN):
                        self.__moveX = 0
                        self.__moveY = 1
                        self.__direction = "down"

                elif (event.type == pygame.KEYUP):
                    if (event.key == pygame.K_LEFT):
                        self.__moveX = 0
                        self.__moveY = 0
                        self.__direction = "left"
                    elif (event.key == pygame.K_RIGHT):
                        self.__moveX = 0
                        self.__moveY = 0
                        self.__direction = "right"
                    elif (event.key == pygame.K_UP):
                        self.__moveY = 0
                        self.__moveY = 0
                        self.__direction = "up"
                    elif (event.key == pygame.K_DOWN):
                        self.__moveY = 0
                        self.__moveY = 0
                        self.__direction = "down"

            window.fill(black)

            # gets x and y coords
            self.__x = self.__pacman.getX()

            self.__y = self.__pacman.getY()

            # sets x and y new coords
            self.__pacman.setX(self.__x + self.__moveX)

            self.__pacman.setY(self.__y + self.__moveY)

            #http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.draw
            # sets rect values equal to pacman's new values
            self.__pacman.rect.x += self.__moveX

            self.__pacman.rect.y += self.__moveY

            # draws the pellets
            self.__pelletList.draw(window)

            # draws the walls
            self.__wallList.draw(window)

            # has the ghosts chnage position every 50 loops of the game
            if self.__changeGhost % 50 == 0:
                #Victoria
                #gives the new x-values a random number
                self.__victX = random.randint(0, 408)

                #gives the new y-values a random number
                self.__victY = random.randint(0, 456)

                #sets the new x-value in ghost the class
                self.__victoria.setX(self.__victX)

                #sets the new y-value in ghost the class
                self.__victoria.setY(self.__victY)

                #changes the rect's x and y to equal the ghosts
                self.__victoria.rect.x = self.__victX

                self.__victoria.rect.y = self.__victY

                #Margie

                self.__margX = random.randint(0, 408)

                self.__margY = random.randint(0, 456)

                self.__margie.setX(self.__margX)

                self.__margie.setY(self.__margY)

                self.__margie.rect.x = self.__margX

                self.__margie.rect.y = self.__margY

                #Nick

                self.__nickX = random.randint(0, 408)

                self.__nickY = random.randint(0, 456)

                self.__nick.setX(self.__nickX)

                self.__nick.setY(self.__nickY)

                self.__nick.rect.x = self.__nickX

                self.__nick.rect.y = self.__nickY

                #Ryan

                self.__ryanX = random.randint(0, 408)

                self.__ryanY = random.randint(0, 456)

                self.__ryan.setX(self.__ryanX)

                self.__ryan.setY(self.__ryanY)

                self.__ryan.rect.x = self.__ryanX

                self.__ryan.rect.y = self.__ryanY

                # renders the ghosts
                self.__victoria.flip()
                self.__margie.flip()
                self.__nick.flip()
                self.__ryan.flip()

            # draws the ghosts in the same spot everytime the changeGhost
            # is not a multiple of 50
            else:
                self.__victoria.flip()
                self.__margie.flip()
                self.__nick.flip()
                self.__ryan.flip()

            # adds 1 each loop so that it knows when the loop is a multiple
            # of 50
            self.__changeGhost += 1

            #http://www.pygame.org/docs/ref/sprite.html\
            ##pygame.sprite.spritecollide
            # Collision detection for the Pellets and deletes the pellet
            self.__pelletHitList = pygame.sprite.\
                                   spritecollide(self.__pacman,\
                                                 self.__pelletList, True)
            #adds 1 to the score each time  there is a pellet collision
            for self.__pellet in self.__pelletHitList:
                self.__score += 1

            # if all dots are eaten displays the win screen
            if self.__score == 197:
                self.__winScreen()

            # collision detection for the ghosts and pacman
            self.__ghostHitList = pygame.sprite.\
                                   spritecollide(self.__pacman,\
                                                 self.__ghostsList, True)

            # add 1 to die if ghostHitList goes up
            for self.__ghost in self.__ghostHitList:
                self.__die += 1

            # checks if ghost hit list is more than 1
            if self.__die > 0:
                #allows for a 50 frame delay so the ghost collision is visible
                if self.__timeDelay == 50:
                    self.__loseScreen(self.__score)
                # once a ghost hit this goes up so on the next loop the lose
                # screen will display
                self.__timeDelay += 50

            # collision detection for walls
            self.__collided = pygame.sprite.spritecollide(self.__pacman,\
                                                          self.__wallList,\
                                                          False)
            # if there is a wall collision occurs runs
            if self.__compare < len(self.__collided):
                # if moving right and hits wall, everything will change to
                # equal the left conditions
                if self.__direction == "right":
                    self.__moveX = -1
                    self.__moveY = 0
                    self.__direction = "left"
                elif self.__direction == "left":
                    self.__moveX = 1
                    self.__moveY = 0
                    self.__direction = "right"
                elif self.__direction == "down":
                    self.__moveY = 0
                    self.__moveY = -1
                    self.__direction = "up"
                elif self.__direction == "up":
                    self.__moveY = 0
                    self.__moveY = 1
                    self.__direction = "down"

            # sets direction in Pacman class
            self.__pacman.setDirection(self.__direction)

            # updates pacman
            self.__pacman.flip()

            # 60 frames per second
            clock.tick(60)

            # updates the display
            pygame.display.update()
Example #19
0
import random

pygame.init()

WIDTH = 360
HEIGHT = 640

clock = pygame.time.Clock()
screen = pygame.display.set_mode((HEIGHT, WIDTH))
map = Level.Level(screen, HEIGHT, WIDTH)

ghost = Ghost.Ghost(screen, map, (170, 20, 20))
ghosttwo = Ghost.Ghost(screen, map, (170, 84, 236))
ghostthree = Ghost.Ghost(screen, map, (18, 191, 47))
ghostfour = Ghost.Ghost(screen, map, (255, 18, 191))
pacmanA = Pacman.Pacman(screen, map, 0,
                        [ghost, ghosttwo, ghostthree, ghostfour])
pacmanB = Pacman.Pacman(screen, map, 1,
                        [ghost, ghosttwo, ghostthree, ghostfour])

drawables = [map, ghost, ghosttwo, ghostthree, ghostfour, pacmanA, pacmanB]
updatables = [pacmanA, pacmanB, ghost, ghosttwo, ghostthree, ghostfour]
b1 = 0

while (True):
    screen.fill((0, 0, 0))

    for drawable in drawables:
        drawable.draw()

    keys = pygame.key.get_pressed()
    for updatable in updatables:
Example #20
0
def gameloop():
    """
    Description: the main loop that will run forever while the game is on.
    Returns: play(bool): return False if the quit button is pressed by the
    user, return True otherwise.
    """
    global pacman_map, pacman, pyman, won, counter, end
    # load the map and get the RGB values of the wall colour generated randomly
    wall_colour = map_load()

    # Create the pacman(and pyman, for mode 3) object(s).
    pacman = Pacman(9, 16, pacman_map, "right", "pacman")
    if gamemode == 3:
        pyman = Pacman(9, 18, pacman_map, "right", "pyman")

    # initialize the timer to tick every 1000ms(1s)
    pygame.time.set_timer(pygame.USEREVENT, 1000)
    end = False
    play = True

    # intialize the ghost objects
    ghost_list = ghost_init()

    while not won and not end:
        # control the pacman with 4 move keys
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    pacman.Left()
                elif event.key == pygame.K_RIGHT:
                    pacman.Right()
                elif event.key == pygame.K_UP:
                    pacman.Up()
                elif event.key == pygame.K_DOWN:
                    pacman.Down()
                pacman.eat_pacdot()

                if gamemode == 3:
                    # add another 4 keys for pyman in mode 3
                    if event.key == pygame.K_a:
                        pyman.Left()
                    elif event.key == pygame.K_d:
                        pyman.Right()
                    elif event.key == pygame.K_w:
                        pyman.Up()
                    elif event.key == pygame.K_s:
                        pyman.Down()
                    pyman.eat_pacdot()

            # tracks if the user pressed the quit button
            if event.type == pygame.QUIT:
                play = False
                end = True

            if gamemode != 1:
                # set time count down for mode 2 and 3
                if event.type == pygame.USEREVENT:
                    counter -= 1

        # determine the end conditions for the game(different end conditions
        # apply to each mode)
        if pacman.score <= 0 or counter <= 0 or \
           (eaten[0] and eaten[1] and eaten[2] and eaten[3]):
            screen.fill((0, 0, 0))
            end = True
        if gamemode == 3:
            if pyman.score <= 0:
                screen.fill((0, 0, 0))
                end = True

        screen.fill((0, 0, 0))
        # draw the map with the correspond random colour
        map_draw(wall_colour)

        # the loop part is different for each mode
        if gamemode == 1:
            gm1_loop(ghost_list)
        elif gamemode == 2:
            gm2_loop(ghost_list)
        elif gamemode == 3:
            gm3_loop(ghost_list)

        pacman.draw(screen)
        # set the 4 ghosts as different modes
        modes = [1, 2, 3, 2]

        for i in range(0, 4):
            if gamemode == 2:
                # all ghosts for mode 2 move randomly
                ghost_list[i].move(pacman, 2)
            else:
                # each ghost will follow their own algorithm based their
                # given mode defined in the mode list(this mode is different
                # from gamemode)
                ghost_list[i].move(pacman, modes[i])

        # calls the display function to display texts if certain
        # condition is satisfied
        display()

        # update the screen
        pygame.display.flip()

        # set the frame rate per second(fps)
        clock = pygame.time.Clock()
        clock.tick(66)

    return(play)
Example #21
0
 def setUp(self):
     self.player = Pacman(-1, -1)
     self.ghosts = Ghosts(self.player)
     self.board = Board(self.ghosts, self.player)
Example #22
0
def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT, SCORE_SURF, SCORE_RECT
    global walls, capsulePos, game, pacman, score, scoreText
    PACMANPLAYER = True

    filename = ".\\layouts\\ASTinyMaze2.lay"
    #filename = ".\\layouts\\ADSmallClassic.lay"
    # filename = ".\\layouts\\ASMediumClassic.lay"
    # filename = ".\\layouts\\ASminimaxClassic.lay"
    # filename = ".\\layouts\\ADSmallClassic.lay"
    # filename = ".\\layouts\\smallDottedMaze.lay"

    scores = 0
    if (len(sys.argv) > 1):
        print(sys.argv[1])
        gAgent = sys.argv[1]
    else:
        gAgent = "random"
    game = PacGame(filename)
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode(
        (game.WINDOWWIDTH, game.WINDOWHEIGHT))

    strS = game.strS
    pygame.display.set_caption('PacMan')
    BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)
    BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)

    # Store the option buttons and their rectangles in OPTIONS.
    scoreText = 'SCORE:' + str(scores)
    SCORE_SURF, SCORE_RECT = makeText(scoreText, TEXTCOLOR, BGCOLOR, 10,
                                      game.WINDOWHEIGHT - 40)
    DISPLAYSURF.blit(SCORE_SURF, SCORE_RECT)
    game.genMaze()
    walls = game.walls
    game.drawWall(DISPLAYSURF)
    pacman = Pacman(game.pacmanPos, 0, PACCOLOR, PAC_SIZE, 0, walls,
                    game.MAZE_WIDTH, game.MAZE_HEIGHT)
    pacman.drawPacman(DISPLAYSURF)
    game.drawCapsule(DISPLAYSURF)
    game.drawFoods(DISPLAYSURF)
    ghost = Ghost(game, PINK, 0)
    ghost.drawGhost(DISPLAYSURF)
    problem = PacmanAdversarialGameProblem(game)
    pacmanAdvAgent = PacmanAdvGameAgent(problem)
    ghostAgent = GhostGameAgent(problem)
    pygame.time.wait(1000)
    slideTo = None
    stop = False
    while not stop:  # main game loop
        for event in pygame.event.get():  # event handling loop
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        while (game.capsulePos or game.foodPos):
            for event in pygame.event.get():  # event handling loop
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            if PACMANPLAYER:
                (collision, pac_action, new_pos) = pacmanAdvAgent.get_action()
                if collision:
                    stop = True
                    break
                currentPos = game.pacmanPos.pop(0)
                game.pacmanPos.append(new_pos)
                if new_pos in game.capsulePos:
                    index = game.capsulePos.index(new_pos)
                    game.capsulePos.pop(index)
                    t = pygame.time.get_ticks()
                    scores += int(t / 10000) + 1
                elif new_pos in game.foodPos:
                    index = game.foodPos.index(new_pos)
                    game.foodPos.pop(index)
                slideTo = pac_action
                if slideTo:
                    slideAnimation(pacman, currentPos, slideTo, "Ok", 8)  #

                scores += 1
                pygame.display.update()
                FPSCLOCK.tick(FPS)
            else:  #ghost play
                (collision, action, new_pos) = ghostAgent.get_action(gAgent)
                if collision:
                    stop = True
                    break
                currentPos = game.ghostPos.pop(0)
                game.ghostPos.append(new_pos)
                slideTo = action
                if slideTo:
                    slideAnimation(ghost, currentPos, slideTo, "Ok", 8)  #

                pygame.display.update()
                FPSCLOCK.tick(FPS)
            scoreText = 'SCORE:' + str(scores)
            SCORE_SURF, SCORE_RECT = makeText(scoreText, TEXTCOLOR, BGCOLOR,
                                              10, game.WINDOWHEIGHT - 40)
            DISPLAYSURF.blit(SCORE_SURF, SCORE_RECT)
            PACMANPLAYER = (not PACMANPLAYER)
        pygame.display.update()
        FPSCLOCK.tick(FPS)
Example #23
0
def place(words):
    arg = words[1].split(',')
    pm = Pacman(int(arg[0]), int(arg[1]), str(arg[2]))
    return pm