def obtainMeasures(): startDate = request.form.get("start") endDate = request.form.get("end") institution = request.form.get("institution") edad = request.form.get("edad") capitulo = request.form.get("capitulo") agrupacion = request.form.get("agrupacion") cie10 = request.form.get("cie10") cleanedCie10 = None cleanedAgrupacion = None cleanedCapitulo = None if cie10 != "" and cie10: cleanedCie10 = cie10.split("-")[0] if agrupacion != "" and agrupacion: cleanedAgrupacion = agrupacion.split(":")[0] if capitulo != "" and capitulo: cleanedCapitulo = capitulo.split(":")[0] MG = MapGenerator(app, institution, cleanedCapitulo, cleanedAgrupacion, cleanedCie10, startDate, endDate, edad) geojson, filterUsed = MG.generateMap() mapTitle = filterUsed if filterUsed == "cie10": mapTitle = "Pacientes de: " + cie10 elif filterUsed == "capitulo": mapTitle = "Pacientes de: " + capitulo elif filterUsed == "agrupacion": mapTitle = "Pacientes de: " + agrupacion return jsonify( gyeData = geojson, mapTitle = mapTitle )
def main(): INF = 10000000 m, n, T = 20, 70, 300 mtyp = 'clust' rtyp = 'CS2' ns = 10 MAP = MapGenerator(staN=m, typ = mtyp) Reqs = RequestGenerator(Map = MAP, typ = rtyp, reqN = n, T = T) DG = DataGenerator(Map = MAP, Reqs = Reqs) cfss = DG.generateCFSS() # for available map test while DG.getCost(cfss) == INF : print('Regenerating..') MAP = MapGenerator(staN=m, typ = mtyp) Reqs = RequestGenerator(Map = MAP, typ = rtyp, reqN = n, T = T) DG = DataGenerator(Map = MAP, Reqs = Reqs) cfss = DG.generateCFSS() # for available map test print('------------------------------------') print(MAP) print(Reqs) V = Visualization() V.drawPoints([coord[0] for coord in MAP.stations], [coord[1] for coord in MAP.stations], 'stations', 'ro') print(cfss) print(DG.getCost(cfss)) GAOP = GAOperator(DG, 'CFSS', ns) V.drawPoints(range(len(GAOP.costs)), GAOP.costs, 'costs for each generation', 'r-') print(GAOP.init) for (i, trip) in enumerate(GAOP.init.trips): points = [] for request in trip: if request > 0: points.append(MAP.stations[Reqs.requests[request-1][1]][0:2]) else: points.append(MAP.stations[Reqs.requests[-request-1][3]][0:2]) V.drawPoints([p[0] for p in points], [p[1] for p in points], 'routes/init/stations of shuttle {i}'.format(i = i), 'r-') print(GAOP.genes[0]) for (i, trip) in enumerate(GAOP.genes[0].trips): points = [] for request in trip: if request > 0: points.append(MAP.stations[Reqs.requests[request-1][1]][0:2]) else: points.append(MAP.stations[Reqs.requests[-request-1][3]][0:2]) V.drawPoints([p[0] for p in points], [p[1] for p in points], 'routes/final/stations of shuttle {i}'.format(i = i), 'r-') pass V.drawTrips(MAP, Reqs, GAOP.init, 'init') V.drawTrips(MAP, Reqs, GAOP.genes[0], 'final')
def __init__(self, m = 20, n = 100, T = 1000, shutN = 10, shutC = 5, offP = 0.6, \ MapType = 'clust', ReqType = 'CS2', gaN = 5, upp = False, lP = 0): self.m = m # number of stations self.n = n # number of requests self.shutN = shutN # number of shuttles self.T = T # running time self.shutC = shutC # capacity of shuttle self.offP = offP # ratio of offline requests self.gaN = gaN # number of GA steps self.upp = upp # convert dists to upper bound self.lP = lP # acceptable Late time Policy self.MG = MapGenerator(self.m, MapType, self.upp) self.RG = RequestGenerator(self.MG, ReqType, self.n, self.T, self.offP) self.DG = DataGenerator(self.MG, self.RG, self.shutN, self.gaN, self.lP) self.requests = self.RG.requests[:] print(self.MG) print(self.RG) print('Stations : {m} | Requests : {r} | Shuttles : {s}\nTime : {t} | Off proportion : {o} | Capacity : {c}\n'\ .format(m=self.m, r=self.n, s=self.shutN, t=self.T, o=self.offP, c=self.shutC)) print('------------------------------------') self.rDS = self.RG.rDS() self.times = [] pass
def reload_level(self, new_map=False, new_difficulty=0): if new_difficulty: self.difficulty = new_difficulty if self.tile_map.popup: self.tile_map.popup.dismiss() self.clear_widgets() self.tile_map = None if new_map: self.hex_tiles = None print new_difficulty rows, cols = map_sizes[new_difficulty - 1] self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map( self.difficulty, self.hardcore_option) tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter)
def __init__(self, cols, rows, difficulty, hardcoreOption, soundsOption, musicOptions, **kwargs): super(MapCanvas, self).__init__(**kwargs) self.soundsOption = soundsOption self.musicOption = musicOptions self.hardcore_option = hardcoreOption self.tile_map = None self.counter = None self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map( difficulty, hardcoreOption) self.difficulty = difficulty tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter) self.return_to_menu = False self.enemy_turn_splash = None self.tile_too_far_splash = None
def reload_level(self, new_map=False, new_difficulty=0): if new_difficulty: self.difficulty = new_difficulty if self.tile_map.popup: self.tile_map.popup.dismiss() self.clear_widgets() self.tile_map = None if new_map: self.hex_tiles = None print (new_difficulty) rows, cols = map_sizes[new_difficulty-1] self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map(self.difficulty, self.hardcore_option) tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter)
def __init__(self, cols, rows, difficulty, hardcoreOption, soundsOption, musicOptions, **kwargs): super(MapCanvas, self).__init__(**kwargs) self.soundsOption = soundsOption self.musicOption = musicOptions self.hardcore_option = hardcoreOption self.tile_map = None self.counter = None self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map(difficulty, hardcoreOption) self.difficulty = difficulty tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter) self.return_to_menu = False self.enemy_turn_splash = None self.tile_too_far_splash = None
class MapCanvas(FloatLayout): def __init__(self, cols, rows, difficulty, hardcoreOption, soundsOption, musicOptions, **kwargs): super(MapCanvas, self).__init__(**kwargs) self.soundsOption = soundsOption self.musicOption = musicOptions self.hardcore_option = hardcoreOption self.tile_map = None self.counter = None self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map(difficulty, hardcoreOption) self.difficulty = difficulty tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter) self.return_to_menu = False self.enemy_turn_splash = None self.tile_too_far_splash = None def add_tile_map(self, tile_map): for tile in tile_map.tiles: if tile.player: px = tile.player.x py = tile.player.y break self.tile_map = tile_map self.tile_map.pos = (-px + Window.size[0] / 2, -py + Window.size[1] / 2) self.add_widget(self.tile_map) def add_counter(self, counter): self.counter = counter self.add_widget(self.counter) def go_to_main_menu(self): self.tile_map.popup.dismiss() self.return_to_menu = True def reload_level(self, new_map=False, new_difficulty=0): if new_difficulty: self.difficulty = new_difficulty if self.tile_map.popup: self.tile_map.popup.dismiss() self.clear_widgets() self.tile_map = None if new_map: self.hex_tiles = None print (new_difficulty) rows, cols = map_sizes[new_difficulty-1] self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map(self.difficulty, self.hardcore_option) tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter) def show_enemy_turn_splash(self): self.enemy_turn_splash = Image(source='assets/graphics/ui/enemyTurn.png', size_hint=(1, 1), pos_hint={'x': 0, 'y': 0}) self.add_widget(self.enemy_turn_splash) def remove_enemy_turn_splash(self): if self.enemy_turn_splash: self.remove_widget(self.enemy_turn_splash) def show_too_far_splash(self): self.tile_too_far_splash = Image(source='assets/graphics/ui/tileTooFar.png', size_hint=(1, 1), pos_hint={'x': 0, 'y': 0}) self.add_widget(self.tile_too_far_splash) def remove_tile_too_far_splash(self, dt): if self.tile_too_far_splash: self.remove_widget(self.tile_too_far_splash) def build_map_tiles(self): return HexScatter(self.hex_tiles, self.difficulty, self.soundsOption, self.musicOption, size=[18 * 120 + 1080, 22 * 120 + 1920], pos=[0, 0], auto_bring_to_front=False)
from MapGenerator import MapGenerator from VMFWriter import VMFWriter gen = MapGenerator(200, 200) gen.generate() vmf = VMFWriter("out.vmf", 48, 3) x_offset = int(gen.rows / 2) y_offset = int(gen.cols / 2) for i in gen.optimize(): vmf.add_cuboid( pointsMin=(i.max[0] - x_offset, (i.min[1] - y_offset)*-1, 0), pointsMax=(i.min[0] - x_offset, (i.max[1] - y_offset)*-1, 1) ) vmf.save()
class MapGuiSetup(QtCore.QObject): """ Responsible for getting the information required for map generation from the dynamic data and communicating the results to the main GUI. """ timeChanged = QtCore.Signal(int) mapReady = QtCore.Signal(int) def __init__(self, parent=None): super(MapGuiSetup, self).__init__(parent) self._mapGenerator = MapGenerator() self.reset() def getDynamics(self): """ Return the dynamic series. :return: np.bool double Dynamic series. """ return self._mapGenerator.dynamics def getMapGenerator(self): """ Return the object used for generating the maps :return: MapGenerator """ return self._mapGenerator def getMaxIntMap(self, giveSignal=True): """ Calculate the maximum intensity map and signal if requested. Request the number of pre-contrast baseline images if not already known. :return: bool True if the user wishes to continue, False otherwise. """ if not self._mapGenerator.isNumBaselineSet(): self._requestBaseline() accept = self._input.exec_() if accept == QtGui.QDialog.Accepted: self._mapGenerator.numBaseline = self._baselineNumInput.spinBox.value( ) else: return False self.latestMap = self._mapGenerator.maximumIntensityMap() self.latestMapName = 'Maximum Intensity Map' if giveSignal: self.mapReady.emit(1) return True def getMeanBaselineMap(self, giveSignal=True): """ Calculate the mean of the pre-contrast baseline images and signal if requested. Request the number of pre-contrast baseline images if not already known. :return: bool True if the user wishes to continue, False otherwise. """ if not self._mapGenerator.isNumBaselineSet(): self._requestBaseline() accept = self._input.exec_() if accept == QtGui.QDialog.Accepted: self._mapGenerator.numBaseline = self._baselineNumInput.spinBox.value( ) else: return False self.latestMap = self._mapGenerator.baselineMap() self.latestMapName = 'Mean Baseline Map' if giveSignal: self.mapReady.emit(1) return True def getNz(self): """ Return the number of slices. :return: int Number of slices. """ return self._mapGenerator.getNz() def getTTPMap(self, giveSignal=True): """ Calculate the maximum intensity timepoint map and signal if requested. Request the number of pre-contrast baseline images if not already known. :return: bool True if the user wishes to continue, False otherwise. """ if not self._mapGenerator.isNumBaselineSet(): self._requestBaseline() accept = self._input.exec_() if accept == QtGui.QDialog.Accepted: self._mapGenerator.numBaseline = self._baselineNumInput.spinBox.value( ) else: return False self.latestMap = self._mapGenerator.timeToPeakMap() self.latestMapName = 'Maximum Intensity Timepoint Map' if giveSignal: self.mapReady.emit(1) return True def getZeroMinIntensityMap(self, giveSignal=True): """ Calculate a mask of voxels who have zero minimum signal intensity in their time series and signal if requested. :return: np.array bool Mask. """ if not self._mapGenerator.isNumBaselineSet(): self._requestBaseline() accept = self._input.exec_() if accept == QtGui.QDialog.Accepted: self._mapGenerator.numBaseline = self._baselineNumInput.spinBox.value( ) else: return False self.latestMap = self._mapGenerator.getZeroMinIntensityMap() self.latestMapName = 'Map of zeros' if giveSignal: self.mapReady.emit(1) return True def displayScoreMap(self): """ Display the score map generated to find the aorta seed and emit a signal. :return: """ self.latestMap = self._mapGenerator.scoreMap self.latestMapName = 'Aorta seed score maps' self.mapReady.emit(1) def reset(self): """ Reset the state of the object. :return: """ self.latestMap = None self.latestMapName = None self._nt = 0 self._currTime = 0 self._input = None self._baselineNumInput = None self._mapGenerator.reset() def setDisplayTimepoint(self, t): """ Set the timepoint to be used for any user dialogs :param t: int time-point :return: """ self._currTime = t if self._input is not None: self._baselineNumInput.spinBox.setValue(t) def setDynamics(self, d, nt): """ Set the dynamic series from which to derive the maps and the number of timepoints. :param d: np.array 3D array [nt x nz, ny, nx] :param nt: int number of timepoints :return: """ self._mapGenerator.setDynamics(d, nt) self._nt = nt def _requestBaseline(self): """ Builds Dialog for requesting the number of pre-contrast images from the user :return: """ self._input = QtGui.QDialog() self._baselineNumInput = AnalysisInput.Ui_Dialog() self._baselineNumInput.setupUi(self._input) g = self._input.geometry() g.moveTo(900, 300) self._input.setGeometry(g) self._baselineNumInput.spinBox.setMinimum(1) self._baselineNumInput.spinBox.setMaximum(self._nt) self._baselineNumInput.spinBox.setValue(self._currTime) self._baselineNumInput.spinBox.valueChanged.connect( self._signalTimepointChanged) def _signalTimepointChanged(self, t): """ Emits the timeChanged signal :param t: int timepoint :return: """ self.timeChanged.emit(t)
def __init__(self, parent=None): super(MapGuiSetup, self).__init__(parent) self._mapGenerator = MapGenerator() self.reset()
class MapCanvas(FloatLayout): def __init__(self, cols, rows, difficulty, hardcoreOption, soundsOption, musicOptions, **kwargs): super(MapCanvas, self).__init__(**kwargs) self.soundsOption = soundsOption self.musicOption = musicOptions self.hardcore_option = hardcoreOption self.tile_map = None self.counter = None self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map( difficulty, hardcoreOption) self.difficulty = difficulty tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter) self.return_to_menu = False self.enemy_turn_splash = None self.tile_too_far_splash = None def add_tile_map(self, tile_map): for tile in tile_map.tiles: if tile.player: px = tile.player.x py = tile.player.y break self.tile_map = tile_map self.tile_map.pos = (-px + Window.size[0] / 2, -py + Window.size[1] / 2) self.add_widget(self.tile_map) def add_counter(self, counter): self.counter = counter self.add_widget(self.counter) def go_to_main_menu(self): self.tile_map.popup.dismiss() self.return_to_menu = True def reload_level(self, new_map=False, new_difficulty=0): if new_difficulty: self.difficulty = new_difficulty if self.tile_map.popup: self.tile_map.popup.dismiss() self.clear_widgets() self.tile_map = None if new_map: self.hex_tiles = None print new_difficulty rows, cols = map_sizes[new_difficulty - 1] self.map_generator = MapGenerator(cols, rows) self.hex_tiles = self.map_generator.generate_map( self.difficulty, self.hardcore_option) tile_map = self.build_map_tiles() self.add_tile_map(tile_map) self.star_counter = StarCounter(23) self.add_counter(self.star_counter) def show_enemy_turn_splash(self): self.enemy_turn_splash = Image( source='assets/graphics/ui/enemyTurn.png', size_hint=(1, 1), pos_hint={ 'x': 0, 'y': 0 }) self.add_widget(self.enemy_turn_splash) def remove_enemy_turn_splash(self): if self.enemy_turn_splash: self.remove_widget(self.enemy_turn_splash) def show_too_far_splash(self): self.tile_too_far_splash = Image( source='assets/graphics/ui/tileTooFar.png', size_hint=(1, 1), pos_hint={ 'x': 0, 'y': 0 }) self.add_widget(self.tile_too_far_splash) def remove_tile_too_far_splash(self, dt): if self.tile_too_far_splash: self.remove_widget(self.tile_too_far_splash) def build_map_tiles(self): return HexScatter(self.hex_tiles, self.difficulty, self.soundsOption, self.musicOption, size=[18 * 120 + 1080, 22 * 120 + 1920], pos=[0, 0], auto_bring_to_front=False)
if self.visited_nodes.get(child.state) is None: # check look up of to_be_visited states to avoid adding duplicate states if self.to_be_visited_lookup.get(child.state) is None: if algorithm == Algorithms.BFS: self.to_be_visited.append(child) elif algorithm == Algorithms.DFS: self.to_be_visited.appendleft(child) elif algorithm == Algorithms.AStar: self.insert(child) else: raise RuntimeError("Choose an algorithm for the search.") self.to_be_visited_lookup[child.state] = 1 while True: mg = MapGenerator(10,10) #map_path = os.path.join(os.path.pardir, "maps", "map.txt") s = Search("generated_map.txt") #s.search(Algorithms.BFS) #s.search(Algorithms.DFS) s.search(Algorithms.AStar) input() map_path = os.path.join(os.path.pardir, "maps", "map.txt") s = Search(map_path) s.search(Algorithms.BFS) s.search(Algorithms.DFS) s.search(Algorithms.AStar)
class GameController: # we need a deepcopy because otherwise it will be the same as currentGrid # originalGrid = DUMMY_MAP # currentGrid = deepcopy(originalGrid) # we need a deepcopy because otherwise it will be the same as currentGrid originalGrid, pPositions = MapGenerator(5, 5, 5, 5, 2).generate() currentGrid = None graphics = None firstTaxiPosition = (-1, -1) taxiPosition = (-1, -1) startPosition = (-1, -1) finishPosition = (-1, -1) isCustomerPickedUp = False isGameFinished = False score = INITIAL_SCORE def __init__(self, isTraining=False): self.isTraining = isTraining def run(self): self.isTraining = True self.putMarkers() self.locateObjects(self.originalGrid) self.printGrid(self.originalGrid) print("taxi:", self.taxiPosition, "start:", self.startPosition, "finish:", self.finishPosition) if not self.isTraining: self.graphics = GameGraphics() self.graphics.drawGrid(self.originalGrid) listener = keyboard.Listener(on_press=self.on_press) listener.start() if not self.isTraining: thread = Thread(target=self.graphics.activateScreen) thread.start() while self.isGameFinished: time.sleep(0.2) def putMarkers(self): fPoint, sPoint = random.sample(self.pPositions, 2) while fPoint == self.taxiPosition or sPoint == self.taxiPosition: fPoint, sPoint = random.sample(self.pPositions, 2) self.originalGrid[fPoint[0]][fPoint[1]] = FINISH_SYMBOL self.originalGrid[sPoint[0]][sPoint[1]] = START_SYMBOL self.currentGrid = deepcopy(self.originalGrid) def move(self, direction: Action): """Given a direction and a grid, updates the current grid so that it shows the next position of the taxi""" # print("ORIGINAL:") # self.printGrid(self.originalGrid) newPosition = self.getNextPoint(direction) # replace cell with T self.currentGrid[newPosition[0]][newPosition[1]] = TAXI_SYMBOL # replace the old cell # print("original old char:", # self.originalGrid[self.taxiPosition[0]][self.taxiPosition[1]]) if self.originalGrid[self.taxiPosition[0]][ self.taxiPosition[1]] not in [START_SYMBOL, FINISH_SYMBOL]: self.currentGrid[self.taxiPosition[0]][ self.taxiPosition[1]] = ROAD_SYMBOL else: self.currentGrid[self.taxiPosition[0]][ self.taxiPosition[1]] = self.originalGrid[ self.taxiPosition[0]][self.taxiPosition[1]] # update taxi position self.taxiPosition = newPosition def step(self, action: Action): """ Returns next state of grid after taking an action""" newGrid = deepcopy(self.currentGrid) if action not in self.getValidMoves(): return newGrid newPosition = self.getNextPoint(action) # replace cell with T newGrid[newPosition[0]][newPosition[1]] = TAXI_SYMBOL # replace the old cell if self.originalGrid[self.taxiPosition[0]][ self.taxiPosition[1]] not in [START_SYMBOL, FINISH_SYMBOL]: newGrid[self.taxiPosition[0]][self.taxiPosition[1]] = ROAD_SYMBOL else: newGrid[self.taxiPosition[0]][ self.taxiPosition[1]] = self.originalGrid[ self.taxiPosition[0]][self.taxiPosition[1]] return newGrid def getReward(self, action: Action): """Updates the score based on the reward of moving from startPoint to endPoint""" reward = 0 currentOriginalChar = self.originalGrid[self.taxiPosition[0]][ self.taxiPosition[1]] if action == Action.PICK_UP: if self.isCustomerPickedUp: # wrong pickup print("WRONG PICK UP") reward += WRONG_PICK_UP_COST elif action == Action.DROP_OFF: if self.isCustomerPickedUp and currentOriginalChar == FINISH_SYMBOL: # correct drop off print("CORRECT DROP OFF") reward += DROP_OFF_REWARD else: print("WRONG DROP OFF") reward += WRONG_DROP_OFF_COST elif action not in self.getValidMoves(): reward += WALL_COST elif action != Action.PICK_UP: reward += MOVE_COST return reward def pickUp(self): """Updates the current grid so that it shows the next state after picking up the customer""" currentOriginalChar = self.originalGrid[self.taxiPosition[0]][ self.taxiPosition[1]] if currentOriginalChar != START_SYMBOL: return self.originalGrid[self.startPosition[0]][ self.startPosition[1]] = ROAD_SYMBOL self.isCustomerPickedUp = True def dropOff(self): """Updates the current grid so that it shows the next state after dropping off the customer""" currentOriginalChar = self.originalGrid[self.taxiPosition[0]][ self.taxiPosition[1]] if currentOriginalChar != FINISH_SYMBOL or not self.isCustomerPickedUp: return self.originalGrid[self.finishPosition[0]][ self.finishPosition[1]] = TAXI_SYMBOL self.endGame() def endGame(self): # self.isGameFinished = True self.updateScore(Action.DROP_OFF) self.isCustomerPickedUp = False self.originalGrid[self.firstTaxiPosition[0]][ self.firstTaxiPosition[1]] = ROAD_SYMBOL self.putMarkers() self.locateObjects(self.originalGrid) print("\n\nGame finished!") print("Final score:", self.score) self.score = INITIAL_SCORE def updateScore(self, action: Action): """Updates the score based on the reward of moving from startPoint to endPoint""" self.score += self.getReward(action) def on_press(self, key): # print("received key:", key) if self.isGameFinished: return validMoves = self.getValidMoves() selectedAction = None if key == Key.up: selectedAction = Action.NORTH self.updateScore(selectedAction) if Action.NORTH in validMoves: self.move(Action.NORTH) elif key == Key.down: selectedAction = Action.SOUTH self.updateScore(selectedAction) if Action.SOUTH in validMoves: self.move(Action.SOUTH) elif key == Key.left: selectedAction = Action.WEST self.updateScore(selectedAction) if Action.WEST in validMoves: self.move(Action.WEST) elif key == Key.right: selectedAction = Action.EAST self.updateScore(selectedAction) if Action.EAST in validMoves: self.move(Action.EAST) elif hasattr(key, 'char') and key.char == 'p': selectedAction = Action.PICK_UP self.updateScore(selectedAction) self.pickUp() elif hasattr(key, 'char') and key.char == 'd': selectedAction = Action.DROP_OFF self.updateScore(selectedAction) self.dropOff() else: return if not self.isGameFinished: self.printGrid(self.currentGrid) if not self.isTraining: self.graphics.drawGrid(self.currentGrid) print("SCORE:", self.score, "CUSTOMER :", self.isCustomerPickedUp) def getValidMoves(self) -> List[Action]: """Returns a list of valid moves for the taxi""" validMoves = [ Action.NORTH, Action.WEST, Action.EAST, Action.SOUTH, Action.PICK_UP, Action.DROP_OFF ] grid = self.currentGrid x = self.taxiPosition[0] y = self.taxiPosition[1] westPoint = Action.getWest((x, y)) eastPoint = Action.getEast((x, y)) northPoint = Action.getNorth((x, y)) southPoint = Action.getSouth((x, y)) if grid[westPoint[0]][westPoint[1]] == WALL_SYMBOL: validMoves.remove(Action.WEST) if grid[eastPoint[0]][eastPoint[1]] == WALL_SYMBOL: validMoves.remove(Action.EAST) if grid[northPoint[0]][northPoint[1]] == WALL_SYMBOL: validMoves.remove(Action.NORTH) if grid[southPoint[0]][southPoint[1]] == WALL_SYMBOL: validMoves.remove(Action.SOUTH) return validMoves def locateObjects(self, grid: List[List[str]]): """Locates and sets the coordinates of the taxi, start, and finish""" for i in range(len(grid)): for j in range(len(grid[i])): point = grid[i][j] if point == TAXI_SYMBOL: self.taxiPosition = (i, j) self.firstTaxiPosition = (i, j) elif point == START_SYMBOL: self.startPosition = (i, j) elif point == FINISH_SYMBOL: self.finishPosition = (i, j) def getNextPoint(self, direction: Action) -> Tuple[int, int]: newPosition = self.taxiPosition if direction == Action.NORTH: newPosition = Action.getNorth(self.taxiPosition) if direction == Action.SOUTH: newPosition = Action.getSouth(self.taxiPosition) if direction == Action.WEST: newPosition = Action.getWest(self.taxiPosition) if direction == Action.EAST: newPosition = Action.getEast(self.taxiPosition) return newPosition @staticmethod def printGrid(grid): """Prints the given grid""" print() for i in range(len(grid)): for j in range(len(grid[i])): # print((i,j),grid[i][j], end=" ") print(grid[i][j], end=" ") print()