def __init__( self, index = 0, inference = "ExactInference", ghostAgents = None, observeEnable = True, elapseTimeEnable = True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable self.weka = Weka() self.weka.start_jvm()
class BustersAgent: "An agent that tracks and displays its beliefs about ghost positions." def __init__(self, index=0, inference="ExactInference", ghostAgents=None, observeEnable=True, elapseTimeEnable=True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable global predictN if predictN <= 0: predictN = 1 # Iniciamos una maquina virtual de Java para Weka self.weka = Weka() self.weka.start_jvm() def registerInitialState(self, gameState): "Initializes beliefs and inference modules" import __main__ self.display = __main__._display for inference in self.inferenceModules: inference.initialize(gameState) self.ghostBeliefs = [ inf.getBeliefDistribution() for inf in self.inferenceModules ] self.firstMove = True def observationFunction(self, gameState): "Removes the ghost states from the gameState" agents = gameState.data.agentStates gameState.data.agentStates = [agents[0]] + [ None for i in range(1, len(agents)) ] return gameState def getAction(self, gameState): "Updates beliefs, then chooses an action based on updated beliefs." #for index, inf in enumerate(self.inferenceModules): # if not self.firstMove and self.elapseTimeEnable: # inf.elapseTime(gameState) # self.firstMove = False # if self.observeEnable: # inf.observeState(gameState) # self.ghostBeliefs[index] = inf.getBeliefDistribution() #self.display.updateDistributions(self.ghostBeliefs) return self.chooseAction(gameState) def chooseAction(self, gameState): "By default, a BustersAgent just stops. This should be overridden." return Directions.STOP
def __init__(self, index=0, inference="ExactInference", ghostAgents=None, observeEnable=True, elapseTimeEnable=True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable global predictN if predictN <= 0: predictN = 1 # Iniciamos una maquina virtual de Java para Weka self.weka = Weka() self.weka.start_jvm()
class BustersAgent: "An agent that tracks and displays its beliefs about ghost positions." def __init__(self, index=0, inference="ExactInference", ghostAgents=None, observeEnable=True, elapseTimeEnable=True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable self.weka = Weka() self.weka.start_jvm() def registerInitialState(self, gameState): "Initializes beliefs and inference modules" import __main__ self.display = __main__._display for inference in self.inferenceModules: inference.initialize(gameState) self.ghostBeliefs = [ inf.getBeliefDistribution() for inf in self.inferenceModules ] self.firstMove = True def observationFunction(self, gameState): "Removes the ghost states from the gameState" agents = gameState.data.agentStates gameState.data.agentStates = [agents[0]] + [ None for i in range(1, len(agents)) ] return gameState def getAction(self, gameState): "Updates beliefs, then chooses an action based on updated beliefs." #for index, inf in enumerate(self.inferenceModules): # if not self.firstMove and self.elapseTimeEnable: # inf.elapseTime(gameState) # self.firstMove = False # if self.observeEnable: # inf.observeState(gameState) # self.ghostBeliefs[index] = inf.getBeliefDistribution() #self.display.updateDistributions(self.ghostBeliefs) return self.chooseAction(gameState) def chooseAction(self, gameState): "By default, a BustersAgent just stops. This should be overridden." return Directions.STOP def calculateFoodPositions(self, state): """ Returns the food positions """ foodPos = [9999999] * state.getNumFood() if (state.getNumFood() > 0): # minDistance = 900000 # pacmanPosition = state.getPacmanPosition() counter = 0 for i in range(state.data.layout.width): for j in range(state.data.layout.height): if state.hasFood(i, j): foodPos[counter] = (i, j) counter += 1 # distance = util.manhattanDistance(pacmanPosition, foodPosition) # if distance < minDistance: # minDistance = distance return foodPos else: return None def bestActions(self, state): # Read variables from state legalActions = state.getLegalActions(0) # No tiene sentido que incluyamos Stop, buscamos que termine lo antes posible if 'Stop' in legalActions: legalActions.remove("Stop") pos = state.getPacmanPosition() #posicion pacman ghosts_pos = state.getGhostPositions() #posicion fantasmas bestGhostAction = ['None' ] * 4 #mejor accion para cada uno de los ghosts distancesToGhosts = [ 10000 ] * 4 #distancia del pacman a cada uno de los ghosts #Encuentra la mejor accion del Pacman para cada fantasma for i in range(0, 4): mini = 9999999999 if (state.getLivingGhosts()[i + 1]): aux = 0 if 'North' in legalActions: aux = self.distancer.getDistance((pos[0], pos[1] + 1), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'North' distancesToGhosts[i] = aux mini = aux if 'East' in legalActions: aux = self.distancer.getDistance((pos[0] + 1, pos[1]), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'East' distancesToGhosts[i] = aux mini = aux if 'West' in legalActions: aux = self.distancer.getDistance((pos[0] - 1, pos[1]), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'West' distancesToGhosts[i] = aux mini = aux if 'South' in legalActions: aux = self.distancer.getDistance((pos[0], pos[1] - 1), ghosts_pos[i]) if mini > aux: bestGhostAction[i] = 'South' distancesToGhosts[i] = aux mini = aux bestScore = min(distancesToGhosts) #distancia al fantasma bestAction = [] #mejor accion #Elige la mejor entre la mejor accion para cada fantasma/comida for action, distance in zip(bestGhostAction, distancesToGhosts): if distance == bestScore: if action != 'None': bestAction = [action] else: bestAction = 'None' aux = distancesToGhosts[:] aux.sort() for i in range(0, 4): index = distancesToGhosts.index(aux[i]) distancesToGhosts[index] = i return bestAction[0], bestGhostAction, distancesToGhosts def printLineData(self, gameState): s = [] s.append(str(gameState.getPacmanPosition()[0])) #p_x---- s.append(str(gameState.getPacmanPosition()[1])) #p_y---- if "West" in gameState.getLegalPacmanActions(): #go_west---- s.append("T") else: s.append("F") if "East" in gameState.getLegalPacmanActions(): #go_east---- s.append("T") else: s.append("F") if "North" in gameState.getLegalPacmanActions(): #go_north---- s.append("T") else: s.append("F") if "South" in gameState.getLegalPacmanActions(): #go_south---- s.append("T") else: s.append("F") for i in range(1, gameState.getNumAgents()): #g1,g2,g3,g4---- if gameState.getLivingGhosts()[i]: s.append("T") # fantasma vivo else: s.append("F") # fantasma comido missing_ghosts = abs(gameState.getNumAgents() - 1 - 4) if missing_ghosts > 0: for i in range(0, missing_ghosts): s.append( "F" ) # Si hay menos de 4 fantasmas, el resto se indica con N que no existe for i in range(1, 5): #g1x,g1y, g2x,g2y, g3x,g3y, g4x,g4y---- if i <= gameState.getNumAgents() - 1: s.append(gameState.getGhostPositions()[i - 1][0]) s.append(gameState.getGhostPositions()[i - 1][1]) else: s.append(-1) s.append(-1) bestAction, bestActions, distancesToGhosts = self.bestActions( gameState) for i in range(0, 4): #distance to ghosts---- if ((i <= gameState.getNumAgents() - 2) and distancesToGhosts[i] < 10000): s.append(distancesToGhosts[i] ) #Si el fantasma ya fue comido, su distancia es 1000 else: s.append( -1 ) # Si hay menos de 4 fantasmas, se indica una distancia falsa de -1 for i in range(0, 4): if gameState.getGhostDirections().get(i) != None: s.append(gameState.getGhostDirections().get(i)) else: s.append('Stop') for i in bestActions: s.append(str(i)) s.append(str(gameState.getScore())) #score---- # s.append(str(gameState.data.agentStates[0].getDirection())) #dir direc = gameState.data.agentStates[0].getDirection() score = gameState.getScore() output = s[0] for i in s[1::]: output = output + "," + str(i) return direc, score, output
class BustersAgent: "An agent that tracks and displays its beliefs about ghost positions." def __init__(self, index=0, inference="ExactInference", ghostAgents=None, observeEnable=True, elapseTimeEnable=True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable self.instanciaAnterior = "" self.accionAnteriorAnterior = 0 # WEKA self.weka = Weka() self.weka.start_jvm() def registerInitialState(self, gameState): "Initializes beliefs and inference modules" import __main__ self.display = __main__._display for inference in self.inferenceModules: inference.initialize(gameState) self.ghostBeliefs = [ inf.getBeliefDistribution() for inf in self.inferenceModules ] self.firstMove = True def observationFunction(self, gameState): "Removes the ghost states from the gameState" agents = gameState.data.agentStates gameState.data.agentStates = [agents[0]] + [ None for i in range(1, len(agents)) ] return gameState def getAction(self, gameState): "Updates beliefs, then chooses an action based on updated beliefs." #for index, inf in enumerate(self.inferenceModules): # if not self.firstMove and self.elapseTimeEnable: # inf.elapseTime(gameState) # self.firstMove = False # if self.observeEnable: # inf.observeState(gameState) # self.ghostBeliefs[index] = inf.getBeliefDistribution() #self.display.updateDistributions(self.ghostBeliefs) return self.chooseAction(gameState) def chooseAction(self, gameState): "By default, a BustersAgent just stops. This should be overridden." # POSICION DE PACMAN columna_pacman = str(gameState.getPacmanPosition()[0]) fila_pacman = str(gameState.getPacmanPosition()[1]) # NUMERO DE FANTASMAS (SIEMPRE ES 4 ES IRRELEVANTE) num_fantasmas = str(gameState.getNumAgents() - 1) # NUMERO DE FANTASMAS VIVOS num_fantasmas_vivos = 0 for fantasma in gameState.getLivingGhosts(): if fantasma: num_fantasmas_vivos = num_fantasmas_vivos + 1 num_fantasmas_vivos = str(num_fantasmas_vivos) # num_fantasmas_vivos = sum([int(g) for g in gameState.getLivingGhosts()]) # POSICION FANTASMA 1 columna_fantasma_1 = str(gameState.getGhostPositions()[0][0]) fila_fantasma_1 = str(gameState.getGhostPositions()[0][1]) # POSICION FANTASMA 2 columna_fantasma_2 = str(gameState.getGhostPositions()[1][0]) fila_fantasma_2 = str(gameState.getGhostPositions()[1][1]) # POSICION FANTASMA 3 columna_fantasma_3 = str(gameState.getGhostPositions()[2][0]) fila_fantasma_3 = str(gameState.getGhostPositions()[2][1]) # POSICION FANTASMA 4 columna_fantasma_4 = str(gameState.getGhostPositions()[3][0]) fila_fantasma_4 = str(gameState.getGhostPositions()[3][1]) # DISTANCIA DE MANHATTAN AL FANTASMA 1 dist_1 = str(gameState.data.ghostDistances[0]) # DISTANCIA DE MANHATTAN AL FANTASMA 2 dist_2 = str(gameState.data.ghostDistances[1]) # DISTANCIA DE MANHATTAN AL FANTASMA 3 dist_3 = str(gameState.data.ghostDistances[2]) # DISTANCIA DE MANHATTAN AL FANTASMA 4 dist_4 = str(gameState.data.ghostDistances[3]) # ORDENAR LISTA DE DISTANCIAS cont = 0 ghostsDistances = gameState.data.ghostDistances for i in range(len(ghostsDistances)): if ghostsDistances[i] < 0: ghostsDistances.pop(i) ghostsDistances.insert(i, -1) ghostsDistancesSorted = sorted( ghostsDistances) # ORDENAR LA LISTA DE DISTANCIAS for i in range(len(ghostsDistancesSorted)): if ghostsDistancesSorted[i] == -1: cont = cont + 1 pos = ghostsDistances.index( ghostsDistancesSorted[cont] ) # ELEGIR EL INDICE CORRESPONDIENTE A LA DISTANCIA MAS PEQUENA #POSICION FANTASMA MAS CERCANO columna_fantasma_mas_cercano = str( gameState.getGhostPositions()[pos][0]) fila_fantasma_mas_cercano = str(gameState.getGhostPositions()[pos][1]) # DISTANCIA EN COLUMNAS AL FANTASMA MAS CERCANO dist_columna_fantasma_cercano = str( abs((gameState.getPacmanPosition()[0]) - (gameState.getGhostPositions()[pos][0]))) # DISTANCIA EN FILAS AL FANTASMA MAS CERCANO dist_fila_fantasma_cercano = str( abs((gameState.getPacmanPosition()[1]) - (gameState.getGhostPositions()[pos][1]))) #DISTANCIA DE MANHATTAN AL FANTASMA MAS CERCANO dist_fantasma_cercano = str( (abs((gameState.getPacmanPosition()[0]) - (gameState.getGhostPositions()[pos][0]))) + (abs((gameState.getPacmanPosition()[1]) - (gameState.getGhostPositions()[pos][1])))) # PUNTOS DE COMIDA RESTANTES num_comida = str(gameState.getNumFood()) # DISTANCIA DE MANHATTAN A LA COMIDA MAS CERCANA dist_comida = str(gameState.getDistanceNearestFood()) # PAREDES isWallNorth = str( gameState.getWalls()[gameState.getPacmanPosition()[0]][ gameState.getPacmanPosition()[1] + 1]) isWallSouth = str( gameState.getWalls()[gameState.getPacmanPosition()[0]][ gameState.getPacmanPosition()[1] - 1]) isWallEast = str( gameState.getWalls()[gameState.getPacmanPosition()[0] + 1][gameState.getPacmanPosition()[1]]) isWallWest = str( gameState.getWalls()[gameState.getPacmanPosition()[0] - 1][gameState.getPacmanPosition()[1]]) # DISTANCIAS A LAS PAREDES MAS CERCANAS aux_columna_pacman = gameState.getPacmanPosition()[0] aux_fila_pacman = gameState.getPacmanPosition()[1] aux_columna = gameState.getWalls()[aux_columna_pacman] lista_columna = [] lista_norte = [] lista_sur = [] aux_cont = -1 for valor in aux_columna: aux_cont = aux_cont + 1 if (valor == True): lista_columna.append(aux_cont) for numero in lista_columna: if (numero < aux_fila_pacman): lista_sur.append(numero) if (numero > aux_fila_pacman): lista_norte.append(numero) pos_North_cercano = sorted(lista_norte)[ 0] # lista norte nos quedamos con el mas pequeno pos_South_cercano = sorted( lista_sur, reverse=True)[0] # lista sur nos quedamos con el mas grande distNorth = str(abs(pos_North_cercano - aux_fila_pacman)) distSouth = str(abs(pos_South_cercano - aux_fila_pacman)) lista_fila = [] lista_este = [] lista_oeste = [] num_columna = -1 num_fila = -1 lista_mapa = [] for valor in gameState.getWalls(): lista_mapa.append(valor) # imprime las columnas de 0 a x # i representa la columna # j representa la fila # almacenamos la columna en la que se encuentran las paredes, la fila es la misma que la del pacman for i in range(len(lista_mapa)): for j in range(len(lista_mapa[i])): if (lista_mapa[i][j] == True and j == aux_fila_pacman): lista_fila.append(i) for numero in lista_fila: if (numero < aux_columna_pacman): lista_oeste.append(numero) if (numero > aux_columna_pacman): lista_este.append(numero) pos_East_cercano = sorted(lista_este)[ 0] # lista este nos quedamos con el mas pequeno pos_West_cercano = sorted( lista_oeste, reverse=True)[0] # lista oeste nos quedamos con el mas grande distEast = str(abs(pos_East_cercano - aux_columna_pacman)) distWest = str(abs(pos_West_cercano - aux_columna_pacman)) # PUNTUACION score = str(gameState.getScore()) # DIRECCION DE PACMAN dir_pacman = str(gameState.data.agentStates[0].getDirection()) if dist_1 == "None": dist_1 = "-1" if dist_2 == "None": dist_2 = "-1" if dist_3 == "None": dist_3 = "-1" if dist_4 == "None": dist_4 = "-1" if dist_comida == "None": dist_comida = "-1" if (self.accionAnteriorAnterior != 0): x = [ num_fantasmas_vivos, dist_columna_fantasma_cercano, dist_fila_fantasma_cercano, dist_fantasma_cercano, dist_comida, isWallNorth, isWallSouth, isWallEast, isWallWest, distNorth, distSouth, distEast, distWest, self.accionAnteriorAnterior ] a = self.weka.predict("./J48_1_4.model", x, "./training_tutorial1.arff") self.accionAnteriorAnterior = dir_pacman else: x = [ num_fantasmas_vivos, dist_columna_fantasma_cercano, dist_fila_fantasma_cercano, dist_fantasma_cercano, dist_comida, isWallNorth, isWallSouth, isWallEast, isWallWest, distNorth, distSouth, distEast, distWest, self.accionAnteriorAnterior ] a = self.weka.predict("./J48_1_4.model", x, "./training_tutorial1.arff") self.accionAnteriorAnterior = dir_pacman legal = gameState.getLegalActions(0) ##Legal position from the pacman if (a in legal): print("LA ACCION EXISTE") return a else: print("RANDOM") move = Directions.STOP move_random = random.randint(0, 3) if (move_random == 0) and Directions.WEST in legal: move = Directions.WEST if (move_random == 1) and Directions.EAST in legal: move = Directions.EAST if (move_random == 2) and Directions.NORTH in legal: move = Directions.NORTH if (move_random == 3) and Directions.SOUTH in legal: move = Directions.SOUTH return move
class BustersAgent(object): "An agent that tracks and displays its beliefs about ghost positions." def __init__(self, index=0, inference="ExactInference", ghostAgents=None, observeEnable=True, elapseTimeEnable=True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable self.weka = Weka() # CUSTOM self.weka.start_jvm() # CUSTOM def registerInitialState(self, gameState): "Initializes beliefs and inference modules" import __main__ self.display = __main__._display for inference in self.inferenceModules: inference.initialize(gameState) self.ghostBeliefs = [ inf.getBeliefDistribution() for inf in self.inferenceModules ] self.firstMove = True def observationFunction(self, gameState): "Removes the ghost states from the gameState" agents = gameState.data.agentStates gameState.data.agentStates = [agents[0]] + \ [None for i in range(1, len(agents))] return gameState def getAction(self, gameState): "Updates beliefs, then chooses an action based on updated beliefs." # for index, inf in enumerate(self.inferenceModules): # if not self.firstMove and self.elapseTimeEnable: # inf.elapseTime(gameState) # self.firstMove = False # if self.observeEnable: # inf.observeState(gameState) # self.ghostBeliefs[index] = inf.getBeliefDistribution() # self.display.updateDistributions(self.ghostBeliefs) return self.chooseAction(gameState) def chooseAction(self, gameState): legal = gameState.getLegalActions(0) x = [] # Positions for position in gameState.getPacmanPosition(): x.append(position) # Valid movements if "North" in gameState.getLegalPacmanActions(): x.append(str(True)) else: x.append(str(False)) if "South" in gameState.getLegalPacmanActions(): x.append(str(True)) else: x.append(str(False)) if "East" in gameState.getLegalPacmanActions(): x.append(str(True)) else: x.append(str(False)) if "West" in gameState.getLegalPacmanActions(): x.append(str(True)) else: x.append(str(False)) # Pacman direction x.append(gameState.data.agentStates[0].getDirection()) # Alive ghosts (index 0 corresponds to Pacman and is always false) # for livinGhost in gameState.getLivingGhosts()[1:]: # x.append(str(livinGhost)) # Ghosts positions for i in range(0, gameState.getNumAgents() - 1): for position in gameState.getGhostPositions()[i]: x.append(position) # Ghosts directions # for i in range(0, gameState.getNumAgents()-1): # if(gameState.getGhostDirections().get(i) == None): # x.append('Stop') # else: # x.append(gameState.getGhostDirections().get(i)) # Manhattan distance to ghosts for ghostDistance in gameState.data.ghostDistances: if ghostDistance == None: x.append(-1) else: x.append(ghostDistance) # Manhattan distance to the closest pac dot # if gameState.getDistanceNearestFood() == None: # x.append(-1) # else: # x.append(gameState.getDistanceNearestFood()) # Last score x.append(gameState.data.score) print(x) # a = self.weka.predict("./p1/phase4/classification/tutorial1/model.model", # x, "./p1/phase4/classification/tutorial1/training_tutorial1.arff") a = self.weka.predict( "./p1/phase4/classification/keyboard/model.model", x, "./p1/phase4/classification/keyboard/training_keyboard.arff") if a not in legal: a = Directions.STOP print(a) return a def printLineData(self, gameState, action, newGameState): # Pacman position data = ','.join(map(str, gameState.getPacmanPosition())) # msg = "Pacman position:"+data+"," msg = data + "," # Legal actions for Pacman in current position if "North" in gameState.getLegalPacmanActions(): data = "True," else: data = "False," if "South" in gameState.getLegalPacmanActions(): data += "True," else: data += "False," if "East" in gameState.getLegalPacmanActions(): data += "True," else: data += "False," if "West" in gameState.getLegalPacmanActions(): data += "True," else: data += "False," data += "True," msg += data # msg += data+"," # Pacman direction data = gameState.data.agentStates[0].getDirection() # msg += "Pacman direction: " + data msg += data + "," # Alive ghosts (index 0 corresponds to Pacman and is always false) for livinGhost in gameState.getLivingGhosts()[1:]: msg += str(livinGhost) + "," # data = ','.join(map(str, gameState.getLivingGhosts())) # msg += "Living ghosts: "+data+"," # msg += data+"," # Ghosts positions for i in range(0, gameState.getNumAgents() - 1): data = ','.join(map(str, gameState.getGhostPositions()[i])) msg += data + "," # Ghosts directions data = ','.join( map(str, [ gameState.getGhostDirections().get(i) for i in range(0, gameState.getNumAgents() - 1) ])) # msg += "Ghosts directions: "+data+"," msg += data + "," # Manhattan distance to ghosts for ghostDistance in gameState.data.ghostDistances: if ghostDistance == None: ghostDistance = -1 msg += str(ghostDistance) + "," # msg += "Ghosts distances: "+data+"," # msg += data+"," # Manhattan distance to the closest pac dot if gameState.getDistanceNearestFood() == None: msg += str(-1) + "," else: msg += str(gameState.getDistanceNearestFood()) + "," # msg += "Distance nearest pac dots: " + data # Last score msg += str(gameState.data.score) + "," # Next scoreChange msg += str(newGameState.data.scoreChange) + "," # Last action msg += str(action) + "," # Next score msg += str(newGameState.data.score) + "\n" return msg def __del__(self): # Destructor de python self.weka.stop_jvm() # CUSTOM
class BustersAgent: "An agent that tracks and displays its beliefs about ghost positions." def __init__(self, index=0, inference="ExactInference", ghostAgents=None, observeEnable=True, elapseTimeEnable=True): inferenceType = util.lookup(inference, globals()) self.inferenceModules = [inferenceType(a) for a in ghostAgents] self.observeEnable = observeEnable self.elapseTimeEnable = elapseTimeEnable self.weka = Weka() self.weka.start_jvm() def registerInitialState(self, gameState): "Initializes beliefs and inference modules" import __main__ self.display = __main__._display for inference in self.inferenceModules: inference.initialize(gameState) self.ghostBeliefs = [ inf.getBeliefDistribution() for inf in self.inferenceModules ] self.firstMove = True def observationFunction(self, gameState): "Removes the ghost states from the gameState" agents = gameState.data.agentStates gameState.data.agentStates = [agents[0]] + [ None for i in range(1, len(agents)) ] return gameState def getAction(self, gameState): "Updates beliefs, then chooses an action based on updated beliefs." #for index, inf in enumerate(self.inferenceModules): # if not self.firstMove and self.elapseTimeEnable: # inf.elapseTime(gameState) # self.firstMove = False # if self.observeEnable: # inf.observeState(gameState) # self.ghostBeliefs[index] = inf.getBeliefDistribution() #self.display.updateDistributions(self.ghostBeliefs) return self.chooseAction(gameState) def chooseAction(self, gameState): info = self.printLineData(gameState) action = self.weka.predict( "./Modelos/j48Heuristico.model", info, "./Ficheros/Fase2Final/training_tutorial1.arff") #Tenemos que comprobar si es la accion es legal o no print(action) aux = list(gameState.getLegalActions()) if action not in aux: print("Ilegal") #En caso de no ser legal tendremos que coger una aleatoria action = random.choice(aux) return action def printLineData(self, gameState): info = list() aux = list(gameState.getLegalActions()) if Directions.WEST in aux: info += "1" else: info += "0" if Directions.EAST in aux: info += "1" else: info += "0" if Directions.NORTH in aux: info += "1" else: info += "0" if Directions.SOUTH in aux: info += "1" else: info += "0" lista = list(gameState.data.ghostDistances) for distancia in lista: if str(distancia) == "None": info += "0" else: info.append(distancia) lista = list(gameState.getGhostPositions()) for index in lista: x = index[0] - gameState.getPacmanPosition()[0] y = index[1] - gameState.getPacmanPosition()[1] info.append(x) info.append(y) #str1 = ','.join(str(e) for e in info) return info
def registerInitialState(self, gameState): BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) self.countActions = 0 self.weka = Weka() self.weka.start_jvm()
class BasicAgentAA(BustersAgent): def registerInitialState(self, gameState): BustersAgent.registerInitialState(self, gameState) self.distancer = Distancer(gameState.data.layout, False) self.countActions = 0 self.weka = Weka() self.weka.start_jvm() ''' Example of counting something''' def countFood(self, gameState): food = 0 for width in gameState.data.food: for height in width: if (height == True): food = food + 1 return food ''' Print the layout''' def printGrid(self, gameState): table = "" #print(gameState.data.layout) ## Print by terminal for x in range(gameState.data.layout.width): for y in range(gameState.data.layout.height): food, walls = gameState.data.food, gameState.data.layout.walls table = table + gameState.data._foodWallStr( food[x][y], walls[x][y]) + "," table = table[:-1] return table def printInfo(self, gameState): print("---------------- TICK ", self.countActions, " --------------------------") # Map size width, height = gameState.data.layout.width, gameState.data.layout.height print("Width: ", width, " Height: ", height) # Pacman position print("Pacman position: ", gameState.getPacmanPosition()) # Legal actions for Pacman in current position print("Legal actions: ", gameState.getLegalPacmanActions()) # Pacman direction print("Pacman direction: ", gameState.data.agentStates[0].getDirection()) # Number of ghosts print("Number of ghosts: ", gameState.getNumAgents() - 1) # Alive ghosts (index 0 corresponds to Pacman and is always false) print("Living ghosts: ", gameState.getLivingGhosts()) # Ghosts positions print("Ghosts positions: ", gameState.getGhostPositions()) # Ghosts directions print("Ghosts directions: ", [ gameState.getGhostDirections().get(i) for i in range(0, gameState.getNumAgents() - 1) ]) # Manhattan distance to ghosts print("Ghosts distances: ", gameState.data.ghostDistances) # Pending pac dots print("Pac dots: ", gameState.getNumFood()) # Manhattan distance to the closest pac dot print("Distance nearest pac dots: ", gameState.getDistanceNearestFood()) # Map walls print("Map:") print(gameState.getWalls()) # Score print("Score: ", gameState.getScore()) def chooseAction(self, gameState): self.countActions = self.countActions + 1 self.printInfo(gameState) move = random.choice(gameState.getLegalActions()) legal = gameState.getLegalActions(0) ##Legal position from the pacman aux = 1000 # search the nearest ghost for i in gameState.data.ghostDistances: if i != None and i < aux: aux = i # set the nearest ghost fantasma = gameState.data.ghostDistances.index(aux) resta = ((gameState.getPacmanPosition()[0] - gameState.getGhostPositions()[fantasma][0]), (gameState.getPacmanPosition()[1] - gameState.getGhostPositions()[fantasma][1])) if (resta[0] < 0) and Directions.EAST in legal: move = Directions.EAST if (resta[0] > 0) and Directions.WEST in legal: move = Directions.WEST if (resta[1] < 0) and Directions.NORTH in legal: move = Directions.NORTH if (resta[1] > 0) and Directions.SOUTH in legal: move = Directions.SOUTH #if ( move_random == 0 ) and Directions.WEST in legal: move = Directions.WEST #if ( move_random == 1 ) and Directions.EAST in legal: move = Directions.EAST #if ( move_random == 2 ) and Directions.NORTH in legal: move = Directions.NORTH #if ( move_random == 3 ) and Directions.SOUTH in legal: move = Directions.SOUTH return move def chooseActionWeka(self, gameState): x = [] #posicion del pacman en el eje x #x.append(gameState.getPacmanPosition()[0]) #posicion del pacman en el eje y #x.append(gameState.getPacmanPosition()[1]) #numero de fantasmas vivos #x.append(gameState.getLivingGhosts().count(True)) #fastama[i] vivo o muerto #for i in range(1, len(gameState.getLivingGhosts())): #x.append(str(gameState.getLivingGhosts()[i])) #direccion en la que se encuentra el fantasma más cercano x.append( str( BasicAgentAA.mostProbablyDirectionForWeka( self, gameState, 'NORTH'))) x.append( str( BasicAgentAA.mostProbablyDirectionForWeka( self, gameState, 'SOUTH'))) x.append( str( BasicAgentAA.mostProbablyDirectionForWeka( self, gameState, 'WEST'))) x.append( str( BasicAgentAA.mostProbablyDirectionForWeka( self, gameState, 'EAST'))) #angulo al fantasma más cercano x.append(BasicAgentAA.angleClosestGhost(self, gameState)) #indicador de pared en las distintas direcciones x.append( str( gameState.hasWall(gameState.getPacmanPosition()[0] - 1, gameState.getPacmanPosition()[1]))) x.append( str( gameState.hasWall(gameState.getPacmanPosition()[0], gameState.getPacmanPosition()[1] - 1))) x.append( str( gameState.hasWall(gameState.getPacmanPosition()[0] + 1, gameState.getPacmanPosition()[1]))) x.append( str( gameState.hasWall(gameState.getPacmanPosition()[0], gameState.getPacmanPosition()[1] + 1))) #puntuacion actual #x.append(gameState.getScore()) return self.weka.predict('./J48-bueno.model', x, './ficheros/pruebas/datos.arff') #todo almacena la informacion del tic anterior todo = "" def printLineData(self, gameState, move): #guardamos en una variable local la información del tick anterior buffer = BasicAgentAA.todo #controlamos el primer tick para no escribir la primera linea de manera defectuosa ignore_first = False if BasicAgentAA.todo == "": ignore_first = True #actualizamos el valor de la variable todo con la información actual para poder usarla en el tick siguiente BasicAgentAA.todo = str(gameState.getPacmanPosition()[0]) + "," + str( gameState.getPacmanPosition()[1]) + "," #BasicAgentAA.todo = BasicAgentAA.todo + str(gameState.data.agentStates[0].getDirection()) + "," #concatenamos la informacion de los fantasmas a la variable todo living_ghost = gameState.getLivingGhosts().count(True) BasicAgentAA.todo = BasicAgentAA.todo + str(living_ghost) + "," for i in range(1, len(gameState.getLivingGhosts())): BasicAgentAA.todo = BasicAgentAA.todo + str( gameState.getLivingGhosts()[i]) + "," for ghost in gameState.getGhostPositions(): BasicAgentAA.todo = BasicAgentAA.todo + str(ghost[0]) + "," + str( ghost[1]) + "," for ghost in gameState.data.ghostDistances: BasicAgentAA.todo = BasicAgentAA.todo + (str(-1) if ghost is None else str(ghost)) + "," BasicAgentAA.todo = BasicAgentAA.todo + str( BasicAgentAA.mostProbablyDirection(self, gameState)) BasicAgentAA.todo = BasicAgentAA.todo + str( BasicAgentAA.angleClosestGhost(self, gameState)) + "," BasicAgentAA.todo = BasicAgentAA.todo + str( gameState.hasWall(gameState.getPacmanPosition()[0] - 1, gameState.getPacmanPosition()[1])) + "," BasicAgentAA.todo = BasicAgentAA.todo + str( gameState.hasWall(gameState.getPacmanPosition()[0], gameState.getPacmanPosition()[1] - 1)) + "," BasicAgentAA.todo = BasicAgentAA.todo + str( gameState.hasWall(gameState.getPacmanPosition()[0] + 1, gameState.getPacmanPosition()[1])) + "," BasicAgentAA.todo = BasicAgentAA.todo + str( gameState.hasWall(gameState.getPacmanPosition()[0], gameState.getPacmanPosition()[1] + 1)) + "," BasicAgentAA.todo = BasicAgentAA.todo + str( -1 if gameState.getDistanceNearestFood() is None else gameState. getDistanceNearestFood()) + "," + str( gameState.getScore()) + "," + str( gameState.getNumFood()) + "," + str(move) if ignore_first: return "" return buffer + "," + str(gameState.getScore()) + "," + str( gameState.getLivingGhosts().count(True)) + "," + str( gameState.getNumFood()) + "\n" def angleClosestGhost(self, gameState): index = 0 aux = 0 minDistance = 100 for ghost in gameState.data.ghostDistances: if ghost is not None: if ghost > 0 and ghost < minDistance: minDistance = ghost index = aux aux += 1 myradians = math.atan2( gameState.getGhostPositions()[index][1] - gameState.getPacmanPosition()[1], gameState.getGhostPositions()[index][0] - gameState.getPacmanPosition()[0]) if myradians < 0: myradians += 2 * math.pi angle = round(math.degrees(myradians)) % 360 return angle def mostProbablyDirection(self, gameState): index = 0 aux = 0 minDistance = 100 for ghost in gameState.data.ghostDistances: if ghost is not None: if ghost > 0 and ghost < minDistance: minDistance = ghost index = aux aux += 1 up = False down = False left = False right = False if gameState.getPacmanPosition()[0] - gameState.getGhostPositions( )[index][0] > 0: left = True if gameState.getPacmanPosition()[0] - gameState.getGhostPositions( )[index][0] < 0: right = True if gameState.getPacmanPosition()[1] - gameState.getGhostPositions( )[index][1] > 0: down = True if gameState.getPacmanPosition()[1] - gameState.getGhostPositions( )[index][1] < 0: up = True return str(up) + "," + str(down) + "," + str(left) + "," + str( right) + "," def mostProbablyDirectionForWeka(self, gameState, direction): index = 0 aux = 0 minDistance = 100 for ghost in gameState.data.ghostDistances: if ghost is not None: if ghost > 0 and ghost < minDistance: minDistance = ghost index = aux aux += 1 up = False down = False left = False right = False if gameState.getPacmanPosition()[0] - gameState.getGhostPositions( )[index][0] > 0: left = True if gameState.getPacmanPosition()[0] - gameState.getGhostPositions( )[index][0] < 0: right = True if gameState.getPacmanPosition()[1] - gameState.getGhostPositions( )[index][1] > 0: down = True if gameState.getPacmanPosition()[1] - gameState.getGhostPositions( )[index][1] < 0: up = True if direction == 'NORTH': return str(up) elif direction == 'SOUTH': return str(down) elif direction == 'WEST': return str(left) elif direction == 'EAST': return str(right)