def generate(N, p, q, M, attempt=1, total=1): intro = 'Generating {}/{}'.format(attempt, total) sys.stdout.write(intro) time_start = time.clock() restart_count = 0 filled = 0 board = Grid(N, p, q) while filled < M: # Check timeout condition elapsed_time = time.clock() - time_start if elapsed_time >= settings.gen_time_limit and settings.gen_time_limit != 0: sys.stdout.write(' Timed out. Consider using a lower M value.\n') return None # Choose a random cell to try row = randint(0, N - 1) col = randint(0, N - 1) while board.cell_empty(row, col): candidates = board.possible_values(row, col) if candidates: random_token = sample(candidates, 1)[0] if board.violates_constraints(row, col, random_token): board.eliminate(row, col, random_token) else: board.assign(row, col, random_token) filled += 1 else: restart_count += 1 sys.stdout.write('\r{}: restarting.. (x{})'.format(intro, restart_count)) board.reset() filled = 0 break sys.stdout.write('\n') return board
def make_move( self, grid, this_player ): grid = copy.deepcopy(grid) alpha, beta = float('-inf'), float('inf') spaces = sorted(Grid.open_spaces( grid ), key=lambda x: abs(x[0] - x[1])%2) lst = [ (x, Minimax.minimax(Grid.make_move(x[0], x[1], grid[:], this_player), 0, alpha, beta, this_player, not this_player)) for x in spaces ] return sorted(lst, key=lambda x: x[1])[-1][0]
def buildMap(world, factory, gridSize): cells = {} # generate a list of candidate coords for cells roomCoords = [(x, y) for x in range(gridSize) for y in range(gridSize)] random.shuffle(roomCoords) roomCount = min(10, int(gridSize * gridSize / 2)) for i in range(roomCount): if len(roomCoords) == 0: break # search for candidate cell coord = roomCoords.pop() while not safeToPlace(cells, coord) and len(roomCoords) > 0: coord = roomCoords.pop() if not safeToPlace(cells, coord): break width = random.randint(3, CELL_SIZE) height = random.randint(3, CELL_SIZE) cells[coord] = Room(world, factory, coord[0] * CELL_SIZE, coord[1] * CELL_SIZE, width, height) grid = Grid() grid.rooms = list(cells.values()) # connect every room to one neighbor for coord in cells: room = cells[coord] room1 = findNearestNeighbor(cells, coord) if not grid.connected(room, room1): grid.corridors.append(Corridor(room, room1)) # we can still end up with more than one connected component. # so let's compute all connected components, and then connect them def inComponent(comp, room): return any((grid.connected(room, room1) for room1 in comp)) comps = [] for coord in cells: room = cells[coord] found = False for comp in comps: if inComponent(comp, room): comp.append(room) found = True break if not found: comps.append([room]) while len(comps) > 1: grid.corridors.append(Corridor(comps[-1][0], comps[-2][0])) comps.pop() return grid
def start_robot(size): """ Sets up the world and robot and enters endless loop of guessing. :param size: """ # create grid that contains world state grid = Grid(size.width, size.height) # create sensor, which queries the grid sensor = Sensor(grid) # create robot, which guesses location based on sensor hmm = HMM(size.width, size.height) robot = Robot(sensor, hmm) moves = 0 guessed_right = 0 while True: # move robot grid.move_robot() moves += 1 print "\nRobot is in: ", grid.robot_location guessed_move, probability = robot.guess_move() if guessed_move == grid.robot_location: guessed_right += 1 man_distance = abs(guessed_move[0] - grid.robot_location[0]) + abs(guessed_move[1] - grid.robot_location[1]) print "Manhattan distance: ", man_distance print "Robot has been correct:", float(guessed_right) / moves, "of the time." sleep(1)
class Gameplay(GameState): def __init__(self): super(Gameplay, self).__init__() self.grid = Grid() self.sim_speed = 45 self.timer = 0 def startup(self, persistent): self.persist = persistent def get_event(self,event): if event.type == pg.QUIT: self.quit = True elif event.type == pg.KEYUP: if event.key == pg.K_ESCAPE: self.quit = True def update(self, dt): self.timer += dt while self.timer > self.sim_speed: self.grid.update(self.sim_speed) self.timer -= self.sim_speed def draw(self, surface): self.grid.draw(surface)
class GridTestCase(unittest.TestCase): def setUp(self): self.robot = Robot(Position('3', '2', 'N')) self.robot.processInstruction = MagicMock() self.grid = Grid([3,2]) def test_initGrid(self): self.assertEqual(self.grid.size, [3,2]) def test_isOutOfBounds(self): outOfBounds = self.grid.isOutOfBounds(Position('4', '2', 'N')) self.assertTrue(outOfBounds) def test_processRobotInstruction(self): self.grid.processRobot(self.robot, 'RFRF') self.assertEqual(self.robot.processInstruction.call_count, 4) def test_robotOutOfBounds(self): self.robot.position = Position(4, 2, 'N') self.grid.processRobot(self.robot, 'F') self.assertTrue(self.grid.lastRobotLost) self.assertEqual(len(self.grid.lostPositions), 1)
def test_ai(): grid = Grid() grid.gprint() ct = CountTime() totalCT = 0 while grid.won==False: # input() print("*******************************************") ai = AI(grid) ct.start() d = ai.nextMove() ct.stop() moved = grid.move(d["move"]) if moved==True: grid.gprint() moveCount = d["moveCount"] cutoffs = d["cutoffs"] print("moveCount:%d\tcutoffs:%d"%(moveCount,cutoffs)) nct = ct.milliseconds() totalCT += nct print("time consume:%d "%(nct)) print("total time consume:%d "%(totalCT)) if grid.won==False: grid.computerMove() else: grid.gprint() else: print("You fail") return
def buildMap(gridSize): cells = {} # generate a list of candidate coords for cells roomCoords = [(x, y) for x in range(gridSize) for y in range(gridSize)] random.shuffle(roomCoords) roomCount = min(10, int(gridSize * gridSize / 2)) for i in range(roomCount): # search for candidate cell coord = roomCoords.pop() while not safeToPlace(cells, coord) and len(roomCoords) > 0: coord = roomCoords.pop() if not safeToPlace(cells, coord): break width = random.randint(3, CELL_SIZE) height = random.randint(3, CELL_SIZE) cells[coord] = Room(coord[0], coord[1], width, height) grid = Grid() grid.rooms = list(cells.values()) # connect every room to one neighbor for coord in cells: room = cells[coord] room1 = findNearestNeighbor(cells, coord) if not grid.connected(room, room1): grid.corridors.append(Corridor(room, room1)) return grid
class GameManager(object): def __init__(self): self.grid = Grid() self.players = {} self.players[Cell.cross] = Player(self) self.players[Cell.nought] = Computer(self) self.turn = choice([Cell.cross, Cell.nought]) def doTurn(self): if self.players[self.turn].turn(): self.turn = not self.turn return self.getWinner() return None def draw(self, surface): surface.fill((0,0,0)) for cell in self.grid.getGrid(): cell.draw(surface) def getWinner(self): return self.grid.getWinner()
def save_princess_2( r, c, grid ): p_loc = find_princess(grid, 'p') temp_r, temp_c = r, c maze = Grid( grid ) maze.start() movement_list = list() while r != p_loc[0] or c != p_loc[1]: movement = next_move(r, c, p_loc[0], p_loc[1]) if movement is 'UP': temp_r -= 1 elif movement is 'DOWN': temp_r += 1 elif movement is 'LEFT': temp_c -= 1 elif movement is 'RIGHT': temp_c += 1 grid[r] = grid[r][:c] + '-' + grid[r][c+1:] grid[temp_r] = grid[temp_r][:temp_c] + 'm' + grid[temp_r][temp_c+1:] r, c = temp_r, temp_c maze.set_grid_data( grid ) movement_list.append( movement ) time.sleep(0.1) return movement_list
def square(self, topleft, topright, bottomleft, bottomright, origin, default = None): square = Grid(3,3) square[(0,0)] = topleft square[(2,0)] = topright square[(0,2)] = bottomleft square[(2,2)] = bottomright choices = [] abc = [ [(1,0),(0,0),(2,0)], [(0,1),(0,0),(0,2)], [(2,1),(2,0),(2,2)], [(1,2),(0,2),(2,2)], ] for a,b,c in abc: square[a] = self.rng.choice((square[b], square[c])) #square[a] = sum((square[b], square[c])) / 2 choices.append(square[a]) square[(1,1)] = self.rng.choice( choices ) #d = 40/self.depth #square[(1,1)] = (sum((topleft, topright, bottomleft, bottomright)) / 4) + self.rng.randint(-d,d) #for x,y in square: # square[(x,y)] = int(abs(square(x,y))) square.origin = origin return square
def __init__(self): grid = Grid() while grid.size < 6: grid = Grid(grid) grid.populate() self._grid = grid self.tiles = {} for v in self._grid.faces: x, y, z = v lat = 180/pi * atan2(z, sqrt(x*x + y*y)) lon = 180/pi * atan2(y, x) self.tiles[v] = Tile(lat, lon) for t in self.tiles.values(): t.emptyocean(self.seafloor()) t.climate = t.seasons = None t.candidate = False self._coastprox = 2 self._range = 6 self.adj = Adjacency(self._grid) self.initindexes() self.populated = set() self.popcache = {}
class HexApp(App): game = ObjectProperty() camera = ObjectProperty() def build(self): self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text') self._keyboard.bind(on_key_down=self._on_key_down) self.game = Grid(size_hint=(None, None)) self.game.build_grid(settings.GRID_WIDTH, settings.GRID_HEIGHT, settings.GRID_SCALE) self.game.add_player(0, settings.GRID_HEIGHT - 1, settings.GRID_SCALE) self.camera = ScrollView(size_hint=(1, 1)) self.camera.add_widget(self.game) return self.camera def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_key_down) self._keyboard = None def _on_key_down(self, keyboard, keycode, text, modifiers): if keycode[1] in keymap.WALK_DIRECTIONS: return self.game.player.action(keycode[1], movesteps=settings.MOVE_STEPS) elif keycode[1] == keymap.QUIT: keyboard.release() return True
class GameOfLife: def __init__(self, size): self._grid = Grid(size) def get_board(self): self._grid.update() return self._grid.get_data()
def init_widgets(self): rows = self.state.rows - self.state.obstructed_rows self.field = Grid(self, rows=rows, cols=self.state.cols, length=25, background_color = level_colors[0]) self.field.grid(row=0,column=0) info = Frame(self) info.grid(row=0, column=1) Label(info, text="Hold").pack() self.hold = Grid(info, rows=4, cols=4, length=25) self.hold.pack() Label(info, text="Preview").pack() self.preview = Grid(info, rows=4, cols=4, length=25) self.preview.pack() self.level_label = ExLabel(info) self.level_label.pack() self.line_label = ExLabel(info) self.line_label.pack() self.score_label = ExLabel(info) self.score_label.pack() self.fps_label = ExLabel(info) self.fps_label.pack()
class LeastSquaresCharges(LeastSquaresBasic): def __init__(self, data): self.molecule = Molecule(atoms=data['atoms']) self.grid = Grid(data) self.setA() reference = self.grid.get_properties(property_name=data['property'],\ theory='%s_%s' % (data['theory'], data['basis'])) LeastSquaresBasic.__init__(self, A=self.A, b=reference) def setA(self): n_p = len(self.grid.points) n_s = len(self.molecule.sites_noneq) self.A = np.zeros((n_p, n_s)) for i in xrange(n_p): proton = Site(coordinates=self.grid.points[i].coordinates, name='H+',index=1) for j, name in enumerate(self.molecule.sites_names_noneq): for site in self.molecule.get_sites(name=name): self.A[i,j] += 1/site.distance_to(proton) def setA_fast(self): grid_coordinates = self.grid.get_coordinates() sites_coordinates = self.molecule.get_coordinates() self.A = fast.set_inversed(grid_coordinates, sites_coordinates, \ len(self.molecule.sites_names_eq), self.molecule.sym_sites) @property def charges(self): charges = {} for q, name in zip(self.solution, self.molecule.sites_names): charges[name] = q return charges
def build_grid(data): grid = Grid2D() grid.x0 = [data.boreholes[0].X, data.boreholes[0].Y, data.boreholes[0].Z] grid.type = '2D' uTx = data.Tx[data.in_vect, :] uRx = data.Rx[data.in_vect, :] b = np.ascontiguousarray(uTx).view(np.dtype((np.void, uTx.dtype.itemsize * uTx.shape[1]))) c = np.ascontiguousarray(uRx).view(np.dtype((np.void, uRx.dtype.itemsize * uRx.shape[1]))) tmpTx = np.unique(b).view(uTx.dtype).reshape(-1, uTx.shape[1]) tmpRx = np.unique(c).view(uRx.dtype).reshape(-1, uRx.shape[1]) uTx = np.sort(tmpTx, axis= 0) uRx = np.sort(tmpRx, axis= 0) data.x0, data.a = Grid.lsplane(np.concatenate((uTx, uRx), axis= 0)) # self.data.x0 : Centroid of the data = point on the best-fit plane # self.data.a : Direction cosines of the normal to the best-fit plane if data.a[2] < 0 : data.a = -data.a data.Tx_p = Grid.proj_plane(data.Tx, data.x0, data.a) data.Rx_p = Grid.proj_plane(data.Rx, data.x0, data.a) return grid, data
def updateProj(self): az, dip = self.get_azimuth_dip() self.grid.Tx = Grid.transl_rotat(self.data.Tx_p, self.grid.x0, az, dip) self.grid.Rx = Grid.transl_rotat(self.data.Rx_p, self.grid.x0, az, dip) self.grid.TxCosDir = Grid.transl_rotat(self.data.TxCosDir, np.zeros(3), az, dip) self.grid.RxCosDir = Grid.transl_rotat(self.data.RxCosDir, np.zeros(3), az, dip) # if not np.isnan(self.data.Tx_Z_water): # self.grid.Tx_Z_water = Grid.transl_rotat(self.data.Tx_Z_water, self.grid.x0, az, dip) # if not np.isnan(self.data.Rx_Z_water): # self.grid.Rx_Z_water = Grid.transl_rotat(self.data.Rx_Z_water, self.grid.x0, az, dip) self.grid.in_vect = self.data.in_vect xmin = np.min(np.concatenate((self.grid.Tx[self.grid.in_vect,0], self.grid.Rx[self.grid.in_vect,0]))) - 0.5*self.dx xmax = np.max(np.concatenate((self.grid.Tx[self.grid.in_vect,0], self.grid.Rx[self.grid.in_vect,0]))) + 0.5*self.dx nx = np.ceil((xmax-xmin)/self.dx) zmin = np.min(np.concatenate((self.grid.Tx[self.grid.in_vect,2], self.grid.Rx[self.grid.in_vect,2]))) - 0.5*self.dz zmax = np.max(np.concatenate((self.grid.Tx[self.grid.in_vect,2], self.grid.Rx[self.grid.in_vect,2]))) + 0.5*self.dz nz = np.ceil((zmax-zmin)/self.dz) nxm = self.grid.border[0] nxp = self.grid.border[1] self.grid.grx = xmin + self.dx*np.arange(-nxm,nx+nxp+1) nzm = self.grid.border[2] nzp = self.grid.border[3] self.grid.grz = zmin + self.dz*np.arange(-nzm,nz+nzp+1)
def testGetLineCells310(self): 'getLineCells Non 0 Origin - 4x4 len 2 - right-to-left - slope down' g = Grid(-4,-4, 4,4, 1) cell = g.getCell(1.9,1.1) self.failUnlessEqual(cell,(1,1)) cells = g.getLineCells(1.9,1.1, .9,.1) # ,verbose=True) self.failUnlessEqual(cells,[(1,1),(1,0),(0,0)])
def testGrid5(self): g = Grid(30, 17, #0 1 2 3 #123456789012345678901234567890 '##############################' # 1 '# #' # 2 '# ##### #### #' # 3 '# ## ## #' # 4 '# # # #' # 5 '# #' # 6 '# #' # 7 '# #' # 8 '# #' # 9 '# #' # 10 '# #' # 11 '# #' # 12 '# # # #' # 13 '# ## ## #' # 14 '# #### #### #' # 15 '# #' # 16 '##############################') # 17 # path = g.find_path((1,1), (20,10)) path = g.find_path((1,1, ), (5,1,)) self.assertEqual([[5,1], [4,1], [3,1], [2,1]], [[n.x, n.y] for n in path]) self.assertEqual(len(g.data), 30*17)
def measure_focused_roi(im, roi, area, focus_points, debug=False): g = Grid(cv.GetSize(im)) canvas = image.new_from(im) cv.Set(canvas, 0) focus_in_roi = image.And(focus_points, roi) if debug: image.show(focus_in_roi, "ROI + Focused Points") densities = [] points = convert_to_points(focus_in_roi) groups = form_groups(points, estimated_size=24, iter=5) for group in groups: ch = ConvexHull(map(lambda x: (x[0], x[1]), group)) ppp = ch.points_per_pixel() a = int(ppp * 255) ch.draw_filled_hull(canvas, rgb=(a,a,a)) if debug: image.show(canvas, "Focused Regions in ROI") quadrants = g.split_in_four(canvas) sums = [] for i,quad in enumerate(quadrants): sums.append(cv.Sum(quad)[0] / float(area/4)) arr = array(sums) print arr.mean(), arr.std() diff = max(sums) - min(sums) return diff, arr.std()
def testGetLineCells310(self): 'getLineCells 4x4 len 2 - right-to-left - slope down' g = Grid(0+self.xmin,0+self.ymin, 4+self.xmin,4, 1+self.ymin) cell = g.getCell(1.9+self.xmin,1.1+self.ymin) self.failUnlessEqual(cell,(1,1)) cells = g.getLineCells(1.9+self.xmin,1.1+self.ymin, .9+self.xmin,.1+self.ymin) # ,verbose=True) self.failUnlessEqual(cells,[(1,1),(1,0),(0,0)])
def testL_GetLineCells020(self): 'getLineCells 1x1 horizontal' g = Grid(0,0, 1,1, 1) cells = g.getLineCells(.1,.1, .2,.1) self.failUnlessEqual(len(cells),1) self.failUnlessEqual(cells[0][0],0) self.failUnlessEqual(cells[0][1],0)
def testGetLineCells200(self): 'getLineCells Non 0 Origin - 4x4 len 3 - left-to-right - simple up slope' g = Grid(-4,-4, 0,0, 1) cells = g.getLineCells(-3.1,-3.9, -2.5,-2.9)#,verbose=True) self.failUnlessEqual(g.xNumCells,4) self.failUnlessEqual(g.yNumCells,4) self.failUnlessEqual(cells,[(0,0),(1,0),(1,1)])
def testL_GetLineCells050(self): 'getLineCells 1x1 slope down, steep' g = Grid(0,0, 1,1, 1) cells = g.getLineCells(.1,.4, .2,.09) self.failUnlessEqual(len(cells),1) self.failUnlessEqual(cells[0][0],0) self.failUnlessEqual(cells[0][1],0)
def testL_GetLineCells030(self): 'getLineCells 1x1 slope up, gentle' g = Grid(0,0, 1,1, 1) cells = g.getLineCells(.1,.1, .2,.11) self.failUnlessEqual(len(cells),1) self.failUnlessEqual(cells[0][0],0) self.failUnlessEqual(cells[0][1],0)
def testL_GetLineCells010(self): 'getLineCells 1x1 vertical' g = Grid(0,0, 1,1, 1) cells = g.getLineCells(.1,.1, .1,.2) self.failUnlessEqual(len(cells),1) self.failUnlessEqual(cells[0][0],0) self.failUnlessEqual(cells[0][1],0)
class MazeView(EasyFrame): """GUI-based maze program.""" def __init__(self, model): """Sets up the window, label, and buttons.""" EasyFrame.__init__(self, "An Amazin' Maze") self.model = model # Add maze squares to the grid self.squares = Grid(self.model.getHeight(), self.model.getWidth()) for row in range(0, self.squares.getHeight()): for column in range(0, self.squares.getWidth()): square = MazeSquare(self, width = 20, height = 20, letter = self.model.getLetter(row, column)) square = self.addCanvas(canvas = square, row = row, column = column) self.squares[row][column] = square self.moveButton = self.addButton(text = "Move", row = self.model.getHeight(), column = 0, columnspan = self.model.getWidth(), command = self.move) def move(self): row, column = self.model.move() self.squares[row][column].setLetter(self.model.getLetter(row, column)) if self.model.isSolved(): self.moveButton["state"] = "disabled" self.messageBox(title = "ALERT", message = "Maze solved") elif not self.model.canMove(): self.moveButton["state"] = "disabled" self.messageBox(title = "ALERT", message = "Maze can't be solved")
def render(self): """Returns svg object.""" grid = Grid(self.size, self.size) grid.draw_grid(stroke='black', stroke_width=2) def text(row, col, value, **attrs): if value is not None and value not in " *": grid.text(col, row, value, **attrs) # Draw all the values in the cells for (row, col), value in self.data.items(): text(row, col, value, font_weight="normal") # Draw right constraints. Give 0.25 offset to draw numbers close to the border. for i, v in self.constraints['right'].items(): text(i, self.size-0.25, v, font_weight='bold') for i, v in self.constraints['left'].items(): text(i, -0.75, v, font_weight='bold') # Draw bottom constraints. Give 0.25 offset to draw numbers close to the border. for j, v in self.constraints['bottom'].items(): text(self.size-0.25, j, v, font_weight='bold') for j, v in self.constraints['top'].items(): text(-0.75, j, v, font_weight='bold') return grid.svg
class BackgroundMap(Grid): """Map class to create the background layer, holds any static and dynamical elements in the field.""" def __init__(self, map, width, height, res): Grid.__init__(self, width, height, map) self.terrain, self.borders, self.overlay = res.terrain, res.borders, res.overlay self.images = {} self.cell_size = TILE_SIZE self.x = self.y = 0 self.sprites = Grid(width, height) for x, y in self.keys(): tiles = self.get_real_tile((x, y)) rect = tiles[0].get_rect() rect.top = y*TILE_SIZE[1] - (rect.height - TILE_SIZE[1]) rect.left = x*TILE_SIZE[0] self.sprites[x, y] = AnimatedTile(tiles, rect, layer = L_MAP(y), interval = FPS / TILE_FPS) def __setitem__(self, pos, value): Grid.__setitem__(self, pos, value) for (x, y), sprite in self.sprites.full_env_items(pos): sprite.images = self.get_real_tile((x, y)) sprite.image = sprite.images[0] sprite.rect = sprite.image.get_rect() sprite.rect.topleft = (x*TILE_SIZE[0], y*TILE_SIZE[1] - (sprite.rect.height - TILE_SIZE[1])) sprite.dirty = 1 for sprite in self.sprites.values(): sprite.reset() def get_repeated(self, (x, y)): return self[clamp_r(x, 0, self.width), clamp_r(y, 0, self.height)]
class EFT_calculator: def __init__(self, order=2): self.mol = Water() self.grid = Grid() self.order = order # order of the interpolant, 1 for linear # Setup the grid structure. If provided with a data file, load it def setup(self, filename=None): if not filename: self.grid.setup() else: self.grid.load(filename) # Given a calculator that evalulates the atomic coordinates of a pair, # use the results to fill the grid def fill_grid(self, calculator, filename='grid_data.txt'): def f(x): coor = self._spherical2Atomic(x) return calculator.eval(coor) if not self.grid.n: raise Exception('setup() before fill') self.grid.fill(f) self.grid.save(filename) def fill_with_QM(self, logfilelist): """ input filename is a file with all gird GAMESS result log in order.""" loglist = open(logfilelist, 'r').readlines() for i in range(len(loglist)): loglist[i] = loglist[i].rstrip() i = 0 for leaf, x in self.grid._gen_leaves_with_x(): leaf.y, coord = self._parseQMlog( loglist[i]) #coord is not using here i += 1 if i >= len(loglist): break def _parseQMlog(self, logname): """extract energy, force from GAMESS log file and return (energy, force[0],force[1],force[2], torque[0],torque[1],torque[2]) ni, nj is the atom num. of framgment i,j """ AU2KCAL = 23.0605 * 27.2116 HperB2toque = 1185.82 # 1Hartree/Bohr = 1185.82 kcal/mol/Angstrom frgE1 = -76.2987810745 * AU2KCAL frgE2 = -76.2987810745 * AU2KCAL e = 0.0 f = np.zeros(3) t = np.zeros(3) logf = open(logname, 'r') log = logf.readlines() logf.close() coords = [] gradients = [] for idx, i in enumerate(log): if i[0:13] == " INPUT CARD> " and len(i.split()) == 7: try: coords.append([float(i) for i in i.split()[4:7]]) except ValueError: continue if 'E(MP2)=' in i: e = float(i.split()[1]) * AU2KCAL - frgE1 - frgE2 if 'GRADIENT OF THE ENERGY' in i: for gline in log[idx + 4:idx + 10]: gradients.append( [float(g) * HperB2toque for g in gline.split()[2:5]]) break coords = np.array(coords) gradients = np.array(gradients) # from com => probe com1 = self.mol.getCOM(coords[3:]) coord1 = coords[:3] grad1 = gradients[:3] for idx in range(len(grad1)): f += grad1[idx] t += np.cross(coord1[idx] - com1, grad1[idx]) return np.array([e, f[0], f[1], f[2], t[0], t[1], t[2]]), coords # Evaluate the Xcom and q for a pair of mols by querying the grid def eval(self, Xcom0, q0, Xcom1, q1): # move COM of mol0 to origin X = Xcom1 - Xcom0 # reorient to align mol0 with refCoor R = tools.q2R(q0) X = np.dot(X, R) q = tools.qdiv(q1, q0) # Use mirror symmetry of mol0 to move mol1 such that its COM has positive y and z values reflections = [] qsub = q[1:] for i in self.mol.refl_axes: if X[i] < 0: X[i] = -X[i] # the following operation on q is equivalent to changing R to MRM # i.e., the probe mol is reflected twice, once in the reference frame, # once in the molecular frame. qsub[i] = -qsub[i] qsub[:] = -qsub reflections.append(i) # Use mirror symmetry of mol1 to orient it such that it has positive q[0] and q[1] values if q[0] < 0: q = -q if q[1] < 0: q[0], q[1], q[2], q[3] = -q[1], q[0], q[3], -q[2] # convert X, q to polar coordinates r, phi, theta = tools.xyz2spherical(X) ophi1, ophi2, otheta = tools.q2spherical(q) coor = [r, phi, theta, ophi1, ophi2, otheta] # use the grid to obtain results eft = self.grid.interpolate(coor, self.order) ener = eft[0] force = eft[1:4] torque = eft[4:7] # Reverse the operations for mol0 mirror symmetry back for i in reflections: force[i] = -force[i] torque[i] = -torque[i] torque[:] = -torque # Reverse the reorientation applied to align mol0 with refCoor force[:] = np.dot(force, R.T) torque[:] = np.dot(torque, R.T) return eft # Generate atomic coordinates for mol pair for grid points along with # an id. The optional arguments can be used to specify a range for the id. # The coordinates are in the form of [XO0, XH0, XH0, XO1, XH1, XH1], where 0 indicates # the center molecule, 1 the probe molecule. def gen_atomic_coors(self, start=None, stop=None): if stop is None: if start is not None: raise Exception('Specify start and stop at the same time!') start = 0 stop = self.grid.n gen_x = itertools.islice(self.grid.gen_x(), start, stop) for i in range(start, stop): x = gen_x.next() coors = self._spherical2Atomic(x) yield i, coors def gen_PDB(self, confs=None): if confs is None: confs = self.grid.gen_x() for i, x in enumerate(confs): #if np.linalg.norm(conf.q) > 1: pdb.set_trace() coors = self._spherical2PDB(x) yield i, coors # Construct atomic coordinates for a pair from grid coordinate def _spherical2Atomic(self, coor): r, phi, theta, ophi1, ophi2, otheta = coor Xcom = tools.spherical2xyz(r, phi, theta) q = tools.spherical2q(ophi1, ophi2, otheta) coor = self.mol.Xq2Atomic(Xcom, q) return np.concatenate((self.mol.refCoor, coor), axis=0) def _spherical2PDB(self, coor, NdxAtom=1, NdxRes=1): c = self._spherical2Atomic(coor) mol = 'TITLE para:' + '%8.3f' * 6 % tuple(coor) + '\n' for i in range(self.mol.n1 + self.mol.n2): mol += "ATOM %5d%3s%6s A%4d%12.3f%8.3f%8.3f 1.00 0.00\n" % ( NdxAtom, self.mol.ele[i], self.mol.frg, NdxRes, c[i][0], c[i][1], c[i][2]) if NdxAtom == self.mol.n1: NdxRes += 1 NdxAtom += 1 return mol
def __init__(self, x, y, limit): Grid.__init__(self, x, y, limit) self.pids = 1 self.runs = 0 self.build()
def calc(log, values, mode, draw={"mode": 0}): from grid import Grid grid = Grid(".") if draw["mode"] == "draw": frame = 0 from PIL import Image, ImageDraw img_width = 13 * draw["height"] img_height = img_width temp = {} x_levels = set() y_levels = set() hex = [] for cur in get_hex(img_width, img_height, draw["type"], 8): min_x = min([x[0] for x in cur]) min_y = min([x[1] for x in cur]) x_levels.add(min_x) y_levels.add(min_y) hex.append({ "hex": cur, "min_x": min_x, "min_y": min_y, }) x_levels = list(sorted(x_levels)) y_levels = list(sorted(y_levels)) x_off = None for y in range(len(y_levels)): temp = sorted([x for x in hex if x["min_y"] == y_levels[y]], key=lambda x: x["min_x"]) if x_off is None: x_off = -(len(temp) // 2) x = x_off for cur in temp: cur["y"] = y - (len(y_levels) // 2) cur["x"] = x * 2 if cur["y"] % 2 == 1: cur["x"] += 1 x += 1 # print(max([x["x"] for x in hex]) - min([x["x"] for x in hex])) # print(max([x["y"] for x in hex]) - min([x["y"] for x in hex])) # print(draw["width"], draw["height"]) r = re.compile("(e|se|sw|w|nw|ne)") for row in values: x, y = 0, 0 grid[x, y] = grid[x, y] trail = set([(x, y)]) for m in r.finditer(row): hit = m.group(1) if hit == "e": x += 2 elif hit == "w": x -= 2 elif hit == "se": y += 1 x += 1 elif hit == "sw": y += 1 x -= 1 elif hit == "ne": y -= 1 x += 1 elif hit == "nw": y -= 1 x -= 1 if draw["mode"] == "draw": grid[x, y] = grid[x, y] trail.add((x, y)) grid[x, y] = "X" if grid[x, y] == "." else "." if draw["mode"] == "draw" and draw["type"] != "ca": image = Image.new('RGB', (img_width, img_height), (128, 128, 128)) dr = ImageDraw.Draw(image) for cur in hex: if (cur["x"], cur["y"]) in grid.grid or draw["type"] in { "coin", "ca" }: if grid[cur["x"], cur["y"]] == "X": if (cur["x"], cur["y"]) in trail: color = (0, 0, 192) else: color = (0, 0, 0) else: if (cur["x"], cur["y"]) in trail: color = (192, 192, 255) else: color = (192, 192, 192) dr.polygon(cur["hex"], outline=(64, 64, 64), fill=color) log("Saving frame " + str(frame)) image.save("frame_%05d.png" % (frame, )) frame += 1 if mode == 1: return len([x for x in grid.grid.values() if x == "X"]) dirs = [(-1, -1), (1, -1), (-2, 0), (2, 0), (-1, 1), (1, 1)] for _ in range(100 if draw.get("type", "normal") == "normal" else 500): todo = [] for y in grid.axis_range(1, 1): for x in grid.axis_range(0, 2): use = False if y % 2 == 0: if x % 2 == 0: use = True else: if x % 2 == 1: use = True if use: black = 0 for xo, yo in dirs: if grid[x + xo, y + yo] == "X": black += 1 if grid[x, y] == "X" and (black == 0 or black > 2): todo.append((x, y, ".")) if grid[x, y] == "." and black == 2: todo.append((x, y, "X")) for x, y, val in todo: grid[x, y] = val if draw["mode"] == "draw": image = Image.new('RGB', (img_width, img_height), (128, 128, 128)) dr = ImageDraw.Draw(image) for cur in hex: if (cur["x"], cur["y"]) in grid.grid or draw["type"] in { "coin", "ca" }: dr.polygon(cur["hex"], outline=(64, 64, 64), fill=(0, 0, 0) if grid[cur["x"], cur["y"]] == "X" else (192, 192, 192)) log("Saving life frame " + str(frame)) image.save("frame_%05d.png" % (frame, )) frame += 1 if draw["mode"] == "size": return grid.width(), grid.height() if draw["mode"] == "draw": for _ in range(30): image.save("frame_%05d.png" % (frame, )) frame += 1 return len([x for x in grid.grid.values() if x == "X"])
(xoff + self.CW, yoff), 4) if not cell.isLinked(cell.cellSouth): pygame.draw.line(SURFACE, COLOR_RAVEN, (xoff, yoff + self.CH), (xoff + self.CW, yoff + self.CH), 4) if not cell.isLinked(cell.cellWest): pygame.draw.line(SURFACE, COLOR_RAVEN, (xoff, yoff), (xoff, yoff + self.CH), 4) if not cell.isLinked(cell.cellEast): pygame.draw.line(SURFACE, COLOR_RAVEN, (xoff + self.CW, yoff), (xoff + self.CW, yoff + self.CH), 4) xoff = xoff + self.CW yoff = yoff + self.CH while True: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if save_img.get_rect().collidepoint(x, y): pygame.image.save(SURFACE, 'maze.png') if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() if __name__ == "__main__": g = Grid(10, 10) MazeDraw(g).draw()
def parseRDD(line): parsedLine = list(line) return parsedLine sc = pyspark.SparkContext() grid = [] lines = sc.textFile(inputUri, 6) words = lines.flatMap(parseRDD) wordsMap = lines.map(parseRDD).collect() grid = Grid([len(wordsMap), len(wordsMap[0])]) #for i in range(len(wordsMap)): # row = [] # for j in range(len(wordsMap[i])): # row.append(0) # grid.append(row) sharedGrid = sc.broadcast(grid) def buildCpd(cell): localGrid = sharedGrid.value start_time = timeit.default_timer() localGrid.dijkstra(cell) elapsed = timeit.default_timer() - start_time
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ]''' grid = Grid(matrix=matrix) '''for x in range(0,len(startList)): start = grid.node(int(startList[x][0]), int(startList[x][1])) end = grid.node(int(goalList[x][0]), int(goalList[x][1])) print("start is ({},{}), end is ({},{})".format(int(startList[x][0]),int(startList[x][1]),int(goalList[x][0]),int(goalList[x][1]))) finder = AStarFinder(diagonal_movement=DiagonalMovement.always) path, runs = finder.find_path(start, end, grid) print('operations:', runs, 'path length:', len(path)) print(grid.grid_str(path=path, start=start, end=end)) print(path) '''
def move(y, x): print("\033[%d;%dH" % (y, x)) from mandalorian import Din, Shield, Bullet from scenery import Scenery from grid import Grid from alarmexception import AlarmException from getch import _getChUnix as getChar from items import Item, Laser, Coins, SpeedUp, Magnet from configure import Configure from enemy import Dragon, IceBall gridObj = Grid(30, 500) os.system("aplay -q ./music/Jetpack.wav &") mandalorianObj = Din(25, 10, 1) mandalorianObj.placeDin(gridObj.getMatrix(), 25, 10, 1) shieldObj = Shield(0, 0) sceneryObj = Scenery() sceneryObj.createGround(gridObj.getMatrix()) sceneryObj.createSky(gridObj.getMatrix()) laserObj = [] coinObj = [] for i in range(16): laserObj.append(Laser(0, 0))
from grid import Grid from search import Search import pygame print (__doc__) raw_input() pygame.init() source= (25,25) goal = (275,275) Width,Height = 500,500 screen = pygame.display.set_mode((Width,Height)) G = Grid(screen) G.create([Width,Height]) grid = G.grid data = [grid,None,None] srch = Search(screen,data[0]) #print len(grid) # get centre_points of grid, animation toggled with bool #print G.get_count((225,225),True) done = 0 state = 0 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # background color red green blue alpha glClearColor(1, 1, 1, 0) # creating the grid self.grid = Grid(5, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.grid_length, properties.cell_size) # creating the player self.player = Player(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, properties.player_initial_state) #creating the score self.score = Score(properties.score_initial_value, properties.off_setX, "Score") #creating the score self.episode = Score(properties.score_initial_value, properties.off_setX + properties.window_width / 2, "Episode") # adding 4 enemies self.enemy_list = [] self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 2, 2)) self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 4, 2)) self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 2, 4)) self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 4, 4)) # adding treasure self.treasure = Treasure(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 1, 5, 'images/treasure.png') # adding small treasure self.small_treasure = Treasure(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 1, 1, 'images/coins.png') self.end = False self.taked_small_treasure = False self.q_table = np.zeros([25, 4]) # Hyperparameters self.alpha = 0.7 self.gamma = 0.6 self.epsilon = 1 self.min_epsilon = 0.01 self.max_epsilon = 1.0 self.decay_rate = 0.01
class MyWindow(pyglet.window.Window): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # background color red green blue alpha glClearColor(1, 1, 1, 0) # creating the grid self.grid = Grid(5, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.grid_length, properties.cell_size) # creating the player self.player = Player(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, properties.player_initial_state) #creating the score self.score = Score(properties.score_initial_value, properties.off_setX, "Score") #creating the score self.episode = Score(properties.score_initial_value, properties.off_setX + properties.window_width / 2, "Episode") # adding 4 enemies self.enemy_list = [] self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 2, 2)) self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 4, 2)) self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 2, 4)) self.enemy_list.append( Enemy(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 4, 4)) # adding treasure self.treasure = Treasure(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 1, 5, 'images/treasure.png') # adding small treasure self.small_treasure = Treasure(properties.cell_size, properties.off_setX, properties.off_setYtop, properties.off_setYbottom, properties.rowsbycols, 1, 1, 'images/coins.png') self.end = False self.taked_small_treasure = False self.q_table = np.zeros([25, 4]) # Hyperparameters self.alpha = 0.7 self.gamma = 0.6 self.epsilon = 1 self.min_epsilon = 0.01 self.max_epsilon = 1.0 self.decay_rate = 0.01 def take_action(self, action): observation = properties.get_observation(self.player.state, action) next_state = observation[0] reward = observation[1] done = observation[2] self.player.update(next_state) self.score.update(reward) self.end = done if self.player.state == 20: ((properties.reward_table[15])[2])[1] = -1 ((properties.reward_table[21])[3])[1] = -1 self.taked_small_treasure = True self.on_draw() return observation def draw(self): self.grid.draw() self.player.draw() self.score.draw() self.episode.draw() for enemy in self.enemy_list: enemy.draw() self.treasure.draw() if not self.taked_small_treasure: self.small_treasure.draw() def game_start(self): pyglet.app.run() def game_restart(self): print("score:" + str(self.score.score)) self.episode.update(1) if self.episode.score > 10000: self.game_over() self.epsilon = self.min_epsilon + ( self.max_epsilon - self.min_epsilon) * np.exp( -self.decay_rate * self.episode.score) initial_state_space = [ 0, 1, 2, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 22, 23 ] self.player.update(choice(initial_state_space)) self.score.reset() self.end == False ((properties.reward_table[15])[2])[1] = 30 ((properties.reward_table[21])[3])[1] = 30 self.taked_small_treasure = False def game_over(self): pyglet.app.exit() def on_draw(self): self.clear() self.draw() def start_Qlearning(self, dt): state = self.player.state if random.uniform(0, 1) > self.epsilon: action = np.argmax(self.q_table[state]) # Exploit learned values else: action = random.randint(0, 3) # Explore action space observation = self.take_action(action) next_state = observation[0] reward = observation[1] old_value = self.q_table[state, action] next_max = np.max(self.q_table[next_state]) new_value = (1 - self.alpha) * old_value + self.alpha * ( reward + self.gamma * next_max) self.q_table[state, action] = new_value if self.end == True: self.game_restart() def exploiting(self, dt): state = self.player.state action = np.argmax(self.q_table[state]) # Exploit learned values observation = self.take_action(action) next_state = observation[0] reward = observation[1] if self.end == True: self.game_restart()
import pygame import os import socket import threading from grid import Grid from constants import * os.environ['SDL_VIDEO_WINDOW_POS'] = '400,100' screen = pygame.display.set_mode((600, 700)) pygame.display.set_caption("Tic-Tac-Toe Server") icon = pygame.image.load("res/tic-tac-toe-icon_32x32.png") pygame.display.set_icon(icon) grid = Grid() turn = True # Socket Constants connection_established = False conn, addr = None, None sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((HOST, PORT)) # Gets Constants from constants file sock.listen(1) # Create a separate thread to send and receive data to not block the execution while waiting for a connection def createThread(target): thread = threading.Thread(target=target) thread.daemon = True
from page069_hunt_and_kill import HuntAndKill from wilsons import Wilsons algorithms = [BinaryTree, SideWinder, AldousBroder, Wilsons, HuntAndKill] tries = 100 size = 20 averages = {} for algorithm in algorithms: print('running', algorithm.__name__) deadend_counts = [] for _ in range(tries): grid = Grid(size, size) algorithm.on(grid) deadend_counts.append(len(grid.deadends())) total_deadends = sum(deadend_counts) averages[algorithm] = total_deadends / len(deadend_counts) total_cells = size * size print('') print(f'Average dead-ends per {size}x{size} maze ({total_cells} cells):') sorted_algorithms = sorted(algorithms, key=lambda a: -averages[a]) for algorithm in sorted_algorithms: percentage = averages[algorithm] * 100.0 / (size * size) print(
def kGrid(self): nDemi = int(self.N - 1) / 2 k = Grid(nDemi, nDemi, centered=False) return k
# 'a_example.in', # 'b_should_be_easy.in', 'c_no_hurry.in', # 'd_metropolis.in', # 'e_high_bonus.in' ] best_score = 0 if True: total_score = 0 for i in grids: with open('../inputs/%s' % i) as f: g = Grid() g.read(f) g.solve_lazy_vehicle() if g.total_score() > best_score: with open('../outputs/%s#score=%d.txt' % (i, g.total_score()), 'w') as f: g.write(f) best_score = g.total_score() print('%s done! Score: %d' % (i, g.total_score())) total_score += g.total_score() print('Total Score:%d' % total_score)
class EncryptView(EasyFrame): """A window for an encryption process.""" def __init__(self): EasyFrame.__init__(self, title = "Block Cipher Encryption") self.setResizable(False) self.matrix = makeMatrix() self.matrixPanel = self.addPanel(row = 0, column = 0) self.addCanvases() fieldPanel = self.addPanel(row = 8, column = 0, columnspan = 12, background = "yellow") fieldPanel.addLabel(text = "Plaintext", row = 0, column = 0, background = "yellow") self.plainField = fieldPanel.addTextField(text = "", row = 0, column = 1) fieldPanel.addLabel(text = "Ciphertext", row = 1, column = 0, background = "yellow") self.cipherField = fieldPanel.addTextField("", row = 1, column = 1, state = "readonly") buttonPanel = self.addPanel(row = 9, column = 0, columnspan = 12, background = "black") self.encryptButton = buttonPanel.addButton(text = "Encrypt", row = 0, column = 0, command = self.encrypt) self.matrixButton = buttonPanel.addButton(text = "New matrix", row = 0, column = 1, command = self.newMatrix) def addCanvases(self): """Adds canvases with the characters to the matrix panel and saves them in a grid for later reference.""" self.canvasGrid = Grid(self.matrix.getHeight(), self.matrix.getWidth()) for row in range(self.matrix.getHeight()): for column in range(self.matrix.getWidth()): canvas = MatrixCanvas(self, 20, 20, self.matrix[row][column]) self.canvasGrid[row][column] = canvas self.matrixPanel.addCanvas(canvas = canvas, row = row, column = column) def newMatrix(self): """Creates a new matrix and resets the matrix canvasses with data.""" self.matrix = makeMatrix() for row in range(self.matrix.getHeight()): for column in range(self.matrix.getWidth()): self.canvasGrid[row][column].draw(self.matrix[row][column]) def selectCanvas(self, row, column, color): """Paints the background of the canvas at the given row and column.""" self.canvasGrid[row][column]["background"] = color def deselectCanvasses(self): """Resets the background of the canvasses in the grid.""" for row in range(self.canvasGrid.getHeight()): for column in range(self.canvasGrid.getWidth()): self.canvasGrid[row][column]["background"] = "white" def encrypt(self): """Uses matrix to encrypt plainText. Does one pair of characters at a time.""" self.cipherText = self.cipherField.getText() # Set up the initial state of the encryption. if self.cipherText == "": self.matrixButton["state"] = "disabled" self.plainText = self.plainField.getText() self.limit = len(self.plainText) if self.limit % 2 == 1: self.limit -= 1 self.cursor = 0 # Use the matrix to encrypt one pair of characters. if self.cursor < self.limit: self.cipherText += self.encryptPair() self.cipherField.setText(self.cipherText) self.cursor += 2 # Add the last character if plaintext length was odd. elif self.limit < len(self.plainText): self.cipherText += self.plainText[self.limit] self.cipherField.setText(self.cipherText) # Clean up when done. if len(self.plainText) == len(self.cipherText): self.encryptButton["text"] = "Clear fields" self.encryptButton["command"] = self.clearFields def encryptPair(self): """Returns the cipherText of the pair of characters at cursor and cursor + 1 in plainText.""" # Locate the characters in the matrix self.deselectCanvasses() (row1, col1) = self.matrix.find(self.plainText[self.cursor]) (row2, col2) = self.matrix.find(self.plainText[self.cursor + 1]) self.selectCanvas(row1, col1, "gray") self.selectCanvas(row2, col2, "gray") # Swap them if they are in the same row or column if row1 == row2 or col1 == col2: return self.plainText[self.cursor + 1] + self.plainText[self.cursor] # Otherwise, use the characters at the opposite # corners of the rectangle in the matrix else: self.selectCanvas(row2, col1, "pink") self.selectCanvas(row1, col2, "pink") ch1 = self.matrix[row2][col1] ch2 = self.matrix[row1][col2] return ch1 + ch2 def clearFields(self): """Resets fields and buttons.""" self.deselectCanvasses() self.plainField.setText("") self.cipherField.setText("") self.encryptButton["text"] = "Encrypt" self.encryptButton["command"] = self.encrypt self.matrixButton["state"] = "normal"
if grid.get_cell_value(x, y) == 0: grid.set_cell_value(x, y, 'o') def waiting_for_connection(): global connection_established, conn, addr conn, addr = sock.accept() # Hangs the code until a connection is established so threading is needed print('Client connected') connection_established = True receive_data() # Allowing waiting_for_connection() function to run simultaneously to the rest of the code create_thread(waiting_for_connection) grid = Grid() running = True player = 'x' turn = True playing = 'True' def draw_screen(color): screen.fill(color) grid.draw(screen) pygame.display.flip() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False
from car import HorizontalCar, VerticalCar from coordinate import Coordinate from grid import Grid import view ''' Project description here. ''' # Game window size. size = (700, 700) # Set up game. grid = Grid(10, 10) car1 = HorizontalCar(grid, Coordinate(0, 0), 2, view.BLUE) car2 = HorizontalCar(grid, Coordinate(3, 0), 3, view.GREEN) car3 = VerticalCar(grid, Coordinate(5, 5), 2, view.RED) grid.add_car(car1) grid.add_car(car2) grid.add_car(car3) grid.add_exit(Coordinate(5, -1)) view.game(size, grid)
class TetrisWindow(arcade.Window): def __init__(self, width, height, title): super().__init__(width, height, title) self.center_window() self.grid = Grid() self.timer = 0 self.state = States.PLAYING self.down_key_held = False def on_draw(self): arcade.start_render() self.grid.draw_all() # Szövegek megjelnítése az ablak jobb oldali részében. arcade.draw_text("Cleared rows:", 832, 840, arcade.color.AERO_BLUE, 20) arcade.draw_text(str(self.grid.cleared_rows), 896, 800, arcade.color.AERO_BLUE, 25) arcade.draw_text("Next letter:", 832, 600, arcade.color.AERO_BLUE, 20) arcade.draw_text("Press P to pause", 852, 80, arcade.color.AERO_BLUE, 15) arcade.draw_text("Press ESC to exit", 852, 40, arcade.color.AERO_BLUE, 15) # Pause valamint a Game Over szövegek. if self.state == States.PAUSE: arcade.draw_text("Game paused", 256, 480, arcade.color.YELLOW, 40) elif self.state == States.LOST: arcade.draw_rectangle_filled(256 + 128, 480 + 10, 512, 140, arcade.color.YANKEES_BLUE) arcade.draw_text("Game Over!", 256, 480, arcade.color.YELLOW, 40) arcade.draw_text("Press Space to restart", 256 + 48, 440, arcade.color.AERO_BLUE, 15) def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.UP and self.state == States.PLAYING: """ Másoljuk át a main_grid adatait a test_grid-be. """ self.grid.grid_copy(self.grid.main_grid, self.grid.test_grid) """ Forgassuk el a betűt a main_grid-en. """ self.grid.rotate_letter() """ Ellenőrizzük, hogy nem e lett felülírva a fal, vagy a megálapodott betűk.""" if not self.grid.check_grids(): """ Ha felülírtunk valamit, akkor visszamásoljuk az adatokat a test_grid-ből a main_grid-be.""" self.grid.grid_copy(self.grid.test_grid, self.grid.main_grid) elif symbol == arcade.key.LEFT and self.state == States.PLAYING: self.grid.move_left() elif symbol == arcade.key.RIGHT and self.state == States.PLAYING: self.grid.move_right() elif symbol == arcade.key.DOWN and self.state == States.PLAYING: self.down_key_held = True elif symbol == arcade.key.SPACE and self.state == States.LOST: self.grid.restart() self.state = States.PLAYING elif symbol == arcade.key.ESCAPE: sys.exit() elif symbol == arcade.key.P: if self.state == States.PLAYING: self.state = States.PAUSE else: self.state = States.PLAYING def on_key_release(self, symbol: int, modifiers: int): if symbol == arcade.key.DOWN and self.state == States.PLAYING: self.down_key_held = False def on_update(self, dt): if self.state == States.PLAYING: self.timer += dt if self.down_key_held and self.timer >= 0.05: self.grid.move_down() self.timer = 0 else: if self.timer >= 0.5: self.grid.move_down() self.timer = 0 if self.grid.game_over: self.state = States.LOST
def __init__(self): self.grid = Grid() self.active_tet = Tetramino()
def __init__(self, master): """Constructor Parameters: master (tk.Tk): tkinter root widget """ self._master = master self._world = World((GRID_WIDTH, GRID_HEIGHT), BLOCK_SIZE) master.title('Ninedraft') load_simple_world(self._world) self._player = Player() self._world.add_player(self._player, 250, 150) self._world.add_collision_handler( "player", "item", on_begin=self._handle_player_collide_item) self._hot_bar = SelectableGrid(rows=1, columns=10) self._hot_bar.select((0, 0)) starting_hotbar = [ Stack(create_item("dirt"), 20), Stack(create_item("apple"), 20), Stack(create_item("pickaxe", "stone"), 1), Stack(create_item("diamond"), 20), Stack(create_item("wool"), 20), Stack(create_item("furnace"), 1), Stack(create_item("honey"), 1), Stack(create_item("hive"), 1), Stack(create_item("bow"), 1), Stack(create_item("arrow"), 20) ] for i, item in enumerate(starting_hotbar): self._hot_bar[0, i] = item self._hands = create_item('hands') starting_inventory = [ ((1, 5), Stack(Item('dirt'), 10)), ((0, 2), Stack(Item('wood'), 10)), ] self._inventory = Grid(rows=3, columns=10) for position, stack in starting_inventory: self._inventory[position] = stack self._crafting_window = None self._master.bind("e", lambda e: self.run_effect( ('crafting', 'basic'))) self._view = GameView(master, self._world.get_pixel_size(), NewWorldViewRouter(BLOCK_COLOURS, ITEM_COLOURS)) self._view.pack() # Task 1.2 Mouse Controls: Bind mouse events here # ... self._view.bind("<Motion>", self._mouse_move) self._view.bind("<Leave>", self._mouse_leave) self._master.bind("<Button-1>", self._left_click) self._view.bind("<Button-3>", self._right_click) # Task 1.3: Create instance of StatusView here # ... self._statusview = StatusView(master, self._player.get_health(), self._player.get_food()) self._statusview.pack(side=tk.TOP) self._hot_bar_view = ItemGridView(master, self._hot_bar.get_size()) self._hot_bar_view.pack(side=tk.TOP, fill=tk.X) # Task 1.5 Keyboard Controls: Bind to space bar for jumping here # ... self._master.bind("<space>", lambda e: self._jump()) self._master.bind("a", lambda e: self._move(-1, 0)) self._master.bind("<Left>", lambda e: self._move(-1, 0)) self._master.bind("d", lambda e: self._move(1, 0)) self._master.bind("<Right>", lambda e: self._move(1, 0)) self._master.bind("s", lambda e: self._move(0, 1)) self._master.bind("<Down>", lambda e: self._move(0, 1)) # Task 1.5 Keyboard Controls: Bind numbers to hotbar activation here # ... self._master.bind("1", lambda e: self._hot_bar.select((0, 0))) self._master.bind("2", lambda e: self._hot_bar.select((0, 1))) self._master.bind("3", lambda e: self._hot_bar.select((0, 2))) self._master.bind("4", lambda e: self._hot_bar.select((0, 3))) self._master.bind("5", lambda e: self._hot_bar.select((0, 4))) self._master.bind("6", lambda e: self._hot_bar.select((0, 5))) self._master.bind("7", lambda e: self._hot_bar.select((0, 6))) self._master.bind("8", lambda e: self._hot_bar.select((0, 7))) self._master.bind("9", lambda e: self._hot_bar.select((0, 8))) self._master.bind("0", lambda e: self._hot_bar.select((0, 9))) # Task 1.6 File Menu & Dialogs: Add file menu here # ... menu_bar = tk.Menu(self._master) master.config(menu=menu_bar) file_menu = tk.Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label='File', menu=file_menu) file_menu.add_command(label='New Game', command=self.restart) file_menu.add_command(label='Exit', command=self.exit) master.protocol("WM_DELETE_WINDOW", self.exit) self._target_in_range = False self._target_position = 0, 0 self.redraw() self.step()
from agent import Agent from rand_agent import Rand_agent from player_agent import Player, Player2 from gen_agent import Gen_agent, Population from p_agent import P_agent from rl_agent import RL_agent, RL_agent2, RRL_agent import q_agent pygame.init() w_width = settings.w_width w_height = settings.w_height screen = pygame.display.set_mode((w_width, w_height)) done = False # Making our world grid = Grid(w_width, w_height, screen) grid.draw(screen) # Making an agent agent = Rand_agent(0, w_height//2) player = Player2(w_width//2, w_height//2) agents = [agent, player] # # Make a population of genetic agents genetic_agents = q_agent.Population(100, grid, screen) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True
def convert_sdk(filestream): content: str = filestream.read() lines = content.replace('.', '0').split('\n') grid = [list(line) for line in lines] num_grid = list(map(lambda row : list(map(lambda value : int(value), row)), grid)) return Grid(num_grid)
'model_name': model_name }), } return render_to_response('djgrid/djgrid_listview.html', context, context_instance=RequestContext(request)) if request.method == 'POST': if 'initial' in request.POST: final = {} final['colModel'], final[ 'colNames'] = Grid.make_column_structure( model, fields, app_label=app_label, model_name=model_name, safe=self.get_safe_list(model_name), inline=self._meta.inline, readonly=self._meta.readonly) return HttpResponse(simplejson.dumps(final), mimetype='application/json') else: queryset = model.objects.all() grid = Grid(queryset=queryset, fields=fields, post=request.POST, app_label=app_label, model_name=model_name, model=model, description=self._meta.description,
def GameLoop(self): #FIELDS global nodeSize global labelCounter global LEFT global RIGHT global mouse_position global pathfinding global drawing global merged global last_pos global isInsideNode global exitedNode global placeNewPoint global playerOneName global playerTwoName global pathFound global displayName global displayInst global instMsgClickNode global instMsgFinishPath global instMsgPlacePoint global instMsgSaveLine #Set background to white self.disp.screen.fill(self.disp.WHITE) #Create grid object, ie. underlying grid-graph. G = Grid(self.disp.size[0], self.disp.size[1]) #Set currently displayed name displayName = playerOneName #This will be a list that will contain all the sprites we intend to use in our game. all_sprites_list = pygame.sprite.Group() startNode = None carryOn = True clock = pygame.time.Clock() while carryOn: for event in pygame.event.get(): #Allows the user to close the window if event.type == pygame.QUIT: carryOn = False elif pathFound: #If a path has just been found, wait for the user to either accept or discard the found line. keys = pygame.key.get_pressed() if keys[K_SPACE]: self.permLst.merge(self.tempLst) pathFound = False placeNewPoint = True startNode.incrementCounter() endNode.incrementCounter() displayInst = instMsgPlacePoint elif keys[K_ESCAPE]: self.tempLst.drawLst(self.disp.screen, self.disp.WHITE) self.tempLst = LinkedList() pathFound = False placeNewPoint = False displayInst = instMsgClickNode elif event.type == MOUSEBUTTONDOWN and event.button == RIGHT: #When right mb is pressed, checks if mouse is over a node, if so save node for pathfinding. pos = pygame.mouse.get_pos() for sprite in self.all_sprites_list: if sprite.rect.collidepoint(pos): if (sprite.isFull()): print("Illegal move, node is full") displayInst = instMsgNodeIsFull elif (placeNewPoint): print("Place a new point, by left clicking") elif pathfinding and not (sprite == startNode): print("TO") #Terminal node endNode = sprite print(endNode.getCoordinates()) #debug print("FINDING PATH...") try: #Checks if there is a path Grid.find_path( startNode, endNode, self.tempLst, self.G, self.all_sprites_list ) #Find path from prev. node to current node. displayInst = instMsgSaveLine pathFound = True except Exception as e: print(str(e)) displayInst = instMsgNoPathfind #No longer pathfinding pathfinding = False H = None #Draw found path, if any, red self.tempLst.drawLst(self.disp.screen, self.disp.LIGHT_RED) else: #Source node startNode = sprite print("FROM") print(sprite.getCoordinates()) #debug pathfinding = True #Start pathfinding displayInst = instMsgFinishPath elif event.type == MOUSEMOTION and pygame.mouse.get_pressed( )[0]: if ( drawing ): #If the mouse moves, and the user is currently drawing pos = pygame.mouse.get_pos() # Restrict the mouse from going into the top region of the window convert = list(pos) if convert[1] < 50: convert[1] = 50 pos = tuple(convert) # Restrict the mouse from going into the bottom region of the window convert = list(pos) if convert[1] > 450: convert[1] = 450 pos = tuple(convert) for sprite in self.all_sprites_list: if sprite.rect.collidepoint(pos): isInsideNode = True break else: isInsideNode = False exitedNode = True # Add the new line to the linked list and draw the line if last_pos is not None and not isInsideNode: # Draws a line between the current mouse position and the mouse position from the last frame self.tempLst.prepend((last_pos, pos)) self.tempLst.drawHead(self.disp.screen, self.disp.LIME_GREEN) last_pos = pos elif event.type == MOUSEBUTTONUP and event.button == LEFT: #When mouse is released, checks if mouse is over a node pos = pygame.mouse.get_pos() for sprite in self.all_sprites_list: if sprite.rect.collidepoint(pos): if (sprite.isFull() or (sprite == startNode and sprite.getCounter() >= 2)): print("Illegal move, node is full") displayInst = instMsgNodeIsFull elif (collision(self.tempLst, self.permLst)): print("Collision with an edge detected") elif (disconnected(self.tempLst)): print("Collision with a node detected") elif exitedNode: #Add edge to perm list of edges. self.fixList.prepend( (self.tempLst.head.data[1], (sprite.rect.centerx, sprite.rect.centery))) #fix visual bug self.permLst.merge(self.tempLst) merged = True endNode = sprite #increment degree of both nodes sprite.incrementCounter() startNode.incrementCounter() print(sprite.getCounter()) placeNewPoint = True displayInst = instMsgPlacePoint if (not merged ): # Delete drawn line if it didn't end in a sprite self.tempLst.drawLst(self.disp.screen, self.disp.WHITE) self.tempLst = LinkedList() #Reset mouse position, tempList and drawing status on release. mouse_position = (0, 0) last_pos = None drawing = False merged = False exitedNode = False elif event.type == MOUSEBUTTONDOWN and event.button == LEFT: #When mouse is pressed, checks if mouse is over a node, if so start drawing. pos = pygame.mouse.get_pos() if (placeNewPoint): newNode = self.newPointOnLine(pos, startNode, endNode, nodeSize) self.all_sprites_list.add(newNode) Grid.block_nodes(self.tempLst, self.G, startNode, endNode, newNode) startNode = None endNode = None self.tempLst = LinkedList() displayInst = instMsgClickNode if (displayName == playerOneName): displayName = playerTwoName else: displayName = playerOneName elif (pathfinding): print( "Finish path finding by right clicking on a node") else: for sprite in self.all_sprites_list: if sprite.rect.collidepoint(pos): if (sprite.isFull()): print("Illegal move, node is full") displayInst = instMsgNodeIsFull else: #save pressed node startNode = sprite drawing = True exitedNode = False placeNewPoint = False #Update visuals self.permLst.drawLst(self.disp.screen, self.disp.LIME_GREEN) self.fixList.drawLst(self.disp.screen, self.disp.LIME_GREEN) self.disp.gameButton("Controls", 20, 0, 100, 50, self.disp.BLACK, self.disp.GREEN, drawing, self.showControls) self.disp.gameButton("Surrender", self.disp.size[0] - 140, 0, 120, 50, self.disp.BLACK, self.disp.GREEN, drawing, self.chooseWinner) self.all_sprites_list.draw(self.disp.screen) self.disp.turnTracker(displayName) self.disp.turnInstructions(displayInst) self.disp.updateScreen(pygame) #Number of frames per secong e.g. 60 clock.tick(120) #Quit game if gameloop is exited pygame.quit()
class GameManager(object): def __init__(self, size=4, win_num=2048): self.size = size self.win_num = win_num self.reset() def reset(self): self.state = 'init' self.win = False self.over = False self.score = 0 self.grid = Grid(self.size) self.grid.reset() @property def screen(self): return Screen(screen=self.stdscr, score=self.score, grid=self.grid, win=self.win, over=self.over) def move(self, direction): if self.can_move(direction): getattr(self.grid, 'move_' + direction)() self.grid.add_random_item() return True else: return False @property def is_win(self): self.win = max(chain(*self.grid.cells)) >= self.win_num return self.win @property def is_over(self): self.over = not any( self.can_move(move) for move in self.action.actions) return self.over def can_move(self, direction): return getattr(self.grid, 'can_move_' + direction)() def state_init(self): self.reset() return 'game' def state_game(self): self.screen.draw() action = self.action.get() if action == Action.RESTART: return 'init' if action == Action.EXIT: return 'exit' if self.move(action): if self.is_win: return 'win' if self.is_over: return 'over' return 'game' def _restart_or_exit(self): self.screen.draw() return 'init' if self.action.get() == Action.RESTART else 'exit' def state_win(self): return self._restart_or_exit() def state_over(self): return self._restart_or_exit() def __call__(self, stdscr): curses.use_default_colors() self.stdscr = stdscr self.action = Action(stdscr) while self.state != 'exit': self.state = getattr(self, 'state_' + self.state)()
class Ninedraft: """High-level app class for Ninedraft, a 2d sandbox game""" def __init__(self, master): """Constructor Parameters: master (tk.Tk): tkinter root widget """ self._master = master self._world = World((GRID_WIDTH, GRID_HEIGHT), BLOCK_SIZE) master.title('Ninedraft') load_simple_world(self._world) self._player = Player() self._world.add_player(self._player, 250, 150) self._world.add_collision_handler( "player", "item", on_begin=self._handle_player_collide_item) self._hot_bar = SelectableGrid(rows=1, columns=10) self._hot_bar.select((0, 0)) starting_hotbar = [ Stack(create_item("dirt"), 20), Stack(create_item("apple"), 20), Stack(create_item("pickaxe", "stone"), 1), Stack(create_item("diamond"), 20), Stack(create_item("wool"), 20), Stack(create_item("furnace"), 1), Stack(create_item("honey"), 1), Stack(create_item("hive"), 1), Stack(create_item("bow"), 1), Stack(create_item("arrow"), 20) ] for i, item in enumerate(starting_hotbar): self._hot_bar[0, i] = item self._hands = create_item('hands') starting_inventory = [ ((1, 5), Stack(Item('dirt'), 10)), ((0, 2), Stack(Item('wood'), 10)), ] self._inventory = Grid(rows=3, columns=10) for position, stack in starting_inventory: self._inventory[position] = stack self._crafting_window = None self._master.bind("e", lambda e: self.run_effect( ('crafting', 'basic'))) self._view = GameView(master, self._world.get_pixel_size(), NewWorldViewRouter(BLOCK_COLOURS, ITEM_COLOURS)) self._view.pack() # Task 1.2 Mouse Controls: Bind mouse events here # ... self._view.bind("<Motion>", self._mouse_move) self._view.bind("<Leave>", self._mouse_leave) self._master.bind("<Button-1>", self._left_click) self._view.bind("<Button-3>", self._right_click) # Task 1.3: Create instance of StatusView here # ... self._statusview = StatusView(master, self._player.get_health(), self._player.get_food()) self._statusview.pack(side=tk.TOP) self._hot_bar_view = ItemGridView(master, self._hot_bar.get_size()) self._hot_bar_view.pack(side=tk.TOP, fill=tk.X) # Task 1.5 Keyboard Controls: Bind to space bar for jumping here # ... self._master.bind("<space>", lambda e: self._jump()) self._master.bind("a", lambda e: self._move(-1, 0)) self._master.bind("<Left>", lambda e: self._move(-1, 0)) self._master.bind("d", lambda e: self._move(1, 0)) self._master.bind("<Right>", lambda e: self._move(1, 0)) self._master.bind("s", lambda e: self._move(0, 1)) self._master.bind("<Down>", lambda e: self._move(0, 1)) # Task 1.5 Keyboard Controls: Bind numbers to hotbar activation here # ... self._master.bind("1", lambda e: self._hot_bar.select((0, 0))) self._master.bind("2", lambda e: self._hot_bar.select((0, 1))) self._master.bind("3", lambda e: self._hot_bar.select((0, 2))) self._master.bind("4", lambda e: self._hot_bar.select((0, 3))) self._master.bind("5", lambda e: self._hot_bar.select((0, 4))) self._master.bind("6", lambda e: self._hot_bar.select((0, 5))) self._master.bind("7", lambda e: self._hot_bar.select((0, 6))) self._master.bind("8", lambda e: self._hot_bar.select((0, 7))) self._master.bind("9", lambda e: self._hot_bar.select((0, 8))) self._master.bind("0", lambda e: self._hot_bar.select((0, 9))) # Task 1.6 File Menu & Dialogs: Add file menu here # ... menu_bar = tk.Menu(self._master) master.config(menu=menu_bar) file_menu = tk.Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label='File', menu=file_menu) file_menu.add_command(label='New Game', command=self.restart) file_menu.add_command(label='Exit', command=self.exit) master.protocol("WM_DELETE_WINDOW", self.exit) self._target_in_range = False self._target_position = 0, 0 self.redraw() self.step() def restart(self): """Restarts the game""" answer = messagebox.askyesno( title='New Game?', message='Are you sure you would like to start a new game?') if answer: for thing in self._world.get_all_things(): self._world.remove_thing(thing) load_simple_world(self._world) self._player = Player() self._world.add_player(self._player, 250, 150) self._hot_bar.select((0, 0)) starting_hotbar = [ Stack(create_item("dirt"), 20), Stack(create_item("apple"), 20), Stack(create_item("pickaxe", "stone"), 1), Stack(create_item("diamond"), 20), Stack(create_item("wool"), 20), Stack(create_item("furnace"), 1), Stack(create_item("honey"), 1), Stack(create_item("hive"), 1), Stack(create_item("bow"), 1), Stack(create_item("arrow"), 20) ] for position, cell in self._hot_bar.items(): self._hot_bar[position] = None for i, item in enumerate(starting_hotbar): self._hot_bar[0, i] = item for position, cell in self._inventory.items(): self._inventory[position] = None starting_inventory = [ ((1, 5), Stack(Item('dirt'), 10)), ((0, 2), Stack(Item('wood'), 10)), ] for position, stack in starting_inventory: self._inventory[position] = stack def exit(self): """Exits the application""" answer = messagebox.askyesno( title='Exit', message='Are you sure you want to quit Ninedraft?') if answer: self._master.destroy() def redraw(self): self._view.delete(tk.ALL) # physical things self._view.draw_physical(self._world.get_all_things()) # target target_x, target_y = self._target_position target = self._world.get_block(target_x, target_y) cursor_position = self._world.grid_to_xy_centre( *self._world.xy_to_grid(target_x, target_y)) # Task 1.2 Mouse Controls: Show/hide target here # ... self._view.show_target(self._player.get_position(), self._target_position) if not self._target_in_range: self._view.hide_target() # Task 1.3 StatusView: Update StatusView values here # ... self._statusview.set_health(self._player.get_health()) self._statusview.set_food(self._player.get_food()) # hot bar self._hot_bar_view.render(self._hot_bar.items(), self._hot_bar.get_selected()) def step(self): data = GameData(self._world, self._player) self._world.step(data) self.redraw() # Task 1.6 File Menu & Dialogs: Handle the player's death if necessary # ... if self._player.is_dead(): self.restart() self._master.after(15, self.step) def _move(self, dx, dy): self.check_target() velocity = self._player.get_velocity() self._player.set_velocity((velocity.x + dx * 80, velocity.y + dy * 80)) def _jump(self): self.check_target() velocity = self._player.get_velocity() # Task 1.2: Update the player's velocity here # ... self._player.set_velocity((velocity.x / 1.5, velocity.y - 150)) def mine_block(self, block, x, y): luck = random.random() active_item, effective_item = self.get_holding() was_item_suitable, was_attack_successful = block.mine( effective_item, active_item, luck) effective_item.attack(was_attack_successful) # if the block has been mined if block.is_mined(): # Task 1.2 Mouse Controls: Reduce the player's food/health appropriately # ... if self._player.get_food() > 0: self._player.change_food(-0.5) else: self._player.change_health(-2.5) # Task 1.2 Mouse Controls: Remove the block from the world & get its drops # ... self._world.remove_item(block) if luck < 1: drops = block.get_drops(luck, was_item_suitable) # Have a look at the World class for removing # Have a look at the Block class for getting the drops if not drops: return x0, y0 = block.get_position() for i, (drop_category, drop_types) in enumerate(drops): print(f'Dropped {drop_category}, {drop_types}') if drop_category == "item": physical = DroppedItem(create_item(*drop_types)) # this is so bleh x = x0 - BLOCK_SIZE // 2 + 5 + ( i % 3) * 11 + random.randint(0, 2) y = y0 - BLOCK_SIZE // 2 + 5 + ( (i // 3) % 3) * 11 + random.randint(0, 2) self._world.add_item(physical, x, y) elif drop_category == "block": self._world.add_block(create_block(*drop_types), x, y) else: raise KeyError(f"Unknown drop category {drop_category}") def get_holding(self): active_stack = self._hot_bar.get_selected_value() active_item = active_stack.get_item() if active_stack else self._hands effective_item = active_item if active_item.can_attack( ) else self._hands return active_item, effective_item def check_target(self): # select target block, if possible active_item, effective_item = self.get_holding() pixel_range = active_item.get_attack_range( ) * self._world.get_cell_expanse() self._target_in_range = positions_in_range(self._player.get_position(), self._target_position, pixel_range) def _mouse_move(self, event): self._target_position = event.x, event.y self.check_target() def _mouse_leave(self, event): self._target_in_range = False def _left_click(self, event): # Invariant: (event.x, event.y) == self._target_position # => Due to mouse move setting target position to cursor x, y = self._target_position if self._target_in_range: block = self._world.get_block(x, y) if block: self.mine_block(block, x, y) elif "Sheep('sheep')": block = WoolBlock("wool", "wood") block.get_drops(1, True) def _trigger_crafting(self, craft_type): print(f"Crafting with {craft_type}") CRAFTING_RECIPES_2x2 = [ (((None, 'wood'), (None, 'wood')), Stack(create_item('stick'), 4)), ((('wood', 'wood'), ('wood', 'wood')), Stack(create_item('crafting_table'), 1)), ((('dirt', 'dirt'), ('dirt', 'dirt')), Stack(create_item('wood'), 1)), ((('stone', 'stone'), ('stone', 'stone')), Stack(create_item('diamond'), 1)), ((('apple', 'apple'), ('apple', 'apple')), Stack(create_item('honey'), 1)), ] CRAFTING_RECIPES_3x3 = { (((None, None, None), (None, 'wood', None), (None, 'wood', None)), Stack(create_item('stick'), 16)), ((('wood', 'wood', 'wood'), (None, 'stick', None), (None, 'stick', None)), Stack(create_item('pickaxe', 'wood'), 1)), ((('stone', 'stone', 'stone'), (None, 'stick', None), (None, 'stick', None)), Stack(create_item('pickaxe', 'stone'), 1)), ((('diamond', 'diamond', 'diamond'), (None, 'stick', None), (None, 'stick', None)), Stack(create_item('pickaxe', 'diamond'), 1)), ((('wood', 'wood', None), ('wood', 'stick', None), (None, 'stick', None)), Stack(create_item('axe', 'wood'), 1)), ((('stone', 'stone', None), ('wood', 'stick', None), (None, 'stick', None)), Stack(create_item('axe', 'stone'), 1)), (((None, 'wood', None), (None, 'stick', None), (None, 'stick', None)), Stack(create_item('shovel', 'wood'), 1)), (((None, 'stone', None), (None, 'stick', None), (None, 'stick', None)), Stack(create_item('shovel', 'stone'), 1)), (((None, 'wood', None), (None, 'wood', None), (None, 'stick', None)), Stack(create_item('sword', 'wood'), 1)), (((None, 'stone', None), (None, 'stone', None), (None, 'stick', None)), Stack(create_item('sword', 'stone'), 1)), (((None, None, None), ('wool', 'wool', 'wool'), ('wood', 'wood', 'wood')), Stack(create_item('bed'), 1)), ((('stone', 'stone', 'stone'), ('stone', None, 'stone'), ('stone', 'stone', 'stone')), Stack(create_item('furnace'), 1)) } if craft_type == "basic": crafter = GridCrafter(CRAFTING_RECIPES_2x2, 2, 2) else: crafter = GridCrafter(CRAFTING_RECIPES_3x3, 3, 3) self._crafting_window = CraftingWindow(self._master, craft_type, hot_bar=self._hot_bar, inventory=self._inventory, crafter=crafter) def run_effect(self, effect): if len(effect) == 2: if effect[0] == "crafting": craft_type = effect[1] if craft_type == "basic": print("Can't craft much on a 2x2 grid :/") elif craft_type == "crafting_table": print("Let's get our kraft® on! King of the brands") self._trigger_crafting(craft_type) return elif effect[0] in ("food", "health"): stat, strength = effect if self._player.get_food() < self._player._max_food: stat = "food" else: stat = "health" print(f"Gaining {strength} {stat}!") getattr(self._player, f"change_{stat}")(strength) return raise KeyError(f"No effect defined for {effect}") def _right_click(self, event): print("Right click") x, y = self._target_position target = self._world.get_thing(x, y) if target: # use this thing print(f'using {target}') effect = target.use() print(f'used {target} and got {effect}') if effect: self.run_effect(effect) else: # place active item selected = self._hot_bar.get_selected() if not selected: return stack = self._hot_bar[selected] if not stack: return drops = stack.get_item().place() stack.subtract(1) if stack.get_quantity() == 0: # remove from hotbar self._hot_bar[selected] = None if not drops: return # handling multiple drops would be somewhat finicky, so prevent it if len(drops) > 1: raise NotImplementedError( "Cannot handle dropping more than 1 thing") drop_category, drop_types = drops[0] x, y = event.x, event.y if drop_category == "block": existing_block = self._world.get_block(x, y) if not existing_block: self._world.add_block(create_block(drop_types[0]), x, y) else: raise NotImplementedError( "Automatically placing a block nearby if the target cell is full is not yet implemented" ) elif drop_category == "effect": self.run_effect(drop_types) else: raise KeyError(f"Unknown drop category {drop_category}") def _activate_item(self, index): print(f"Activating {index}") self._hot_bar.toggle_selection((0, index)) def _handle_player_collide_item(self, player: Player, dropped_item: DroppedItem, data, arbiter: pymunk.Arbiter): """Callback to handle collision between the player and a (dropped) item. If the player has sufficient space in their to pick up the item, the item will be removed from the game world. Parameters: player (Player): The player that was involved in the collision dropped_item (DroppedItem): The (dropped) item that the player collided with data (dict): data that was added with this collision handler (see data parameter in World.add_collision_handler) arbiter (pymunk.Arbiter): Data about a collision (see http://www.pymunk.org/en/latest/pymunk.html#pymunk.Arbiter) NOTE: you probably won't need this Return: bool: False (always ignore this type of collision) (more generally, collision callbacks return True iff the collision should be considered valid; i.e. returning False makes the world ignore the collision) """ item = dropped_item.get_item() if self._hot_bar.add_item(item): print(f"Added 1 {item!r} to the hotbar") elif self._inventory.add_item(item): print(f"Added 1 {item!r} to the inventory") else: print(f"Found 1 {item!r}, but both hotbar & inventory are full") return True self._world.remove_item(dropped_item) return False
# plot param.freq_plot = 10 param.plot_interactive = True param.plot_psi = True param.plot_var = 'vorticity' param.cax = np.array([-2, 2.]) * 5 param.colorscheme = 'imposed' param.generate_mp4 = True # physics param.noslip = False param.diffusion = False param.additional_tracer = ['tracer'] grid = Grid(param) param.Kdiff = 5e-2 * grid.dx xr, yr = grid.xr, grid.yr # it's time to modify the mask and add obstacles if you wish, 0 is land msk_config = 'none' # the other possibility is 'T-wall' or 'bay' if msk_config == 'bay': x0, y0, radius = 0.5, 0.35, 0.2 y1 = 0.5 msk2 = ap.vortex(xr, yr, param.Lx, param.Ly, x0, y0, radius, 'step') grid.msk[yr < y1] = 0
# -*- coding: utf-8 -*- import sys import json from grid import Grid, GridGraphic from flask import Flask, request from logger import Logger import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output http_server = Flask(__name__) lgr = Logger() g = Grid() external_stylesheets = [dbc.themes.BOOTSTRAP] app = dash.Dash(__name__, server=http_server, routes_pathname_prefix='/dash/', external_stylesheets=external_stylesheets, suppress_callback_exceptions=True) # Declare containers in app.layout to use callbacks on them app.head = [html.Link(rel="stylesheet", href='assets/styles.css')] app.layout = dbc.Container([ dbc.Container([], id='header'), dbc.Container([ dcc.Input(id='size-input', placeholder='Insert grid size', type='number', value='2',
def queueMaze(mazeText): #parses maze file and captures maze attributes mazeFile = open(mazeText, "r") mazeList = mazeFile.read().splitlines( ) #https://stackoverflow.com/questions/24946640/removing-r-n-from-a-python-list-after-importing-with-readlines mazeFile.close() rows = len(mazeList) columns = len(mazeList[0]) #builds blank grid maze = Grid(rows, columns) #builds maze from list of maze rows for row in range(maze.getHeight()): for column in range(maze.getWidth()): maze[row][column] = mazeList[row][column] #creates intersection queue queue = ArrayQueue() #creates a player player = Player(maze) #searches for starting point of player for r in range(0, rows): for c in range(0, columns): if maze[r][c] == "P": player.setRow(r) player.setColumn(c) break choicePoints = 0 #end condition check while maze[player.getRow()][player.getColumn() + 1] != 'T': #convenience variables representing the value of the grid at these positions relative to player up = maze[player.getRow() - 1][player.getColumn()] down = maze[player.getRow() + 1][player.getColumn()] right = maze[player.getRow()][player.getColumn() + 1] left = maze[player.getRow()][player.getColumn() - 1] #dead end check routes = 0 if up == ' ': routes += 1 if down == ' ': routes += 1 if right == ' ': routes += 1 if left == ' ': routes += 1 if routes == 0: #player is at a dead end. #retrieves the previous intersection from the queue pos = queue.pop() #backtracks the player to previous intersection maze[player.getRow()][player.getColumn()] = '-' player.setRow(pos.getRow()) player.setColumn(pos.getColumn()) maze[pos.getRow()][pos.getColumn()] = 'P' #marks last path as dead end maze[pos.getActivePath()[0]][pos.getActivePath()[1]] = '-' elif routes > 1: #player is at an intersection #increment choice points by 1 choicePoints += 1 intersection = Intersection(player.getRow(), player.getColumn()) if up == ' ': intersection.setActivePath( [player.getRow() - 1, player.getColumn()]) nextMove = player.moveUp() elif down == ' ': intersection.setActivePath( [player.getRow() + 1, player.getColumn()]) nextMove = player.moveDown() elif right == ' ': intersection.setActivePath( [player.getRow(), player.getColumn() + 1]) nextMove = player.moveRight() elif left == ' ': intersection.setActivePath( [player.getRow(), player.getColumn() - 1]) nextMove = player.moveLeft() queue.add(intersection) else: #the player is not at a dead end if down == ' ': nextMove = player.moveDown() elif up == ' ': nextMove = player.moveUp() elif right == ' ': nextMove = player.moveRight() elif left == ' ': nextMove = player.moveLeft() #moves player to the next position nextMove #moves P to the end of the maze maze[player.getRow()][player.getColumn()] = "-" maze[player.getRow()][player.getColumn() + 1] = "P" print("Queue-based Maze Solution:\n") print(maze) print("Choice points: " + str(choicePoints)) #writes maze solution to text file fw = open("queuesolution.txt", "w") fw.writelines(str(maze)) fw.write("Choice points: " + str(choicePoints) + "\n") fw.close()
def initializeGameState( self, filename ): #Initializes the game state specified in the textfile "filename" self.G = Grid(self.disp.size[0], self.disp.size[1]) margin = 100 lineCounter = 0 y = 1 x = 1 firstRead = False f = open(filename, "r") lines = f.readlines() for line in lines: lineCounter += 1 if not ( firstRead ): #For the very first line of the file, initialize only n nodes in grid-like structure n = int(line) for labelCounter in range(1, n + 1): currNode = Node(self.disp.BROWN, nodeSize, nodeSize, (margin * x), (margin * y), 0, labelCounter) self.all_sprites_list.add(currNode) x += 1 if ((margin * x)) >= (self.disp.size[0]): x = 1 y += 1 firstRead = True else: #For the rest of the lines in the file, connect nodes as specified, in the given order, until an error is encountered. labels = line.split() startNode = self.all_sprites_list.sprites()[int(labels[0]) - 1] endNode = self.all_sprites_list.sprites()[int(labels[1]) - 1] if startNode.isFull() or endNode.isFull( ): #Check if a move would exceed the allowed maximum degree print( "Line {} would cause a node to exceed degree 3".format( lineCounter)) startNode = None endNode = None self.tempLst = LinkedList() break elif ( labels[0] == labels[1] ): #Check if a move asks for a loop, loops are allowed but the pathfinding algorithm can not handle it. print("Loop detected at line {}, ending initialization". format(lineCounter)) startNode = None endNode = None self.tempLst = LinkedList() break try: Grid.find_path( startNode, endNode, self.tempLst, self.G, self.all_sprites_list ) #Try to find a path between the specified nodes. except: print( "Could not find a path between nodes {} and {} at line {} of initalize.txt.." .format(labels[0], labels[1], lineCounter)) startNode = None endNode = None self.tempLst = LinkedList() break #Place a new node on the found line, increment degrees, block nodes in the underlying grid, before moving on to the next line newNode = self.generate_node_on_path(startNode, endNode, self.tempLst, self.G) startNode.incrementCounter() endNode.incrementCounter() self.all_sprites_list.add(newNode) #Grid.remove_node_area(newNode,self.G,0) Grid.block_nodes(self.tempLst, self.G, startNode, endNode, newNode) self.permLst.merge(self.tempLst) startNode = None endNode = None self.tempLst = LinkedList() #Initialization finished print("Done with initialization")