Example #1
0
 def loop(self, player, item_factory, ghost_factory):
     if self.game_state == "run":
         ghost_factory.activation()
         player.move()
         item_factory.check_collisions()
         Ghost.move_all()
         Ghost.check_collisions()
Example #2
0
    def draw(self, display, maze, player, item_factory):
        pygame.draw.rect(display, (0, 0, 0),
                         (0, 0, self.display_width, self.display_height))

        maze.draw()
        item_factory.draw_all()
        player.draw(self.game_state)
        Ghost.draw_ghosts()

        game_font = pygame.freetype.SysFont("Helvetica.ttf", 40)
        game_font.render_to(display, (15, 15), "SCORE: " + str(self.score),
                            (255, 255, 255))
        game_font = pygame.freetype.SysFont("Helvetica.ttf", 20)
        game_font.render_to(display, (300, 15),
                            str(self.lives) + " LIVES", (255, 255, 255))
Example #3
0
    def __init__(self, gui_root, pac_actions):
        self.gui_root = gui_root
        self.canvas = tk.Canvas(self.gui_root,
                                bg='red',
                                width=1000,
                                height=500)
        self.canvas.pack()

        self.pac_actions = pac_actions
        self.lines = []

        self.n_pac_balls = 3
        self.pac_balls = []
        self.pac_balls_coord = []

        self.initUI()
        self.gui_root.bind('<KeyPress>', self.keydown)

        self.PacMan = PacMan(self.canvas, self.lines, self.n_pac_balls,
                             self.pac_balls, self.pac_balls_coord)

        self.Ghost = Ghost(self.canvas, self.lines, 212, 162)

        self.PacMan.start()

        return
Example #4
0
    def Load(self):  # Basic logic of making Load(self) is adapted from [1]
        self.background = pygame.image.load('maze2.png')
        self.background = pygame.transform.scale(
            self.background,
            (WIDTH, HEIGHT))  # To fatima: You don't actually need this line

        enemyPos = []

        with open("Maps.txt", 'r') as file:
            for y, line in enumerate(file):
                for x, char in enumerate(line):
                    if (char == '1'):
                        self.walls.append(vec(x, y))
                    elif (char in "2"):
                        # enemyPos.append((vec(x, y), char))
                        enemyPos.append(vec(x, y))
                    elif (char == 'D'):
                        self.doors.append(vec(x, y))
                    elif (char == 'P'):
                        self.player = Player(self, vec(x, y))
                    elif (char == 'C'):
                        self.coins.append(vec(x, y))
                        self.remainingCoins += 1

        G = self.LoadGraph()

        for pos in enemyPos:
            # self.ghosts.append(Ghost(self, pos[0], pos[1], G))
            self.ghosts.append(Ghost(self, pos, G))
Example #5
0
def run(state, numGhosts, intelligenceLevel, IDS, verbose):

    # Run with Q Table
    if not IDS:
        board = B.GameBoard(state)
        p = P.PacMan(board.pacManSpawnPt)
        ghosts = []
        for i in range(numGhosts):
            ghosts.append(G.Ghost(board.ghostSpawnPt))
        if verbose:
            print("\tRunning PacMan with Q Table\n\tTraining Q Table...")
        Q, scores = p.trainQ(board, 30, 0.5, 0.7, ghosts, intelligenceLevel)
        if verbose: print("\tDone!\n\tRunning game...")
        results = PG.startGame(board, p, ghosts, Q, intelligenceLevel, False,
                               False)
        if verbose: print("\tDone!")
        ghostInfo = "[" + str(numGhosts) + ", " + str(intelligenceLevel) + "]"
        print("\t", ghostInfo, "Q Table Results:\t\tTurns:", results[0],
              "\tScore:", results[1], "\tLives left:", results[2],
              "\tDots left:", results[3])
    # Run with Pacman IDS
    else:
        avgResults = [0, 0, 0, 0, 0]
        if verbose: print("\tRunning PacMan with IDS 30 times")
        for i in range(30):
            board = B.GameBoard(state)
            p = P.PacMan(board.pacManSpawnPt)
            ghosts = []
            for j in range(numGhosts):
                ghosts.append(G.Ghost(board.ghostSpawnPt))
            Q = []
            results = PG.startGame(board, p, ghosts, Q, intelligenceLevel,
                                   True, False)
            if verbose:
                print("\tIDS", (i + 1), "results:\t\tTurns:", results[0],
                      "\tScore:", results[1], "\tLives left:", results[2],
                      "\tMoves explored:", results[3], "\tDots left:",
                      results[4])
            for j in range(len(results)):
                avgResults[j] += results[j]
        if verbose: print("\tDone!")
        for i in range(len(avgResults)):
            avgResults[i] = int(avgResults[i] / 30)
        ghostInfo = "[" + str(numGhosts) + ", " + str(intelligenceLevel) + "]"
        print("\t", ghostInfo, "IDS 30-average results:\t\tTurns:",
              avgResults[0], "\tScore:", avgResults[1], "\tLives left:",
              avgResults[2], "\tDots left:", avgResults[3])
Example #6
0
 def init_ghosts(self):
     width = self.screen_map.get_height() // len(self.map)
     qw = width // 4  #quater width
     spawn = get_ghost_spawn(self.map)
     sp_i = spawn[0]
     sp_j = spawn[1]
     blinky = Ghost("Blinky", width + 2 * qw, self.map, [sp_i, sp_j + 2],
                    width)
     pinky = Ghost("Pinky", width + 2 * qw, self.map, [sp_i, sp_j + 3],
                   width)
     inky = Ghost("Inky", width + 2 * qw, self.map, [sp_i + 1, sp_j + 2],
                  width)
     clyde = Ghost("Clyde", width + 2 * qw, self.map, [sp_i + 1, sp_j + 3],
                   width)
     ghosts = []
     ghosts.append(blinky)
     ghosts.append(pinky)
     ghosts.append(inky)
     ghosts.append(clyde)
     return ghosts
Example #7
0
    def move(self):
        step = self.step_len
        self.array_coord = [
            int((self.x + self.block_size / 2) / self.block_size),
            int((self.y + self.block_size / 2) / self.block_size)
        ]

        if self.powered_up:
            # end power up at end of timer
            if self.timer >= self.power_time * self.main.fps:
                self.powered_up = False
                Ghost.end_blue()
            else:
                self.timer += 1

        # Can only change direction within the bounds of the maze
        if self.block_size < self.x < self.main.display_width - self.block_size:
            # Change movement direction to match look direction if possible
            if self.look_dir != self.move_dir:
                if self.maze.can_move(self, self.look_dir):
                    self.move_dir = self.look_dir

            # Do movement
            if self.maze.can_move(self, self.move_dir):
                self.x += step * self.COORD_DIR[self.move_dir][0]
                self.y += step * self.COORD_DIR[self.move_dir][1]

        # If outside maze, keep moving forwards until wrapped to the other side of the screen
        else:
            self.maze.center(self, "y", self.y)
            if self.move_dir == self.DIR["LEFT"]:
                self.x -= step
            if self.move_dir == self.DIR["RIGHT"]:
                self.x += step
            # Screen wrap
            if self.x < -self.size:
                self.x = self.main.display_width
            if self.x > self.size + self.main.display_width:
                self.x = -self.size
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 __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 #10
0
    def run(self):
        # initialize
        pygame.init()
        pygame.display.set_caption("PY-MAN")
        display_surf = pygame.display.set_mode(
            (self.display_width, self.display_height))
        pygame.font.init()

        # spawn maze and player
        maze = Maze.Maze(display_surf, self)
        player = PacMan.PacMan(9, 11, display_surf, maze, self)

        # generate all coins and power ups
        item_factory = Items.ItemFactory(maze, self.block_size, display_surf,
                                         player, self)
        item_factory.setup()

        # spawn ghosts
        ghost_factory = Ghost.GhostFactory(maze, display_surf, player, self)

        # running game loop
        while self.running:
            if self.game_state in ("run", "respawn"):

                # main game loop
                self.events(player)
                self.loop(player, item_factory, ghost_factory)
                self.draw(display_surf, maze, player, item_factory)

                # check win condition
                if self.coins >= self.total_coins:
                    self.game_state = "win"

                pygame.display.update()
                self.fps_clock.tick(self.fps)
                self.tick_counter += 1

            # end game at win/lose
            elif self.game_state == "win":
                self.running = False
            elif self.game_state == "lose":
                self.running = False
Example #11
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 #12
0
def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowSize(1200, 780)
    glutInitWindowPosition(0, 0)
    glutCreateWindow(bytes("Pac", "ascii"))
    init()
    glutDisplayFunc(RenderScene)
    create_list_lib()
    Pac()

    #glutKeyboardFunc(mykey)

    #glutSpecialFunc(specialDown)
    #glutSpecialUpFunc(specialUp)

    glEnable(GL_DEPTH_TEST)
    '''for the ghosts'''
    start_x = [11, 12, 15, 16]
    ghost = []
    for i in range(0, 4):  #for all gohsts
        ghost.append(Ghost(start_x[i], 14))
    ghost_color = [(255 / 255, 0, 0), (120 / 255, 240 / 255, 120 / 255),
                   (255 / 255, 200 / 255, 200 / 255),
                   (255 / 255, 125 / 255, 0)]
    for i in range(0, 4):
        ghost[i].x = start_x[i]
        ghost[i].y = 14
        ghost[i].eaten = False
        ghost[i].max_speed = 0.1 - 0.01 * i
        ghost[i].speed = ghost[i].max_speed
        #colorize ghosts
        for j in range(0, 3):
            ghost[i].color[j] = ghost_color[i][j]
    tp_array = []
    for k in range(0, 31):
        for l in range(0, 28):
            tp_array[k][l] = pebbele_array[k][l]
    pebbeles_left = 244
    glShadeModel(GL_SMOOTH)
    glMainLoop()
Example #13
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 #14
0
    # Really basic state to start with
    state = [['=', '=', '=', '=', '=', '=', '=', '=', '=', '=', '='],
             ['|', ' ', ' ', ' ', ' ', 'G', ' ', ' ', ' ', ' ', '|'],
             ['|', ' ', '=', '=', '=', ' ', '=', '=', '=', ' ', '|'],
             ['|', ' ', '|', ' ', '|', ' ', '|', ' ', '|', ' ', '|'],
             ['|', ' ', '=', '=', '=', ' ', '=', '=', '=', ' ', '|'],
             ['|', '.', '.', '.', '.', '.', '.', '.', '.', 'P', '|'],
             ['=', '=', '=', '=', '=', '=', '=', '=', '=', '=', '=']]

    # Start game with above state and 2 ghosts
    board = Board.GameBoard(state)
    # Create a Pacman object using this board
    p = P.PacMan(board.pacManSpawnPt)

    ghostsAvailable = [G.Ghost(board.ghostSpawnPt)]
    intelligenceLevel = 3

    # Train Q for p
    Q = []
    # Trains Q table and prints each game
    Q, scores = p.trainQ(board, 30, 0.5, 0.7, ghostsAvailable, intelligenceLevel, True)
    print(scores)

    # Runs startGame without Pacman intelligence and printing
    #startGame(board, p, ghostsAvailable, Q, intelligenceLevel, False, True)

    # Runs startGame with Pacman intelligence and not printing
    #startGame(board, p, ghostsAvailable, Q, intelligenceLevel, True, True)

    # Runs startGame with Q table and printing
Example #15
0
		pac.x=pac.x+1
		return pac.x
	elif(mov=='d'):
		matrix[pac.x][pac.y]="."
		pac.y=pac.y+1
		return pac.y




if __name__ == '__main__':
        max=coins()
	printit()
	print "Score:","0"
	ob1=Pacman()
	ob2=Ghost()
	ob1.x=3
	ob1.y=3
	ob2.x=5
	ob2.y=18
	while(1):
		if(max==ob1.t):
		    ob1.t=0
	            max=coins()
		print "Enter move:",
	        var=raw_input()
	        matrix=ob2.ghostPosition(matrix)
	        if(ob2.temp==1):
		    print "Final Score:",ob1.getscore()
		    print "GAME OVER",
		    break
Example #16
0
def main():
	Board=[]
	p=[]
	flag=0
	for i in range(0,16):
		for j in range(0,36):
			p.append('.')
		Board.append(p)
		p=[]
	
	n=60


#MAKE WALLS#60
	while n:
	
		p=randint(0,15)
		q=randint(0,35)
		while Board[p][q] !='.' :
			p=randint(0,15)
			q=randint(0,35)
		Board[p][q]='X'
		n=n-1
				
#PUT COINS#40
	n=40
	while n:
		p=randint(0,14)
		q=randint(0,34)
		while Board[p][q]!='.' :
			p=randint(0,14)
			q=randint(0,34)
		Board[p][q]='C'
		n=n-1
		
# put Pacman

	p=randint(0,14)
	q=randint(0,34)
	while Board[p][q]!='.' :
		p=randint(0,14)
		q=randint(0,34)
	Board[p][q]='P'
	initialx=p
	initialy=q

	
#put ghost

	p=randint(0,14)
	q=randint(0,34)
	while Board[p][q]!='.':
		p=randint(0,14)
		q=randint(0,34)
	if Board[p][q]!='C':
		Board[p][q]='G'
	ghostx=p
	ghosty=q
	
	for i in range(0,15) :
		for j in range(0,35):
			print Board[i][j],
		print '\n'

	
	
	hello=Pacman()
	hey=Person()
	hola=Ghost()
	score=0
	while True:
		if score==40:
			Board=[]
			p=[]
			flag=0
			for i in range(0,16):
				for j in range(0,36):
					p.append('.')
				Board.append(p)
				p=[]
	
			n=60


		#MAKE WALLS#60
			while n:
	
				p=randint(0,15)
				q=randint(0,35)
				while Board[p][q] !='.' :
					p=randint(0,15)
					q=randint(0,35)
				Board[p][q]='X'
				n=n-1
					
												
		#PUT COINS#40
			n=40
			while n:
				p=randint(0,14)
				q=randint(0,34)
				while Board[p][q]!='.' :
					p=randint(0,14)
					q=randint(0,34)
				Board[p][q]='C'
				n=n-1
		
		# put Pacman

			p=randint(0,14)
			q=randint(0,34)
			while Board[p][q]!='.' :
				p=randint(0,14)
				q=randint(0,34)
			Board[p][q]='P'
			initialx=p
			initialy=q

	
		#put ghost

			p=randint(0,14)
			q=randint(0,34)
			while Board[p][q]!='.':
				p=randint(0,14)
				q=randint(0,34)
			if Board[p][q]!='C':
				Board[p][q]='G'
			ghostx=p
			ghosty=q
			for i in range(0,15) :
					for j in range(0,35):
						print Board[i][j],
					print '\n'
			continue
			print "YOU HAVE COLLECTED ALL COINS , BOARD RELOADED :) "			
		flag=0
		print "ENTER A MOVE",
     		move=raw_input() 
		if move=='q':
			exit(0)
		else:
#q=
		
			q=hello.checkmove(move,initialx,initialy,Board,flag,score)
			initialx=q[1]
			initialy=q[2]
			Board=q[3]
			flag=q[4]
			score=q[5]
			if q[0]==0:
				flag=0
				print "OOPS!!!!A WALL TRY AGAIN!!!"
				for i in range(0,15) :
					for j in range(0,35):
						print Board[i][j],
					print '\n'
				continue
			else:
				le=hola.ghostPosition(Board,ghostx,ghosty)
				Board=le[0]
				ghostx=le[1]
				ghosty=le[2]
				'''
				if ghostx==initialx and ghosty==initialy:
					print "a ghost :O"
					flag=0
				'''
				final=checkghost(initialx,initialy,ghostx,ghosty)
				if final==1:
					print "a ghost :O"
					flag=0
					exit(0)
				else:
					woah=hello.collectCoin(initialx,initialy,Board,flag,score)	
					Board=woah[0]
					flag=1
					score=woah[2]
				
			
		for i in range(0,15) :
			for j in range(0,35):
				print Board[i][j],
			print '\n'

		print "SCORE",score
		flag=0
Example #17
0
import Level
import Pacman
import Dot
import Ghost
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))
Example #18
0
Ghost.containers = all, ghosts
Score.containers = all, hud

while True:
    level = Level("level1.lvl")
    player = players.sprites()[0]
    score = Score([100, height - 30])

    levNum = 1

    while len(ghosts.sprites()) < levNum + 1:
        s = [0,0]
        while s == [0,0]:
            s = [5 * random.randint(-1,1), 5* random.randint(-1,1)]
        p = [random.randint(25, width-25), random.randint(25, height-25)]
        Ghost("RedTestPac.png", s, p, 25)
        if ghosts.sprites()[-1].detectPlayer(player):
            ghosts.sprites()[-1].kill()
        pygame.sprite.groupcollide(ghosts, walls, True, False)

    while player.living:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player.go("up")
                if event.key == pygame.K_DOWN:
                    player.go("down")
                if event.key == pygame.K_LEFT:
                    player.go("left")
                if event.key == pygame.K_RIGHT:
Example #19
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 #20
0
def createChildren(populationMsPac, populationGhosts, genSize, genSizeGhost, bestOverallScore, worldFile, solFile, pDensity, maxDepth, p, pGhosts, parentSelection, parentSelectionGhosts, width, height, run, runs):
	ghostChildren = []
	msPacChildren = []
	i = 0

	while i < genSizeGhost:
		rand = random.randrange(0, 2)
		if rand == 0 and i < genSizeGhost-1:
			ghostParents = chooseParents(populationGhosts, parentSelectionGhosts, 2)
			tree1, tree2 = combine(ghostParents)

			ghost1 = Ghost.Ghost()
			ghost1.tree = tree1
			ghost2 = Ghost.Ghost()
			ghost2.tree = tree2

			ghostChildren.append(ghost1)
			ghostChildren.append(ghost2)
			i+=2

		else:
			ghostParents = chooseParents(populationGhosts, parentSelectionGhosts, 1)
			tree = ghostParents[0].tree
			ghost = Ghost.Ghost()
			ghost.tree = tree
			ghost = mutate(ghost)

			ghostChildren.append(ghost)
			i+=1
	i = 0
	while i < genSize:
		#Choose Parents
		rand = random.randrange(0, 2)
		if rand == 0 and i < genSize-1:
			msPacParents = chooseParents(populationMsPac, parentSelection, 2)
			tree1, tree2 = combine(msPacParents)

			msPac1 = MsPac.MsPac()
			msPac1.tree = tree1
			msPac2 = MsPac.MsPac()
			msPac2.tree = tree2

			msPacChildren.append(msPac1)
			msPacChildren.append(msPac2)
			i+=2

		else:
			parentsMsPac = chooseParents(populationMsPac, parentSelection, 1)
			tree = parentsMsPac[0].tree
			msPac = MsPac.MsPac()
			msPac.tree = tree
			msPac = mutate(msPac)

			msPacChildren.append(msPac)
			i+=1

	i = 0
	if genSize >= genSizeGhost:
		for i in range(0, genSize):
			if i < genSizeGhost:
				index = i
			else:
				index = random.randrange(0, len(ghostChildren))

			ghosts = []
			for j in range(0, 3):
				ghost = Ghost.Ghost()
				ghost.tree = ghostChildren[index].tree
				ghosts.append(ghost)

			state = State.State(width, height, ghosts, msPacChildren[i], pDensity)
			state.generateGrid(pDensity)

			state, tempWorld = runGame(state)
			msPacChildren[i].score = state.score
			if ghostChildren[index].score != 0:
				ghostChildren[index].score = (ghostChildren[index].score + state.score*(-1))/2
			else:
				ghostChildren[index].score = state.score * -1

			ghostChildren[index] = penalty(ghostChildren[index], pGhosts, maxDepth)
			msPacChildren[i] = penalty(msPacChildren[i], p, maxDepth)
			if msPacChildren[i].score > bestOverallScore and run == runs-1:
				world = open(worldFile, 'w')
				world.write(tempWorld)
				world.close()

				bestOverallScore = msPacChildren[i].score

	else:
		for i in range(0, genSizeGhost):
			if i < genSize:
				index = i
			else:
				index = random.randrange(0, len(msPacChildren))

			ghosts = []
			for j in range(0, 3):
				ghost = Ghost.Ghost()
				ghost.tree = ghostChildren[i].tree
				ghosts.append(ghost)

			state = State.State(width, height, ghosts, msPacChildren[index], pDensity)
			state.generateGrid(pDensity)

			state, tempWorld = runGame(state)
			if msPacChildren[index].score != 0:
				msPacChildren[index].score = (msPacChildren[index].score + state.score)/2
			else:
				msPacChildren[index].score = state.score
			ghostChildren[i].score = state.score * -1

			ghostChildren[i] = penalty(ghostChildren[i], pGhosts, maxDepth)
			msPacChildren[index] = penalty(msPacChildren[index], p, maxDepth)
			if msPacChildren[index].score > bestOverallScore and run == runs-1:
				world = open(worldFile, 'w')
				world.write(tempWorld)
				world.close()

				bestOverallScore = msPacChildren[index].score

	populationGhosts.extend(ghostChildren)
	populationMsPac.extend(msPacChildren)
	return populationMsPac, populationGhosts, bestOverallScore
Example #21
0
def main():
    if len(sys.argv) > 1:
        config = open(sys.argv[1], 'r')
    else:
        config = open('config/1.cfg', 'r')

    #read in config values
    width = int(config.readline().split()[1])
    height = int(config.readline().split()[1])
    pDensity = int(config.readline().split()[1])
    seed = int(config.readline().split()[1])
    evals = int(config.readline().split()[1])
    runs = int(config.readline().split()[1])
    logFile = config.readline().split()[1]
    worldFile = config.readline().split()[1]

    #seed Random
    current_time = time.mktime(datetime.datetime.now().timetuple())
    if seed == 0:
        seed = current_time
    random.seed(seed)

    #open files
    log = open(logFile, 'w')

    #log headers
    log.write("Number of Runs: " + str(runs))
    log.write("\nNumber of Evals: " + str(evals))
    log.write("\nWorld height: " + str(height))
    log.write("\nWorld width: " + str(width))
    log.write("\nPill Density: " + str(pDensity))
    log.write("\nRandom Seed " + str(seed))
    log.write("\n\nResults Log")
    log.write("\n---------------\n\n")

    #begin runs
    bestOverallScore = 0
    for i in range(0, runs):
        log.write("Run " + str(i + 1) + "\n")
        bestScore = 0
        for j in range(0, evals):

            #Initialize ghosts and Ms. Pacman
            ghosts = []
            for i in range(0, 3):
                ghosts.append(Ghost.Ghost())
            msPac = MsPac.MsPac()

            #Initialize State
            state = State.State(width, height, ghosts, msPac, pDensity)
            #Generate the pills
            state.generateGrid(pDensity)

            #Initial World Log
            tempWorld = ""
            tempWorld += str(state.width) + "\n"
            tempWorld += str(state.height) + "\n"
            tempWorld += "m" + " " + str(state.msPac.locationX) + " " + str(
                state.msPac.locationY) + "\n"
            for k in range(0, len(state.ghosts)):
                tempWorld += str(k + 1) + " " + str(
                    state.ghosts[k].locationX) + " " + str(
                        state.ghosts[k].locationY) + "\n"
            for k in range(0, len(state.pills)):
                tempWorld += "p" + " " + str(state.pills[k].x) + " " + str(
                    state.pills[k].y) + "\n"
            tempWorld += "t" + " " + str(state.time) + " " + str(
                state.score) + "\n"

            #Run the game
            gameOver = False
            while not gameOver:
                #Update the board
                state.step()

                #World Log
                tempWorld += "m" + " " + str(
                    state.msPac.locationX) + " " + str(
                        state.msPac.locationY) + "\n"
                for k in range(0, len(state.ghosts)):
                    tempWorld += str(k + 1) + " " + str(
                        state.ghosts[k].locationX) + " " + str(
                            state.ghosts[k].locationY) + "\n"
                tempWorld += "t" + " " + str(state.time) + " " + str(
                    state.score) + "\n"

                #Check if game is over
                gameOver = state.isGameOver()

            if state.score > bestScore:
                #Log if improved score
                bestScore = state.score
                log.write(str(j) + "\t" + str(state.score) + "\n")

            if state.score > bestOverallScore:
                #Log the world file if best overall
                bestOverallScore = state.score
                world = open(worldFile, 'w')
                world.write(tempWorld)
                world.close()

        log.write("\n")
    log.close()
Example #22
0
def main():
	#Checks arguments for given config file, defaults to 1.cfg
	if len(sys.argv) > 1:
		config = open(sys.argv[1], 'r')
	else:
		config = open('config/1.cfg', 'r')

	#read in config values
	width = int(config.readline().split()[1])
	height = int(config.readline().split()[1])
	pDensity = int(config.readline().split()[1])
	seed = int(config.readline().split()[1])
	popSize = int(config.readline().split()[1])
	genSize = int(config.readline().split()[1])
	popSizeGhost = int(config.readline().split()[1])
	genSizeGhost = int(config.readline().split()[1])
	maxDepth = int(config.readline().split()[1])
	parentSelection = config.readline().split()[1]
	parentSelectionGhosts = config.readline().split()[1]
	k = int(config.readline().split()[1])
	kGhosts = int(config.readline().split()[1])
	p = int(config.readline().split()[1])
	pGhosts = int(config.readline().split()[1])
	numEvals = int(config.readline().split()[1])
	runs = int(config.readline().split()[1])
	n = int(config.readline().split()[1])
	logFile = config.readline().split()[1]
	worldFile = config.readline().split()[1]
	solFile = config.readline().split()[1]

	#seed Random
	current_time = time.mktime(datetime.datetime.now().timetuple())
	if seed == 0:
		seed = current_time
	random.seed(seed)

	#open files
	log = open(logFile, 'w')

	#log headers
	log.write("Number of Runs: " + str(runs))
	log.write("\nNumber of Evals: " + str(numEvals))
	log.write("\nWorld height: " + str(height))
	log.write("\nWorld width: " + str(width))
	log.write("\nPill Density: " + str(pDensity))
	log.write("\nRandom Seed: " + str(seed))
	log.write("\nPopulation Size: " + str(popSize))
	log.write("\nGeneration Size: " + str(genSize))
	log.write("\nMax Tree Depth: " + str(maxDepth))
	if parentSelection == "OVERSELECTION":
		log.write("\nUsing Overselection Parent Selection for Ms Pacman")
	else:
		log.write("\nUsing Fitness Proportional Parent Selection for Ms Pacman")
	if parentSelectionGhosts == "OVERSELECTION":
		log.write("\nUsing Overselection Parent Selection for Ghosts")
	else:
		log.write("\nUsing Fitness Proportional Parent Selection for Ghosts")
	if k != 0:
		log.write("\nUsing K-Tournament Survivor Selection for Ms Pacman, k: " + str(k))
	else:
		log.write("\nUsing Truncation Survivor Selection for Ms Pacman")

	if kGhosts != 0:
		log.write("\nUsing K-Tournament Survivor Selection for Ghosts, k: " + str(kGhosts))
	else:
		log.write("\nUsing Truncation Survivor Selection for Ghosts")
	log.write("\nParsimony Pressure Constant for Ms Pacman: " + str(p))
	log.write("\nParsimony Pressure Constant for Ghosts: " + str(pGhosts))
	if n != 0:
		log.write("\nUsing N-Convergence, n: " + str(n))
	log.write("\nSolution File: " + str(solFile))
	log.write("\nWorld File: " + str(worldFile))
	log.write("\n\nResults Log\n\n")

	#begin runs
	bestOverallScore = 0
	for run in range(0, runs):
		log.write("Run " + str(run+1) + "\n")
		bestScore = 0
		evals = 0

		#initialize population, ramp half and half
		#First full trees
		populationGhosts = []
		populationMsPac = []

		for j in range(0, popSizeGhost/2):
			ghost = Ghost.Ghost()
			ghost.generateFullTree(maxDepth)
			populationGhosts.append(ghost)

		for j in range(popSizeGhost/2, popSizeGhost):
			ghost = Ghost.Ghost()
			ghost.generateGrowTree(maxDepth)
			populationGhosts.append(ghost)

		for j in range(0, popSize/2):
			msPac = MsPac.MsPac()
			msPac.generateFullTree(maxDepth)
			populationMsPac.append(msPac)

		#Then Grow trees
		for j in range(popSize/2, popSize):
			msPac = MsPac.MsPac()
			msPac.generateGrowTree(maxDepth)
			populationMsPac.append(msPac)

		if popSize >= popSizeGhost:
			for i in range(0, popSize):
				if i < popSizeGhost:
					index = i
				else:
					index = random.randrange(0, len(populationGhosts))

				ghosts = []
				for j in range(0, 3):
					ghost = Ghost.Ghost()
					ghost.tree = populationGhosts[index].tree
					ghosts.append(ghost)

				state = State.State(width, height, ghosts, populationMsPac[i], pDensity)
				state.generateGrid(pDensity)

				state, tempWorld = runGame(state)
				populationMsPac[i].score = state.score
				if populationGhosts[index].score > 0:
					populationGhosts[index].score = (populationGhosts[index] + state.score*(-1))/2
				else:
					populationGhosts[index].score = state.score * -1

				if populationMsPac[i].score > bestOverallScore and run == runs-1:
					#Log the world file if best overall
					bestOverallScore = populationMsPac[i].score
					world = open(worldFile, 'w')
					world.write(tempWorld)
					world.close() 

		else:
			for i in range(0, popSizeGhost):
				if i < popSize:
					index = i
				else:
					index = random.randrange(0, len(populationMsPac))

				ghosts = []
				for j in range(0, 3):
					ghost = Ghost.Ghost()
					ghost.tree = populationGhosts[i].tree
					ghosts.append(ghost)

				state = State.State(width, height, ghosts, populationMsPac[index], pDensity)
				state.generateGrid(pDensity)

				state, tempWorld = runGame(state)
				if populationMsPac[index].score > 0:
					populationMsPac[index].score = (populationMsPac[index].score + state.score)/2
				else:
					populationMsPac[index].score = state.score
				populationGhosts[index].score = state.score * -1

				if populationMsPac[index].score > bestOverallScore and run == runs-1:
					#Log the world file if best overall
					bestOverallScore = populationMsPac[index].score
					world = open(worldFile, 'w')
					world.write(tempWorld)
					world.close() 

		#Calculates bests and averages for initial population
		evals += len(populationMsPac)
		avgScore = averageFitness(populationMsPac)
		bestScore = bestFitness(populationMsPac)
		log.write(str(evals) + "\t" + str(avgScore) + "\t" + str(bestScore) + "\n")	
		terminate = False
		previousBest = bestScore
		tillConverge = n

		#Runs a generation while termination criteria is not met.
		while not terminate:
			#Create Children
			populationMsPac, populationGhosts, bestOverallScore = createChildren(populationMsPac, populationGhosts, genSize, genSizeGhost, bestOverallScore, worldFile, solFile, pDensity, maxDepth, p, pGhosts, parentSelection, parentSelectionGhosts, width, height, run, runs)
			
			#Survival Selection
			populationMsPac = cutLosers(populationMsPac, popSize, k)
			populationGhosts = cutLosers(populationGhosts, popSizeGhost, kGhosts)
			#Update number of evals
			if genSizeGhost > genSize:
				evals += genSizeGhost
			else:
				evals += genSize

			#Log
			avgScore = averageFitness(populationMsPac)
			bestScore = bestFitness(populationMsPac)
			log.write(str(evals) + "\t" + str(avgScore) + "\t" + str(bestScore) + "\n")
			
			#Checks convergence criteria
			tillConverge -= 1
			if n != 0:
				if bestScore > previousBest:
					tillConverge = n
					previousBest = bestScore
				elif tillConverge == 0:
					terminate = True

			#Checks number of evals
			if evals >= numEvals:
				terminate = True

		log.write("\n")

		x = bestIndex(populationMsPac)
		y = bestIndex(populationGhosts)
		solution = open(solFile, 'w')
		solution.write(populationMsPac[x].tree.printOut(1))
		solution.write("\n\n")
		solution.write(populationGhosts[y].tree.printOut(1))
		solution.close()
	log.close()
Example #23
0





# 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 = []


# Logos, other images and game variables.
game_running = False
Example #24
0
 def power_up(self, time):
     Ghost.turn_blue()
     self.powered_up = True
     self.power_time = time
     self.timer = 0
Example #25
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 #26
0
# Don't display the mouse pointer
pygame.mouse.set_visible(False)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Sprite list
all_sprites_list = pygame.sprite.Group()

# Game characters
player = Player.Player()
annoying = Ghost.AnnoyingGhost()  # Creates an AnnoyingGhost
annoying.setX(100)
annoying.setY(100)
shy = Ghost.ShyGhost()  # Creates a ShyGhost
shy.setX(500)
shy.setY(100)
shy.setColours(GREEN_GHOST)
cultured = Ghost.CulturedGhost()  # Creates a Culturedghost
cultured.setX(100)
cultured.setY(500)
cultured.setColours(PURPLE_GHOST)
robo = Ghost.RobotGhost()  # Creates a RobotGhost
robo.setX(500)
robo.setY(500)

# Add the ball to the list of player-controlled objects