def addGeometry(self, objects): self.geometries.extend(objects) def clearGeometries(self): self.geometries.clear() self.canvas.delete("all") def update(self): for geometry in self.geometries: for entity in geometry.getEntities(): entity.draw(self.canvas, self.c_rotmat, self.canvas_width, self.canvas_height) self.master.update() if __name__ == "__main__": e = Engine( np.array([150, 150, 150]).reshape(3, 1), np.array([np.pi / 2 - .4, -1, .3]).reshape(3, 1)) e.addGeometry([Grid(20, 20)]) e.addGeometry([Target(np.array([0, 100, 100]).reshape(3, 1), "t0")]) e.addGeometry( [CameraTurret([Target(np.array([0, 100, 100]).reshape(3, 1), "t0")])]) e.addGeometry([GunTurret(0, 0, 70, [-100, 50, 100])]) while (True): e.update() time.sleep(1)
properties = Properties() properties._load_properties() ### Parametros Ventana ### WINDOW_WIDTH = 760 WINDOW_HEIGHT = 820 WINDOW_TITLE = 'Sopa De Letras' HELP_FONT_SIZE = 23 ### Parametros adicionales ### GAME_WORDS = properties.words pygame.font.init() win = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption(WINDOW_TITLE) GAME_BOARD = create_board(GAME_WORDS, properties.orientation) grid = Grid(GAME_BOARD, WINDOW_WIDTH, WINDOW_HEIGHT - 60) start = time.time() correct_words = [] def redraw_window(win, grid, time, correct_words): win.fill(properties.backgroundColor) if (properties.help): margin = 15 gap = 10 fnt = pygame.font.SysFont(properties.fontFamily, HELP_FONT_SIZE) for w in GAME_WORDS: word = w[0] text_time = fnt.render(word, True, (255, 0, 0)) win.blit(text_time, (gap, WINDOW_HEIGHT - 40)) text_width, text_height = fnt.size(w[0])
from EscapeRoomPlayer import EscapeRoomPlayer from FileManager import FileManager from Game import Game from Display import Display LED_COUNT = 64 GRID_WIDTH = 8 GRID_HEIGHT = 8 np = neopixel.NeoPixel(Pin(2), LED_COUNT) i2c = I2C(-1, scl=Pin(22), sda=Pin(21)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) btn_1 = Pin(33, Pin.IN) btn_2 = Pin(32, Pin.IN) btn_3 = Pin(35, Pin.IN) btn_4 = Pin(34, Pin.IN) grid = Grid(GRID_WIDTH, GRID_HEIGHT) player = EscapeRoomPlayer() file_manager = FileManager() game = Game() display = Display() if __name__ == '__main__': player_location = None response = None final_question = False generate_random_location = True random_location = None previous_player_location = player_location update_grid = grid.update(player)
from Grid import Grid import numpy as np pm = np.genfromtxt('prob_matrix.csv', delimiter=',') g = Grid(pm, 2) g.summon_passengers() print[x.position for x in g.passengers] print[x.get_position() for x in g.idle_car_list] g.assign_cars() print[x.get_position() for x in g.use_car_list] print[x.position for x in g.passengers]
best_a = np.argmax( self.Q[self.agent.convert_location_to_state(), :]) if random_step: a = np.random.choice(self.nA) else: a = best_a r = self.get_reward(a) best_r = self.get_reward(best_a) new_belief = self.Q[self.agent.convert_location_to_state(),a] + \ alpha * (r + gamma * best_r - self.Q[self.agent.convert_location_to_state(),a]) self.Q[self.agent.convert_location_to_state(), a] = new_belief self.agent.simulate_step(a) def get_reward(self, a): return self.agent.get_reward(a) + self.grid.get_reward()[0] def choose_action(self): return np.argmax(self.Q[self.agent.convert_location_to_state(), :]) if __name__ == '__main__': grid = Grid() grid.add_agent() grid.add_agent() ql = QLearning(grid.agents[0]) print(ql.choose_action()) ql.learn() print(ql.choose_action())
import makeMaze import Pathfinder from PIL import Image from Grid import Grid Input = "maze.png" Output = "output.png" maze = makeMaze.make(Input) #lines = file.readlines() #aze = [] #for i in lines: # maze.append([]) # for j in i.strip(): # maze[-1].append(j) grid = Grid(len(maze), len(maze[0])) grid.grid = maze path = Pathfinder.aStar(grid.grid, grid.find("x"), grid.find("o"), "#") img = Image.open("maze.png") for i in path: img.putpixel((i[1], i[0]), (0, 255, 0)) img.save(Output)
def test_closest_intersect(filename,expected): grid = Grid(Lines(filename)) grid.populate() assert(grid.closest_intersect() == expected)
occupied += 1 return occupied def get_visible_seats(grid, y, x): found_seats = {} for i in range(1, max(grid.size())): for sign_y in [-1, 0, 1]: for sign_x in [-1, 0, 1]: pos_y = y + sign_y * i pos_x = x + sign_x * i direction_code = f'{sign_y}{sign_x}' try: if grid.get(pos_y, pos_x) != '.' and direction_code not in found_seats and direction_code != '00' \ and pos_y >= 0 and pos_x >= 0: found_seats[direction_code] = grid.get(pos_y, pos_x) except IndexError: pass if len(found_seats) == 8: return list(found_seats.values()) return list(found_seats.values()) # --- Part 1 --- # grid = Grid(rows) end_grid = run_simulation(grid, consider='adjacents') print(end_grid.count_occurence('#')) # --- Part 2 --- # end_grid = run_simulation(grid, consider='visible') print(end_grid.count_occurence('#'))
from plot import plot #Number of cells N_cells = 100 #Grid step delta_x = 1 #Number of faces N_faces = N_cells + 1 #Generation of face positions faces = np.arange(-N_cells // 2, N_cells // 2 + 1, delta_x) #Grid generation grid = Grid(faces) #Specific heat ratio gamma = 1.4 #Initial condition U_initial = [ State("Left", gamma, 1, 0, 2) if grid.cell_position[i] <= 0 else State( "Right", gamma, 1, 0, 1) for i in range(N_cells) ] #Time parameters t0 = 0 t_final = 25 #Exact solution
def __init__(self, **kwargs): super(Drw, self).__init__(**kwargs) self.CellCount = 28 #initial number of columns with self.canvas: self.array = np.zeros((28, 28)) self.Im = Image.open(self.byte_io) self.draw = ImageDraw.Draw(self.Im) self.Grids = Grid(28, self.Height, self.Height, self.draw, self.GridColor) #creates grid array self.Cells = Cells( self.Grids[0], self.Grids[1] ) #3D list of all the cell coordinates eg [ [[0,1,2,3], [5, 6, 7]....], [[0,1,2,3,4], [6,7,8,9]....] . 1st list holds x coordinate lists and 2nd list y coordinate lists self.byte_io = BytesIO() self.Im.save(self.byte_io, 'PNG') self.bg = Bg(texture=self.ImageByte( self, self.byte_io.getvalue()).texture, pos=(0, 0), size=(self.Height, self.Height)) #background self.clear = Button(text="clear", font_size=self.Height * 0.05, size=(self.Width * 0.25, self.Height * 0.10), pos=(self.Height, self.Height * 0.90)) self.clear.bind(on_press=self.Clear) self.add_widget(self.clear) #percentage bars 0-9 self.ZeroRectangle = Rectangle(pos=(self.Width / 2, self.Height * 0.10), size=(self.Width / 2 * 0.10, 0)) self.OneRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.10, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.TwoRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.20, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.ThreeRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.30, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.FourRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.40, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.FiveRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.50, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.SixRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.60, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.SevenRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.70, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.EightRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.80, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) self.NineRectangle = Rectangle( pos=(self.Width / 2 + (self.Width / 2) * 0.90, self.Height * 0.10), size=(self.Width / 2 * 0.05, 0)) #number labels 0-9 self.ZeroLabel = Label( text='0', pos=(self.Width / 2 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.OneLabel = Label( text='1', pos=(self.Width / 2 + (self.Width / 2) * 0.10 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.TwoLabel = Label( text='2', pos=(self.Width / 2 + (self.Width / 2) * 0.20 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.ThreeLabel = Label( text='3', pos=(self.Width / 2 + (self.Width / 2) * 0.30 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.FourLabel = Label( text='4', pos=(self.Width / 2 + (self.Width / 2) * 0.40 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.FiveLabel = Label( text='5', pos=(self.Width / 2 + (self.Width / 2) * 0.50 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.SixLabel = Label( text='6', pos=(self.Width / 2 + (self.Width / 2) * 0.60 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.SevenLabel = Label( text='7', pos=(self.Width / 2 + (self.Width / 2) * 0.70 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.EightLabel = Label( text='8', pos=(self.Width / 2 + (self.Width / 2) * 0.80 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10)) self.NineLabel = Label( text='9', pos=(self.Width / 2 + (self.Width / 2) * 0.90 + (self.Width / 2 * 0.035) / 2, self.Height * 0.05), size=(10, 10))
def setUp(self): self.grid = Grid(None, None, None, None, None, None) self.numemy = Numemy(None, None, None, None, None)
Map = np.zeros((20, 20)) Map[1, 4] = 100000 Map[2, 4] = 100000 Map[3, 4] = 100000 Map[4, 4] = 100000 Map[5, 4] = 100000 Map[6, 4] = 100000 Map[7, 4] = 100000 Map[8, 3] = 100000 Map[17, 17] = 100000 Map[17, 18] = 100000 Map[18, 17] = 100000 Map[18, 16] = 100000 Map[16, 18] = 100000 grid = Grid(Map=Map, meeting_point=[18, 18]) plt.figure(1) grid.show_grid() plt.figure(2) for _ in range(30): grid.add_agent(location=[3, 1], learner='DynamicMCTSFinder', ant_mode=False) # grid.add_agent(location=[3, 1], learner='DynamicMCTSFinder',ant_mode = False) # grid.add_agent(location=[8,7],learner = 'DynamicMCTSFinder') #grid.add_agent(learner='RandomFinder') #grid.add_agent(learner='RandomFinder') #grid.add_agent(learner='RandomFinder') print('meeting point is %s' % (str(grid.agents[0].meeting_point))) #Simulatortext(grid, num_steps=100) Simulatorgraphical(grid, num_steps=100, just_agents=True)
def __init__(self): self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect((HOST, PORT)) self.grid = Grid()
def getBestMove(self) -> int: (child, _) = maximize(Grid(matrix=self.grid.getMatrix()), -1, MAX_INT, self.maxDepth) return self.grid.getMoveTo(child)
def test_grid_size(self): grid = Grid() assert grid.nRows == SCS.GRIDSIZE assert grid.nCols == SCS.GRIDSIZE assert grid.nrSquaresWithValues() == 0
def __init__(self): self.window = self.init_window() self.game_board = Grid(self.window) self.init_keys()
def test_grid_allowed_values_initial(self): grid = Grid() for square in grid.squares: assert len(square.GetAllowedValues()) == SCS.GRIDSIZE
# Grid dimensions dims = input("Enter comma separated grid dimensions - width, height\n") dims = dims.split(',') width = int(dims[0]) height = int(dims[1]) # Intializing the grid gen_zero = np.zeros((height, width)) # Row input print("Enter Initial Grid") for i in range(height): row = input() row = [ int(cell) for cell in row ] gen_zero[i] = row[:] # Cell indices cell_idx = input("Enter comma separated cell indices\n") cell_idx = cell_idx.split(",") x = int(cell_idx[0]) y = int(cell_idx[1]) # Total number of cycles cycles = input("Enter number of runs\n") cycles = int(cycles) grid = Grid(gen_zero) # Initialization and game execution game = Game(grid, cycles, y, x) game.play() print("Green counter: " + str(game.result()))
def Load(self, display_surf): self.setBgColor(display_surf) '''Loading xml values''' xmlGrid1 = self.xmlActivity.getElementsByTagName('cells')[0] self.Grid1 = Grid(xmlGrid1) try: xmlGrid2 = self.xmlActivity.getElementsByTagName('cells')[1] self.Grid2 = Grid(xmlGrid2) self.styleCell2 = StyleCell(xmlGrid2) except: self.Grid2 = Grid() '''only 1 Grid''' self.styleCell = StyleCell(xmlGrid1) ''' Calculate Real size''' width = self.Grid1.cellWidth * self.Grid1.numCols height = self.Grid1.cellHeight * self.Grid1.numRows ''' Calculamos porcentaje...''' '''Maximize size''' coef = self.calculateCoef(width, height) height = self.Grid1.cellHeight * self.Grid1.numRows * coef width = self.Grid1.cellWidth * self.Grid1.numCols * coef '''Loading constants for the activity''' xActual = Constants.MARGIN_TOP yActual = Constants.MARGIN_LEFT xGrid = (Constants.ACTIVITY_WIDTH - width) / 2 yGrid = (Constants.ACTIVITY_HEIGHT - height) / 2 xGrid = max(xGrid, xActual) yGrid = max(yGrid, yActual) '''Cargamos grupo de celdas comunes...''' ''' 1 Imagen por cada celda ( tipo texto)''' self.Grid1.Load(self.Grid1.numRows, self.Grid1.numCols, width, height, xGrid, yGrid, display_surf) cells = xmlGrid1.getElementsByTagName('cell') i = 0 for cell in cells: self.printxmlCellinCell(self.Grid1.Cells[i], cell, self.styleCell) id = int(cell.getAttribute('id')) self.Grid1.Cells[i].contentCell.id = id i = i + 1 try: '''if cells 2 not exists, only create an empty Grid''' self.Grid2.Load(self.Grid1.numRows, self.Grid1.numCols, width, height, xActual, yActual, display_surf) cells = xmlGrid2.getElementsByTagName('cell') i = 0 for cell in cells: self.printxmlCellinCell(self.Grid2.Cells[i], cell, self.styleCell2) i = i + 1 except: pass
grassConsRate = args.grassConsRate numLearningIterations = args.numLearningIterations totalNumIterations = args.totalNumIterations preyV = [] predV = [] grassV = [] predLastAteV = [] preyLastAteV = [] ratioV = [] WeightsInfo = [] grid = Grid(xDim, yDim, nPredators, nPrey, nGrass, learningRate, discountFactor, predRepAge, predDeathRate, predRepRate, preyRepAge, preyDeathRate, preyRepRate, mPred, mPrey, grassRepRate, grassConsRate) numAgents = nPredators + nPrey + nGrass for i in range(1, numLearningIterations): numAgents = grid.update(True, i) print( "Iteration: %d. Pred: %d, prey: %d, grass: %d, avg. prey death age: %.2f, avg. pred death age: %.2f" % (i, numAgents[0], numAgents[1], numAgents[2], numAgents[3], numAgents[4])) preyV.append(numAgents[0]) predV.append(numAgents[1]) grassV.append(numAgents[2]) [preyDeathAvg, predDeathAvg, preyLastAteP, predLastAteP, ratio] = numAgents[3:]
def test_shortest_intersect_path(filename,expected): grid = Grid(Lines(filename)) grid.populate() assert(grid.shortest_intersect_path() == expected)
#Tic_tac_toe_game #Authors Mario Carricato & Marco Amato import time from Grid import Grid from Computer import Computer from Player import Player grid_obj = Grid() computer = Computer() player = Player() def start_game(): run = 0 print("\nHello player, you are welcome....") player.insert_player_name(str(input("Insert Your Name \n"))) while True: is_choice_wrong = True while is_choice_wrong: grid_obj.get_snapschoot() choice = input("chose an empty space for X. ") if choice in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]: choice = int(choice) if grid_obj.list[choice] != "X" and grid_obj.list[choice] != "O": grid_obj.list[choice] = "X"
self.Gr.add_edge(nodes[i], nodes[j]) def RECONNECT(self): self.Gr = nx.DiGraph() for i, agent in enumerate(self.grid.agents): self.Gr.add_node(agent, label=i) self.D = self.get_Dist_Mat() self.connect(self.D) def show_Graph(self): nx.draw(Gr.Gr) plt.show() if __name__ == '__main__': G = Grid() G.add_agent([1, 0], viewing=3) G.add_agent([3, 0], viewing=3.3) G.add_agent([3, 3]) Gr = Graph(G) Gr.show_Graph() # from Grid import Grid # import numpy as np # G = Grid() # G.add_agent([1,0],viewing = 2) # G.add_agent([3,0]) # # Gr = nx.Graph() # for i,agent in enumerate(G.agents): # Gr.add_node(agent)
def simulate(): xml_files = os.listdir('Data\\') corrupts = [ 'WHITBYCGS', 'STONE MILLS SF', 'DPNTMTLND', 'HARMON', 'KIPLING', 'LITTLELONG', 'SILVERFALLS' ] gens_dict = {} sim_grid = Grid() for file in xml_files: addr = os.path.join('Data', file) #print(addr) tree = ET.parse(addr) root = tree.getroot() generators = root[1][1] for generator in generators: name = generator[0].text # Generator Name #print(generator[0].tag, generator[0].text) if name in corrupts: continue #corrupted generator if name not in gens_dict: agen = Agent(name, generator[1].text) gens_dict[name] = agen sim_grid.add_vpp(agen) # Generator Fuel Type #print(generator[1].tag, generator[1].text) ''' if len(generator[2][0]) < 2: # N/A generator #pass continue ''' outputs = generator[2] outs = [] # print("outputs") for sample in outputs: # Hour # print(sample[0].text) if len(sample) > 1: # EnergyMW # print(sample[1].text) outs.append(sample[1].text) gens_dict[name].add_out(sample[1].text) else: print("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH") print(generator[1].text, generator[0].text) capabilities = generator[3] forec = [] # print("capabilities") for sample in capabilities: # Hour # print(sample[0].text) # EnergyMW # print(sample[1].text) forec.append(sample[1].text) gens_dict[name].add_forec(sample[1].text) capacities = generator[4] caps = [] # print("capacities") for sample in capacities: # Hour # print(sample[0].text) # EnergyMW # print(sample[1].text) caps.append(sample[1].text) gens_dict[name].add_capac(sample[1].text) ''' for i in range(24): if forec[i] != caps[i]: print("!!!FFFFFFF!!!!") break ''' # print(len(root[1][1])) # print(len(gens_dict)) # gen = gens_dict['ADELAIDE'] # gen2 = gens_dict['AMARANTH'] # gen3 = gens_dict['ARMOW'] # print(gen.output(34)) # print(gen2.output(34)) # print(gen3.output(34)) # gen2.merge_holon(gen3) # gen.merge_holon(gen2) # print(gen.output_sum(34)) # # # grid = Grid() # grid.add_vpp(gen) # grid.pay_for_time(34) # print(gen.incomes[0] + gen2.incomes[0] + gen3.incomes[0]) # # gen.remove_child(gen2) # gen.remove_child(gen3) # grid.add_vpp(gen2) # grid.add_vpp(gen3) # grid.pay_for_time(34) # print(gen.incomes[1] + gen2.incomes[1] + gen3.incomes[1]) # ss = 0 # for time in range(744): # for vpp in sim_grid.vpps: # ss += abs(vpp.output(time) - vpp.forecast(time)) # if time < 24: # #print(vpp.name, time, vpp.output(time), vpp.forecast(time)) # pass # if (time + 1) % 24 == 0: # print(ss) # ss = 0 return sim_grid.run()
import globals from Case import Case from Grid import Grid from Visual import Visual globals.initialize() grid = Grid([[Case() for i in range(globals.sizeOfGrid)] for j in range(globals.sizeOfGrid)]) visual = Visual(grid)
def generate_maze(): grid = Grid() cord_arr = generate_start_and_finish() startIndex = cord_arr[0] endIndex = cord_arr[1] grid = grid_init(grid, endIndex) grid.environment[startIndex[0]][startIndex[1]].startBlock = True grid.environment[endIndex[0]][endIndex[1]].endBlock = True #initialize neighbors of each cell for i in range(DIM): for j in range(DIM): if i == 0: tuple = ("South", grid.environment[i + 1][j]) grid.environment[i][j].children.append(tuple) if j > 0 and j < DIM - 1: e_neighbor = ("East", grid.environment[i][j + 1]) w_neighbor = ("West", grid.environment[i][j - 1]) grid.environment[i][j].children.append(e_neighbor) grid.environment[i][j].children.append(w_neighbor) elif j == 0: tuple = ("East", grid.environment[i][j + 1]) grid.environment[i][j].children.append(tuple) else: tuple = ("West", grid.environment[i][j - 1]) grid.environment[i][j].children.append(tuple) elif j == 0: tuple = ("East", grid.environment[i][j + 1]) grid.environment[i][j].children.append(tuple) if i > 0 and i < DIM - 1: n_neighbor = ("North", grid.environment[i - 1][j]) s_neighbor = ("South", grid.environment[i + 1][j]) grid.environment[i][j].children.append(n_neighbor) grid.environment[i][j].children.append(s_neighbor) elif i == DIM - 1: tuple = ("North", grid.environment[i - 1][j]) grid.environment[i][j].children.append(tuple) elif i == DIM - 1: tuple = ("North", grid.environment[i - 1][j]) grid.environment[i][j].children.append(tuple) if j > 0 and j < DIM - 1: e_neighbor = ("East", grid.environment[i][j + 1]) w_neighbor = ("West", grid.environment[i][j - 1]) grid.environment[i][j].children.append(e_neighbor) grid.environment[i][j].children.append(w_neighbor) elif j == DIM - 1: tuple = ("West", grid.environment[i][j - 1]) grid.environment[i][j].children.append(tuple) elif j == DIM - 1: tuple = ("West", grid.environment[i][j - 1]) grid.environment[i][j].children.append(tuple) if i > 0 and i < DIM: n_neighbor = ("North", grid.environment[i - 1][j]) s_neighbor = ("South", grid.environment[i + 1][j]) grid.environment[i][j].children.append(n_neighbor) grid.environment[i][j].children.append(s_neighbor) else: n_neighbor = ("North", grid.environment[i - 1][j]) s_neighbor = ("South", grid.environment[i + 1][j]) e_neighbor = ("East", grid.environment[i][j + 1]) w_neighbor = ("West", grid.environment[i][j - 1]) grid.environment[i][j].children.append(n_neighbor) grid.environment[i][j].children.append(s_neighbor) grid.environment[i][j].children.append(e_neighbor) grid.environment[i][j].children.append(w_neighbor) stack = Frontier() #choose random initial state x = generate_x() y = generate_y() initial_cell = grid.environment[x][y] initial_cell.visited = True initial_cell.blocked = False neighbors = initial_cell.children state = initial_cell while (1): #get neighbors of state neighbors = state.children #add neighbors to stack and mark as visited for neighbor in neighbors: if (neighbor[1].visited is False and neighbor[1].startBlock is False and neighbor[1].endBlock is False): node = Node(neighbor[1], None) neighbor[1].visited = True stack.push(node) #stack is empty return if (stack.size == 0): print("GridWorld Created!") break #else pop from stack random_cell = stack.pop().value #make cell unblocked or blocked with a probability rand = random.randint(1, 10) if (rand < 4): #mark as blocked random_cell.blocked = True index = (random_cell.x * DIM) + random_cell.y item = draw.c.find_withtag(str(index + 1)) draw.c.itemconfig(item, fill='black') else: #mark as unblocked random_cell.blocked = False #move state to neighbor state = random_cell forward_a_star(grid, startIndex) #runs foward a* reset_values(grid, startIndex) backward_a_star(grid, endIndex) #runs backward a * reset_values(grid, endIndex) adaptive_a_star(grid, startIndex) #runs adaptive a*
def play_again(): global GAME_BOARD, grid, start, correct_words GAME_BOARD = create_board(GAME_WORDS, properties.orientation) grid = Grid(GAME_BOARD, WINDOW_WIDTH, WINDOW_HEIGHT - 60) start = time.time() correct_words = []
import sys from Grid import Grid from BinaryTree import BinaryTree from Sidewinder import Sidewinder op = sys.argv[1] grid = Grid(10, 10) BinaryTree.on(grid) grid.to_ascii() # img = grid.to_png(cell_size=10, folder="out/binarytree") # img.show() grid2 = Grid(10, 10) Sidewinder.on(grid2) grid2.to_ascii() # print("deadends:%s" % len(grid2.check_deadends())) img2 = grid2.to_png(cell_size=30, folder="out/sidewinder") if op == "on": img2.show()
def __init__(self,xDim,yDim) : self.myGrid = Grid(xDim,yDim) self.xDim = xDim self.yDim = yDim self.myGrid.gliderSetup()
def __init__(self, model, filename, save=False, savefile=None, digitImagesPath=None): self.SudokuGrid = None # Grid used to analyse the image and solve the sudoku self.OutputImage = None # Image of the solution of the sudoku self.OutputUnrotatedImage = None # Unrotated image of the solution of the sudoku # Load the image try: SudokuImage = cv.imread(filename, 0) except Exception as e: print("\nError during the loading of the image:") print(e) sys.exit() # Add a small margin try: (h, w) = SudokuImage.shape hr, wr = int(h * 1.1), int(w * 1.1) InputImage = SudokuImage.max() * np.ones((hr, wr)) InputImage[int(np.floor((hr - h) / 2)):int(np.floor((hr + h) / 2)), int(np.floor((wr - w) / 2)):int(np.floor((wr + w) / 2))] = SudokuImage InputImage = np.uint8(InputImage) except Exception as e: print("\nError during the creation of the margin:") print(e) sys.exit() # Instanciate the Grid try: self.SudokuGrid = Grid(InputImage) except Exception as e: print("\nError during the instanciation of the Grid:") print(e) sys.exit() # Analyse the image try: self.SudokuGrid.setCellImages() except Exception as e: print("\nError during the analysis of the grid:") print(e) sys.exit() # Predict the digits try: self.SudokuGrid.predictDigits(model) except Exception as e: print("\nError during the prediction of the digits:") print(e) sys.exit() # Solve the Sudoku try: self.SudokuGrid.solve() except Exception as e: print("\nError during the solving of the sudoku:") print(e) sys.exit() # Save the result as an image try: if save: if savefile != None: self.OutputImage, self.OutputUnrotatedImage = self.SudokuGrid.toImage( getDigitalDigits(digitImagesPath), savefile) else: self.OutputImage, self.OutputUnrotatedImage = self.SudokuGrid.toImage( getDigitalDigits(digitImagesPath), filename) else: self.OutputImage, self.OutputUnrotatedImage = self.SudokuGrid.toImage( getDigitalDigits(digitImagesPath)) except Exception as e: print("\nError during the saving of the solution:") print(e) sys.exit()