def test_when_checking_for_mines_on_top_then_detects_right_number(self): string = "x3y2***..." grid = Grid(string) mined_string = grid.get_mines_surronding_squares() mined_string = mined_string.replace('\n', '') self.assertEqual(int(mined_string[4]), self.MAX_NUMBER_MINES_CENTER_FOR_ROW) self.assertEqual(int(mined_string[3]), self.MAX_NUMBER_MINES_CORNER_FOR_ROW)
def test_when_checking_for_mines_then_detects_right_number(self): string = "x3y3****.****" middle = 4 grid = Grid(string) mined_string = grid.get_mines_surronding_squares() mined_string = mined_string.replace('\n', '') self.assertEqual(self.MAX_NUMBER_MINES_AROUND_SQUARE, int(mined_string[middle]))
def test_when_checking_for_mines_on_sides_then_detects_right_number(self): string = "x1y3.*." grid = Grid(string) mined_string = grid.get_mines_surronding_squares() mined_string = mined_string.replace('\n', '') self.assertEqual(int(mined_string[0]), 1) self.assertEqual(int(mined_string[2]), 1)
def __init__(self, params: EnvironmentParams): self.display = DHDisplay() super().__init__(params, self.display) self.grid = Grid(params.grid_params, stats=self.stats) self.rewards = Rewards(params.reward_params, stats=self.stats) self.physics = Physics(params=params.physics_params, stats=self.stats) self.agent = DDQNAgent(params.agent_params, self.grid.get_example_state(), self.physics.get_example_action(), stats=self.stats) self.trainer = DDQNTrainer(params.trainer_params, agent=self.agent) self.display.set_channel(self.physics.channel) self.first_action = True self.last_actions = [] self.last_rewards = [] self.last_states = []
def __init__(self): # Données multijoueur self.pseudo = "" # Initialisation des éléments de jeu du joueur self.gridDef = Grid() self.gridAtk = Grid() self.boats = [] self.boats.append(Boat("Porte avion", 5, 1)) self.boats.append(Boat("Croiseur", 4, 2)) self.boats.append(Boat("Sous marin", 3, 3)) self.boats.append(Boat("Contre Torpilleur", 3, 4)) self.boats.append(Boat("Torpilleur", 2, 5))
[0, 6, 0, 0, 9, 0, 0, 0, 0], [0, 7, 9, 0, 0, 4, 0, 3, 2], [0, 2, 0, 0, 0, 3, 0, 0, 4], ########################### [0, 4, 2, 0, 0, 8, 0, 0, 0], [1, 0, 0, 6, 2, 9, 0, 0, 7], [0, 0, 0, 4, 5, 0, 2, 8, 0], ########################### [4, 0, 0, 5, 0, 0, 0, 2, 0], [7, 1, 0, 8, 0, 0, 6, 5, 0], [0, 0, 0, 0, 3, 0, 0, 1, 0], ] grid3 = [ [0, 0, 0, 0, 0, 5, 0, 6, 8], [0, 0, 3, 0, 0, 0, 7, 0, 0], [9, 0, 0, 7, 0, 8, 4, 0, 2], ########################### [3, 0, 0, 6, 0, 9, 2, 1, 0], [1, 2, 0, 0, 8, 0, 0, 9, 4], [0, 4, 9, 5, 0, 2, 0, 0, 6], ########################### [2, 0, 4, 1, 0, 3, 0, 0, 5], [0, 0, 7, 0, 0, 0, 9, 0, 0], [5, 9, 0, 2, 0, 0, 0, 0, 0], ] sudoku = Grid(grid3) print(sudoku.solve())
from src.Grid import Grid try: lines = [line.rstrip('\n') for line in open('minesweeper.txt')] except FileNotFoundError: raise IOError("File 'minesweeper.txt' needs to exist !") for line in lines: grid = Grid(line) print(grid)
class Environment(BaseEnvironment): def __init__(self, params: EnvironmentParams): self.display = DHDisplay() super().__init__(params, self.display) self.grid = Grid(params.grid_params, stats=self.stats) self.rewards = Rewards(params.reward_params, stats=self.stats) self.physics = Physics(params=params.physics_params, stats=self.stats) self.agent = DDQNAgent(params.agent_params, self.grid.get_example_state(), self.physics.get_example_action(), stats=self.stats) self.trainer = DDQNTrainer(params.trainer_params, agent=self.agent) self.display.set_channel(self.physics.channel) self.first_action = True self.last_actions = [] self.last_rewards = [] self.last_states = [] def test_episode(self): state = copy.deepcopy(self.init_episode()) self.stats.on_episode_begin(self.episode_count) first_action = True while not state.all_terminal: for state.active_agent in range(state.num_agents): if state.terminal: continue action = self.agent.get_exploitation_action_target(state) if not first_action: reward = self.rewards.calculate_reward( self.last_states[state.active_agent], GridActions(self.last_actions[state.active_agent]), state) self.stats.add_experience( (self.last_states[state.active_agent], self.last_actions[state.active_agent], reward, copy.deepcopy(state))) self.last_states[state.active_agent] = copy.deepcopy(state) self.last_actions[state.active_agent] = action state = self.physics.step(GridActions(action)) if state.terminal: reward = self.rewards.calculate_reward( self.last_states[state.active_agent], GridActions(self.last_actions[state.active_agent]), state) self.stats.add_experience( (self.last_states[state.active_agent], self.last_actions[state.active_agent], reward, copy.deepcopy(state))) first_action = False self.stats.on_episode_end(self.episode_count) self.stats.log_testing_data(step=self.step_count) def test_scenario(self, scenario): state = copy.deepcopy(self.init_episode(scenario)) while not state.all_terminal: for state.active_agent in range(state.num_agents): if state.terminal: continue action = self.agent.get_exploitation_action_target(state) state = self.physics.step(GridActions(action)) def step(self, state: State, random=False): for state.active_agent in range(state.num_agents): if state.terminal: continue if random: action = self.agent.get_random_action() else: action = self.agent.act(state) if not self.first_action: reward = self.rewards.calculate_reward( self.last_states[state.active_agent], GridActions(self.last_actions[state.active_agent]), state) self.trainer.add_experience( self.last_states[state.active_agent], self.last_actions[state.active_agent], reward, state) self.stats.add_experience( (self.last_states[state.active_agent], self.last_actions[state.active_agent], reward, copy.deepcopy(state))) self.last_states[state.active_agent] = copy.deepcopy(state) self.last_actions[state.active_agent] = action state = self.physics.step(GridActions(action)) if state.terminal: reward = self.rewards.calculate_reward( self.last_states[state.active_agent], GridActions(self.last_actions[state.active_agent]), state) self.trainer.add_experience( self.last_states[state.active_agent], self.last_actions[state.active_agent], reward, state) self.stats.add_experience( (self.last_states[state.active_agent], self.last_actions[state.active_agent], reward, copy.deepcopy(state))) self.step_count += 1 self.first_action = False return state def init_episode(self, init_state=None): state = super().init_episode(init_state) self.last_states = [None] * state.num_agents self.last_actions = [None] * state.num_agents self.first_action = True return state
class Player: def __init__(self): # Données multijoueur self.pseudo = "" # Initialisation des éléments de jeu du joueur self.gridDef = Grid() self.gridAtk = Grid() self.boats = [] self.boats.append(Boat("Porte avion", 5, 1)) self.boats.append(Boat("Croiseur", 4, 2)) self.boats.append(Boat("Sous marin", 3, 3)) self.boats.append(Boat("Contre Torpilleur", 3, 4)) self.boats.append(Boat("Torpilleur", 2, 5)) def enterPseudo(self): self.pseudo = input("Entrez votre pseudo :") def setCoordinatesAtk(self): xA = input("Lettre (a-j):") y = 0 while True: try: y = int(input("Chiffre (0-9):")) break except ValueError: print("Oops! Ce n'est pas un chiffre. Réessayez...") xA = xA.lower() if (len(xA) == 1) & (0 <= y <= 9): if ord("a") <= ord(xA) <= ord("j"): x = int(ord(xA) - ord("a")) return [x, y] print("Coordonées invalides ! réessayez s'il vous plait") return self.setCoordinatesAtk() def setCoordinatesBoat(self, boat): xA = input("Lettre (a-j):") y = 0 while True: try: y = int(input("Chiffre (0-9):")) break except ValueError: print("Oops! Ce n'est pas un chiffre. Réessayez...") xA = xA.lower() if (len(xA) == 1) & (0 <= y <= 9): if ord("a") <= ord(xA) <= ord("j"): x = int(ord(xA) - ord("a")) boat.setCoordonees(x, y) return boat print("Coordonées invalides ! réessayez s'il vous plait") return self.setCoordinatesBoat(boat) def setDirection(self): direction = input("Spécifiez la direction ( N/S/E/W) :") direction.upper() if len(direction) == 1: if (direction == "N") | (direction == "S") | (direction == "E") | (direction == "W"): return direction print("Direction invalide ! réessayez") self.setDirection() def tryPlaceBoat(self, boat): boatVerified = self.setCoordinatesBoat(boat) retour = self.gridDef.setBoat(boatVerified, self.setDirection()) if retour == False: self.tryPlaceBoat(boat) def boatPlacement(self): self.gridDef.display() for i in self.boats: print("Ou voulez vous placer votre " + str(i.getNom()) + " ?") self.tryPlaceBoat(i) self.gridDef.display() def isDead(self): count = 0 for i in self.boats: if i.down == True: count += 1 if int(count) == int(len(self.boats)): return True else: return False def isTouched(self, x, y): return self.gridDef.checkEmpty(x, y) def gridDefToJson(self): return Encoder().encode(self.gridDef) def jsonToGrid(obj): if "grid" in obj: return Grid(obj["grid"]) return obj
def __init__(self, xml_file, xml_recipe): self.grid = Grid(xml_recipe, xml_file) self.grid.initializeGrid() self.gridBasicMeasures = ['residence_time', 'concentrations'] self.beachCondition = getBeachFromRecipe(xml_recipe)
class GridBase: def __init__(self, xml_file, xml_recipe): self.grid = Grid(xml_recipe, xml_file) self.grid.initializeGrid() self.gridBasicMeasures = ['residence_time', 'concentrations'] self.beachCondition = getBeachFromRecipe(xml_recipe) def run(self, measures, sources, vtuParser, fileTimeHandler, netcdfWriter): print('-> Measures to compute: ', measures) sourcesDict = sources['id'] for sourceID, sourceName in sourcesDict.items(): print('\t' + sourceName) dt = fileTimeHandler.dt # initialize the measures: RawCounter = RawCounts(self.grid) if 'concentrations' in measures: AreaCounter = ConcentrationArea(self.grid) VolumeCounter = ConcentrationVolume(self.grid) if 'residence_time' in measures: ResidenceCounter = ResidenceTime(self.grid, dt) VarInCellCounter = {} for measure in measures: if measure not in self.gridBasicMeasures: VarInCellCounter[measure] = VarInCell(self.grid, base_name=measure) netcdfWriter.resetTimeIdx() vtuFileList = vtuParser.fileList for vtuFile in tqdm(vtuFileList, desc='Progress', position=0, leave=True): sourceIdx = 0 vtuParser.updateReaderWithFile(vtuFile) for sourceID, sourceName in sourcesDict.items(): # get particle position particlePos = vtuParser.getVariableData( 'coords', sourceID, beachCondition=self.beachCondition) # get counts nCountsArray = self.grid.getCountsInCell(particlePos) # Update valid cells (to avoid to compute measures on empty cells) self.grid.setValidCells(nCountsArray) dataArrayDict, dataArrayName = RawCounter.run( nCountsArray, sourceName) netcdfWriter.appendVariableTimeStepToDataset( dataArrayName, dataArrayDict) if 'residence_time' in measures: dataArrayDict, dataArrayName = ResidenceCounter.run( nCountsArray, sourceName) netcdfWriter.appendVariableTimeStepToDataset( dataArrayName, dataArrayDict) if 'concentrations' in measures: dataArrayDict, dataArrayName = AreaCounter.run( nCountsArray, sourceName) netcdfWriter.appendVariableTimeStepToDataset( dataArrayName, dataArrayDict) dataArrayDict, dataArrayName = VolumeCounter.run( nCountsArray, sourceName) netcdfWriter.appendVariableTimeStepToDataset( dataArrayName, dataArrayDict) for measure in VarInCellCounter: if measure not in self.gridBasicMeasures: varInParticles = vtuParser.getVariableData( measure, sourceID, beachCondition=self.beachCondition) varInCell = self.grid.getMeanDataInCell( particlePos, varInParticles) dataArrayDict, dataArrayName = VarInCellCounter[ measure].run(varInCell, sourceName) netcdfWriter.appendVariableTimeStepToDataset( dataArrayName, dataArrayDict) sourceIdx += 1 netcdfWriter.increaseTimeIdx()
def test_when_adding_padding_then_it_is_correctly_set(self): string = "x2y3.*.*.*" grid = Grid(string) padded = grid.pad_grid(grid.data) self.assertEqual((3 + 2) * (2 + 2), sum(len(x) for x in padded))
def test_when_parsing_grid_then_row_number_matches_input(self): grid_data = "...***" string = "x3y2" + grid_data grid = Grid(string) self.assertEqual(2, len(grid.data))
def test_when_parsing_grid_then_correct_data_is_set(self): grid_data = "*..*" string = "x2y2" + grid_data grid = Grid(string) self.assertEqual(len(grid_data), sum(len(x) for x in grid.data))
def test_given_invalid_grid_data_when_parsing_then_raises(self): string = "x1y1.." with self.assertRaises(SyntaxError): grid = Grid(string)
def test_when_parsing_grid_then_correct_dimensions_are_set(self): string = "x1y1*" grid = Grid(string) self.assertEqual((grid.x, grid.y), (1, 1))