public MainForm() { InitializeComponent(); grid = new Cell[9,9]; Random rand = new Random(); List<Point> potentialMineLocations = new List<Point>(grid.Length); for (int i = 0; i < grid.GetLength(0); i++) { for (int j = 0; j < grid.GetLength(1); j++) { potentialMineLocations.Add(new Point(i, j)); } } for (int i = 0; i < 10; i++) { Point x = potentialMineLocations[rand.Next(potentialMineLocations.Count)]; grid[x.X, x.Y] = new MineCell(); } for (int i = 0; i < grid.GetLength(0); i++) { for (int j = 0; j < grid.GetLength(1); j++) { if (grid[i, j] is MineCell) continue; grid[i, j] = new SafeCell(); ((SafeCell)grid[i, j]).CellValue = GetNeighbouringCellCount(i, j); } } }
public static void Recalculate(INavigationTarget target) { cellSize = target.CellSize; width = target.XCells; height = target.ZCells; maxHeight = target.MaxHeight; maxSlope = target.MaxSlope; worldOffset = new Vector3(-width * cellSize / 2f, 0, -height * cellSize / 2f); linearCost = cellSize; diagonalCost = (float)Math.Sqrt(2) * cellSize; var halfCell = new Vector3(cellSize / 2, 0, cellSize / 2); cells = new Cell[width, height]; // Scan the area of the mesh from above to find the walkable parts int xLength = cells.GetLength(0); int zLength = cells.GetLength(1); for (int x = 0; x < xLength; x++) { for (int z = 0; z < zLength; z++) { cells[x, z] = new Cell { Center = worldOffset + new Vector3(x * cellSize, maxHeight, z * cellSize) + halfCell, X = x, Z = z }; target.SetCellIntersections(cells[x, z]); } } }
public Maze (int width, int height) { map = new Cell[width, height]; //Generate all the cells, and set them as undetermined. for (int i = 0; i < map.GetLength (0); i++) for (int j = 0; j < map.GetLength (1); j++) map [i, j] = new Cell (i, j, 0); }
public MatrixViewModel(int matrixSizeWidth, int matrixSizeHeight) { Matrix = new Cell[matrixSizeWidth, matrixSizeHeight]; for (int i = 0; i < Matrix.GetLength(0); i++) for (int j = 0; j < Matrix.GetLength(1); j++) { Matrix[i, j] = new Cell(i, j); } }
public Grille(int width, int height) { cellules = new Cell[width, height]; for (int i = 0; i < cellules.GetLength(0); i++) { for (int j = 0; j < cellules.GetLength(1); j++) { cellules[i,j] = new Cell(j, i); } } }
public GuiGrid(GuiScreen screen) { this.screen = screen; cells = new Cell[8, 8]; CellSize = new Point(60, 60); SetSize(new Point(cells.GetLength(0) * CellSize.X, cells.GetLength(1) * CellSize.Y)); destroyers = new List<Destroyer>(); random = new Random(); shapes = Enum.GetValues(typeof(Shape)); IsAnimating = false; }
public AboxSolver(Cell[,] map, Cell[,] top) { this.map = map; this.top = top; w = map.GetLength(0); h = map.GetLength(1); directions = new List<Dirs>(); directions.Add(new Dirs(-1, 0, "4")); directions.Add(new Dirs(1, 0, "6")); directions.Add(new Dirs(0, -1, "8")); directions.Add(new Dirs(0, 1, "2")); }
public void FindPath(Cell startCell, Cell goalCell, Cell[,] map, bool targetCellMustBeFree) { this.map = map; this.mapWidth = map.GetLength(0); this.mapHeight = map.GetLength(1); start = new Node((int)startCell.coordinates.x, (int)startCell.coordinates.y, 0, 0, 0, null, startCell); end = new Node((int)goalCell.coordinates.x, (int)goalCell.coordinates.y, 0, 0, 0, null, goalCell); openList.Add(start); bool keepSearching = true; bool pathExists = true; while ((keepSearching) && (pathExists)) { Node currentNode = ExtractBestNodeFromOpenList(); if (currentNode == null) { pathExists = false; break; } closeList.Add(currentNode); if (NodeIsGoal(currentNode)) keepSearching = false; else { if (targetCellMustBeFree) FindValidFourNeighbours(currentNode); else FindValidFourNeighboursIgnoreTargetCell(currentNode); foreach (Node neighbour in neighbours) { if (FindInCloseList(neighbour) != null) continue; Node inOpenList = FindInOpenList(neighbour); if (inOpenList == null) { openList.Add (neighbour); } else { if (neighbour.G < inOpenList.G) { inOpenList.G = neighbour.G; inOpenList.F = inOpenList.G + inOpenList.H; inOpenList.parent = currentNode; } } } } } if (pathExists) { Node n = FindInCloseList(end); while (n != null) { finalPath.Add (n); n = n.parent; } } }
public MouseSolver(Cell[,] map, Cell[,]top) { this.map = map; this.top = top; w = map.GetLength(0); h = map.GetLength(1); directions = new List<Brain>(); directions.Add(new Brain(-1, 0, "4")); directions.Add(new Brain(1, 0, "6")); directions.Add(new Brain(0, -1, "8")); directions.Add(new Brain(0, 1, "2")); }
public bool Init(int level_nr, out int widht, out int height) { LevelFile level = new LevelFile(); map = level.LoadLevel(level_nr); if (map == null) { widht = 0; height = 0; return false; } widht = w = map.GetLength(0); height = h= map.GetLength(1); top = new Cell[widht, height]; for (int x = 0; x < w; x++) for (int y = 0; y < h; y++) { switch(map[x,y]) { case Cell.user: mouse = new Place(x, y); map[x, y] = Cell.none; top[x, y] = Cell.user; break; case Cell.none: case Cell.wall: case Cell.here: top[x, y] = Cell.none; break; case Cell.abox: top[x, y] = Cell.abox; map[x, y] = Cell.none; break; case Cell.done: top[x, y] = Cell.abox; map[x, y] = Cell.here; break; } } return true; }
public Pathfinder(Cell start, Cell target, Cell[,] map) { this.start = start; this.target = target; this.map = map; current = start; previous = current; size = map.GetLength (0); path = new List<Cell>(); neighbours = new List<Cell>(); }
private IEnumerable <int2> GetNextAvailablePathCell() { if (Grid == null) { return(Enumerable.Empty <int2>()); } if (Path.Length == 0) { var WidthPossibilities = Enumerable.Range(0, Grid?.GetLength(0) ?? 0); var HeightPossibilities = Enumerable.Range(0, Grid?.GetLength(1) ?? 0); var AllPossibilities = from x in WidthPossibilities from y in HeightPossibilities select new int2(x, y); return(AllPossibilities); } int2 Previous = Path[Path.Length - 1]; List <int2> Candidates = new List <int2>() { Previous + new int2(0, 1), Previous + new int2(0, -1), Previous + new int2(1, 0), Previous + new int2(-1, 0) }; Debug.Log($"Previous {Previous}"); Debug.Log($"Candiates Length: {Candidates.Count}"); var Final = Candidates.Where(x => IsValidCell(x) && !Previous.Equals(x)); Debug.Log($"Final Length: {Final.ToList().Count}"); return(Final); }
public Board() { board = new Cell[8, 8]; var counter = 0; for (var row = 0; row < board.GetLength(0); row++) { for (var column = 0; column < board.GetLength(1); column++) { if (counter % (board.GetLength(0) + 1) == 0) { counter++; } board[row, column] = new Cell(); if (counter % 2 != 0) { board[row, column].IsUsable = false; } counter++; } } }
public void Regenerate() { // Clean up Ungenerate(); // Regenerate maze maze.Regenerate(); // Make the mesh seriously like 5x the resolution of the original maze for destructivity hiResGrid = new Cell[maze.Grid.GetLength(0) * MAZE_RESOLUTION, maze.Grid.GetLength(1) * MAZE_RESOLUTION]; for (int x = 0; x < maze.Grid.GetLength(0); ++x) { for (int y = 0; y < maze.Grid.GetLength(1); ++y) { for (int ix = 0; ix < MAZE_RESOLUTION; ++ix) { for (int iy = 0; iy < MAZE_RESOLUTION; ++iy) { Cell oldCell = maze.Grid[x, y]; int newX = x * MAZE_RESOLUTION + ix; int newY = y * MAZE_RESOLUTION + iy; Cell newCell = new Cell(oldCell); newCell.position = new Point(newX, newY); hiResGrid[newX, newY] = newCell; } } } } // Store a list of empty spaces emptySpaces = new List<GridCell>(); // Copy maze to pathfinding grid int width = hiResGrid.GetLength(0); int height = hiResGrid.GetLength(1); Grid = new GridCell[width, height]; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { Grid[x, y] = new GridCell(x, y, hiResGrid[x, y].visited); if (Grid[x, y].Accessible) emptySpaces.Add(Grid[x, y]); } } // Create cell grid for pathfinding cellGrid = CellGrid; // Reset enemy pathfinding data NonplayerCharacter.ResetPathfinding(); // Get list of empty cells List<GridCell> emptyCellsCopy = new List<GridCell>(emptySpaces); // Pick random deadend for player GridCell playerSpawnCell = emptyCellsCopy[Random.Range(0, emptyCellsCopy.Count)]; // Remove this dead end from the list so that no enemies can spawn there emptyCellsCopy.Remove(playerSpawnCell); // Spawn the player there Vector3 playerPos = cellGrid.GetCellPos(playerSpawnCell); playerPos.z = 0; GameObject playerObj = ((Component)GameObject.FindObjectOfType(typeof(PlayerCharacter))).gameObject; playerObj.transform.position = playerPos; // Create enemies and do the same enemies = new GameObject("Enemies"); for (int i = 0; i < enemyCount; ++i) { // Pick random place for enemy to spawn GridCell enemySpawnCell = emptyCellsCopy[Random.Range(0, emptyCellsCopy.Count)]; Vector3 enemyPos = cellGrid.GetCellPos(enemySpawnCell); enemyPos.z = 0; GameObject enemy = (GameObject)GameObject.Instantiate(enemyPrefab, enemyPos, Quaternion.identity); enemy.GetComponent<NonplayerCharacter>().target = playerObj; enemy.transform.parent = enemies.transform; // Add a slight force to enemy so they get unstuck if they're overlapping another character enemy.rigidbody.AddForce(new Vector3(0.1f, 0.1f)); } // Spawn powerups in maze PowerupManager powerupManager = (PowerupManager)GameObject.FindObjectOfType(typeof(PowerupManager)); powerupManager.SetOpenSpaces(cellGrid, emptySpaces); powerupManager.SpawnPowerups(); // Create mesh for level mesh = MeshGenerator.GenerateMesh(hiResGrid); // Asign mesh to mesh filter GetComponent<MeshFilter>().mesh = mesh; GetComponent<MeshCollider>().sharedMesh = mesh; // Create lights on walls if (wallLightPrefab != null) { CreateLights(); } }
public void Reveal(Cell[,] cells) { if (flagged) { return; } image = Properties.Resources.laatta; revealed = true; if (bomb) { return; } switch (bombCount) { case 1: image = Properties.Resources.laatta1; break; case 2: image = Properties.Resources.laatta2; break; case 3: image = Properties.Resources.laatta3; break; case 4: image = Properties.Resources.laatta4; break; case 5: image = Properties.Resources.laatta5; break; case 6: image = Properties.Resources.laatta6; break; case 7: image = Properties.Resources.laatta7; break; case 8: image = Properties.Resources.laatta8; break; default: image = Properties.Resources.laatta; break; } if (bombCount == 0) { for (int i = -1; i < 2; i++) { if (i + x < 0 || i + x >= cells.GetLength(0)) { continue; } for (int j = -1; j < 2; j++) { if (j + y < 0 || j + y >= cells.GetLength(1)) { continue; } Cell cell = cells[x + i, y + j]; if (!cell.Revealed && !cell.IsABomb) { cell.Reveal(cells); } } } } }
public static string Serialize(this Cell[,] board) => string.Join(RowSeperator, Enumerable.Range(0, board.GetLength(1)).Select(y => string.Join(CellSeperator, Enumerable.Range(0, board.GetLength(0)).Select(x => SerializeCell(board[x, y])))));
public SudokuBoard(int[,] presets) { if ((presets.GetLength(0) > 9) || (presets.GetLength(1) > 9)) throw new Exception("Error - Sudoku board size too large"); else { board = new Cell[9,9]; rows = new List<Section>(); columns = new List<Section>(); regions = new List<Section>(); // Initialize each section for (int i = 0; i < 9; i++) { rows.Add(new Section(SectionType.ROW)); // initialize each Row columns.Add(new Section(SectionType.COLUMN)); // initalize each Column regions.Add(new Section(SectionType.REGION)); // initialize each Region } // Initalize each cell with it's preset value and whether or not it's a blank (modifiable) square for (int i = 0; i < board.GetLength(0); i++) { for (int j = 0; j < board.GetLength(1); j++) { if ((presets[i, j] > 0) && (presets[i, j] <= 9)) // if coordinate is a preset cell, set it to value and isBlank false board[i, j] = new Cell(presets[i, j], false, j, i); else // else set it to zero and isBlank true board[i, j] = new Cell(0, true, j, i); } } // Assign each row and column it's group of cells List<Cell> rowCells = new List<Cell>(); List<Cell> colCells = new List<Cell>(); for (int i = 0; i < board.GetLength(0); i++) { for (int j = 0; j < board.GetLength(1); j++) { rowCells.Add(board[i, j]); // load up all cells in row colCells.Add(board[j, i]); // load up all cells in column } rows[i].AssignCells(rowCells); // set each rows cells columns[i].AssignCells(colCells); // set each columns cells rowCells = new List<Cell>(); // generate new List after each row as to not delete from memory colCells = new List<Cell>(); // generate new List after each column as to not delete from memory } // Assign each region it's group of cells List<Cell> regCells = new List<Cell>(); int reg = 0; for (int i = 0; i < board.GetLength(0); i += 3) { for (int j = 0; j < board.GetLength(1); j += 3) { for (int k = i; k < i + 3; k++) for (int l = j; l < j + 3; l++) regCells.Add(board[k, l]); // load up all cells in region regions[reg].AssignCells(regCells); // set each regions cells ++reg; // increment counter for List of regions regCells = new List<Cell>(); // generate new List after each region as to not delete from memory } } // Assign each cell their sections int regNum = 0; for (int i = 0; i < board.GetLength(0); i++) { for (int j = 0; j < board.GetLength(1); j++) { if ((j % 3 == 0) && (j != 0)) // step over one region horizontally every 3 cells regNum++; board[i, j].SetSections(rows[i], columns[j], regions[regNum]); } if (i < 2) // bring region back to 0 regNum = 0; else if (i < 5) // bring region back to 3 regNum = 3; else if (i < 8) // bring region back to 6 regNum = 6; } } }
private static void Dfs(Cell[,] cells) { Cell maxStepsCell = new Cell(); int maxSteps = -1; int maxX = cells.GetLength(0); int maxY = cells.GetLength(1); for (int x = 0; x < maxX; x++) { for (int y = 0; y < maxY; y++) { cells[x, y] = new Cell(cells[x, y].Value) { X = x, Y = y } } } ; for (int x = 0; x < maxX; x++) { for (int y = 0; y < maxY; y++) { Cell cell = cells[x, y]; if (!cell.Visited) { VisitCell(cells, x, y); cell = cells[x, y]; } if (cell.Steps > maxSteps) { maxStepsCell = cell; maxSteps = cell.Steps; } } } int nextX = maxStepsCell.X; int nextY = maxStepsCell.Y; string coords = ""; string values = ""; while (nextX != -1 && nextY != -1) { Cell cell = cells[nextX, nextY]; if (coords.Length != 0) { coords += " -> "; values += " -> "; } coords += $"({cell.X}, {cell.Y})"; values += $"{cell.Value}"; nextX = cell.NextLongestX; nextY = cell.NextLongestY; } Console.WriteLine(coords); Console.WriteLine(values); }
public static Cell[,] spielzug(Cell[,] spielfeld, int xMax, int percent) { Starter starter = new Starter(); Cell[,] spielfeldNeu = starter.start(xMax); spielfeldNeu = starter.fill(spielfeldNeu, percent); xMax = xMax - 1; for (int x = 0; x < spielfeld.GetLength(0); x++) { for (int y = 0; y < spielfeld.GetLength(0); y++) { //Oben Links if (x == 0 && y == 0) { spielfeldNeu[0, 0].Status = Logik.topLeftCorner(spielfeld); } //Unten Rechts else if (x == xMax && y == xMax) { spielfeldNeu[x, y].Status = Logik.botRightCorner(spielfeld, x); } //Unten Links else if (x == xMax && y == 0) { spielfeldNeu[xMax, 0].Status = Logik.botLeftCorner(spielfeld, x); } // oben Rechts else if (x == 0 && y == xMax) { spielfeldNeu[0, xMax].Status = Logik.topRightCorner(spielfeld, y); } //linke Spalte else if (x != 0 && y == 0 && x != xMax) { spielfeldNeu[x, y].Status = Logik.leftColumn(spielfeld, x, y); } //rechte Spalte else if (x != 0 && y == xMax) { spielfeldNeu[x, y].Status = Logik.rightColumn(spielfeld, x, y); } //oben else if (x == 0 && y != 0 && y != xMax) { spielfeldNeu[x, y].Status = Logik.topRow(spielfeld, x, y); } //unten else if (x == xMax && y != 0) { spielfeldNeu[x, y].Status = Logik.botRow(spielfeld, x, y); } else { spielfeldNeu[x, y].Status = Logik.fullCircle(spielfeld, x, y); } } } return(spielfeldNeu); }
public void Initialize(Cell[,] cells) { Diffs = new float[cells.GetLength(0), cells.GetLength(1)]; }
// Simular primeiro public void Simulate(ref Cell[,] cells) { float flow = 0; // Reseta array de modificacoes for (int x = 0; x < cells.GetLength(0); x++) { for (int y = 0; y < cells.GetLength(1); y++) { Diffs [x, y] = 0; } } // MAIN for (int x = 0; x < cells.GetLength(0); x++) { for (int y = 0; y < cells.GetLength(1); y++) { // Referencia celula e reseta flow Cell cell = cells [x, y]; cell.ResetFlowDirections(); // Valida celula if (cell.Type == CellType.Solid) { cell.Liquid = 0; continue; } if (cell.Liquid == 0) { continue; } if (cell.Settled) { continue; } if (cell.Liquid < MinValue) { cell.Liquid = 0; continue; } // Quanto liquido a celula tem desde o inicio float startValue = cell.Liquid; float remainingValue = cell.Liquid; flow = 0; // Flow para baixo if (cell.Bottom != null && cell.Bottom.Type == CellType.Blank) { // Determina velocidade do flow flow = CalculateVerticalFlowValue(cell.Liquid, cell.Bottom) - cell.Bottom.Liquid; if (cell.Bottom.Liquid > 0 && flow > MinFlow) { flow *= FlowSpeed; } // Restringe o flow flow = Mathf.Max(flow, 0); if (flow > Mathf.Min(MaxFlow, cell.Liquid)) { flow = Mathf.Min(MaxFlow, cell.Liquid); } // Update dos temps if (flow != 0) { remainingValue -= flow; Diffs [x, y] -= flow; Diffs [x, y + 1] += flow; cell.FlowDirections[(int)FlowDirection.Bottom] = true; cell.Bottom.Settled = false; } } // Checa se ainda tem liquido na celula if (remainingValue < MinValue) { Diffs [x, y] -= remainingValue; continue; } // Flow pra esquerda if (cell.Left != null && cell.Left.Type == CellType.Blank) { // Calcula velocidade do flow flow = (remainingValue - cell.Left.Liquid) / 4f; if (flow > MinFlow) { flow *= FlowSpeed; } // Restringe flow flow = Mathf.Max(flow, 0); if (flow > Mathf.Min(MaxFlow, remainingValue)) { flow = Mathf.Min(MaxFlow, remainingValue); } // Update dos temps if (flow != 0) { remainingValue -= flow; Diffs [x, y] -= flow; Diffs [x - 1, y] += flow; cell.FlowDirections[(int)FlowDirection.Left] = true; cell.Left.Settled = false; } } // Checa se ainda tem liquido na celula if (remainingValue < MinValue) { Diffs [x, y] -= remainingValue; continue; } // Flow pra direita if (cell.Right != null && cell.Right.Type == CellType.Blank) { // Calcula velocidade do flow flow = (remainingValue - cell.Right.Liquid) / 3f; if (flow > MinFlow) { flow *= FlowSpeed; } // Restringe flow flow = Mathf.Max(flow, 0); if (flow > Mathf.Min(MaxFlow, remainingValue)) { flow = Mathf.Min(MaxFlow, remainingValue); } // Update dos temps if (flow != 0) { remainingValue -= flow; Diffs [x, y] -= flow; Diffs [x + 1, y] += flow; cell.FlowDirections[(int)FlowDirection.Right] = true; cell.Right.Settled = false; } } // Checa se ainda tem liquido na celula if (remainingValue < MinValue) { Diffs [x, y] -= remainingValue; continue; } // Flow pra cima if (cell.Top != null && cell.Top.Type == CellType.Blank) { // Calcula velocidade do flow flow = remainingValue - CalculateVerticalFlowValue(remainingValue, cell.Top); if (flow > MinFlow) { flow *= FlowSpeed; } // Restringe flow flow = Mathf.Max(flow, 0); if (flow > Mathf.Min(MaxFlow, remainingValue)) { flow = Mathf.Min(MaxFlow, remainingValue); } // Update dos temps if (flow != 0) { remainingValue -= flow; Diffs [x, y] -= flow; Diffs [x, y - 1] += flow; cell.FlowDirections[(int)FlowDirection.Top] = true; cell.Top.Settled = false; } } // Checa se ainda tem liquido na celula if (remainingValue < MinValue) { Diffs [x, y] -= remainingValue; continue; } // Checa se acabou o flow if (startValue == remainingValue) { cell.SettleCount++; if (cell.SettleCount >= 10) { cell.ResetFlowDirections(); cell.Settled = true; } } else { cell.UnsettleNeighbors(); } } } // Update dos valores da celula for (int x = 0; x < cells.GetLength(0); x++) { for (int y = 0; y < cells.GetLength(1); y++) { cells [x, y].Liquid += Diffs [x, y]; if (cells [x, y].Liquid < MinValue) { cells [x, y].Liquid = 0; cells [x, y].Settled = false; //celula default para inicio } } } }
public void Generate() // This method Create the world each turn. { /// The method generate the world, it has two parts: /// 1. When the world is empty (else part). /// 2. When the world has been created (if part) the method will call other methods to make the necessary changes. if (cells != null) // [2] { ChangeLadybirds(); ChangeGreenflies(); graphValues.Add(timeStep, new int[] { greenflies.Count, ladybirds.Count }); continu &= (ladybirds.Count != 0 && greenflies.Count != 0); // Checking if the number of greenflies or ladybirds has reached 0. } else //[1] { timeStep = 0; graphValues.Add(timeStep, new int[] { startGreenflyNums, startLadybirdNums }); cells = new Cell[length, width]; for (int i = 0; i < cells.GetLength(0); i++) { for (int j = 0; j < cells.GetLength(1); j++) { cells[i, j] = new Cell(i, j); } } // GreenFlies and Ladybirds are created randomly throughout the grid. Random rand = new Random(); for (int L = 0; L < startLadybirdNums; L++) // Creating Ladybirds. { int randX = rand.Next(0, length); int randY = rand.Next(0, width); if (CellIsEmpty(randX, randY)) { LadyBird ladyBird = new LadyBird(randX, randY); ladybirds.Add(ladyBird); cells[randX, randY].content = ladyBird.shape; } else { while (!CellIsEmpty(randX, randY)) // keep looping until en empty cell is found. { randX = rand.Next(0, length); randY = rand.Next(0, width); } LadyBird ladyBird = new LadyBird(randX, randY); ladybirds.Add(ladyBird); cells[randX, randY].content = ladyBird.shape; } } for (int G = 0; G < startGreenflyNums; G++) //Creating Greenflies. { int randX = rand.Next(0, length); int randY = rand.Next(0, width); if (CellIsEmpty(randX, randY)) { GreenFly greenfly = new GreenFly(randX, randY); greenflies.Add(greenfly); cells[randX, randY].content = greenfly.shape; } else { while (!CellIsEmpty(randX, randY)) { randX = rand.Next(0, length); randY = rand.Next(0, width); } GreenFly greenfly = new GreenFly(randX, randY); greenflies.Add(greenfly); cells[randX, randY].content = greenfly.shape; } } } Information(); // Update the information. }
/// <summary> /// Get surrounding neighbours from a node /// </summary> /// <param name="n"></param> /// <param name="grid"></param> /// <returns>List of neighbour nodes</returns> private List <Node> GetNeighbourNodes(Node n, Cell[,] grid) { Debug.Log("Check on position: " + n.position.x + " " + n.position.y); List <Node> neighbours = new List <Node>(); // Search in 3x3 block for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { // Skip orgin node && diagonal nodes since this is a maze with squares if (x == 0 && y == 0 || x == -1 && y == 1 || x == 1 && y == 1 || x == -1 && y == -1 || x == 1 && y == -1) { Debug.Log("c"); continue; } int checkX = n.position.x + x; int checkY = n.position.y + y; // Check if position is inside the grid if (checkX >= 0 && checkX < grid.GetLength(0) && checkY >= 0 && checkY < grid.GetLength(1)) { // Node is in grid // Now check if there isnt a wall blocking it bool blocked = false; //Debug.Log(checkX + " " + checkY); // grid size is wrong if (x == 0) { if (y == 1) { if ((grid[checkX, checkY].walls & Wall.DOWN) != 0) { blocked = true; } } else if (y == -1) { if ((grid[checkX, checkY].walls & Wall.UP) != 0) { blocked = true; } } } else if (y == 0) { if (x == -1) { if ((grid[checkX, checkY].walls & Wall.RIGHT) != 0) { blocked = true; } } else if (x == 1) { if ((grid[checkX, checkY].walls & Wall.LEFT) != 0) { blocked = true; } } } if (!blocked) { // Add it neighbours.Add(new Node(new Vector2Int(checkX, checkY), n, 0, 0)); } } } } return(neighbours); }
private void GenerateCell() { // Clear previous cell foreach (Transform child in environment.transform) { Destroy(child.gameObject); } // Generate new cells for (int y = 0; y < cellGrid.GetLength(1); y++) { for (int x = 0; x < cellGrid.GetLength(0); x++) { cellGrid[x, y] = new Cell(x, y, RandomizeBoolean(), environment.transform); } } }
public Board(Cell[,] table) { this.Table = table; neighboursCounter = new int[table.GetLength(0), table.GetLength(1)]; }
// return a matrice of float to generate the Unity Terrain heights public float[,] GetHeights() { float[,] res = new float[cells.GetLength(0), cells.GetLength(1)]; for (int i = 0; i < res.GetLength(0); i++) { for (int j = 0; j < res.GetLength(1); j++) { res [i, j] = cells [i, j].Height; } } return(res); }
private void Create_Field() { Num_Cells_H = Convert.ToInt32(cb_n.SelectedItem); Num_Cells_V = Convert.ToInt32(cb_m.SelectedItem); Field_Cells = new Cell[Num_Cells_H ,Num_Cells_V]; WayGuards = new List<List<int>>(); f_way_g = true; if (Num_Cells_V > Num_Cells_H) { Height_Cell = 400 / Num_Cells_V; } else { Height_Cell = 400 / Num_Cells_H; } Size s_Cell = new Size(Height_Cell, Height_Cell); Point Cell_Point = new Point(Control_Point.X, Control_Point.Y); //dataGridView1. for (int i = 0; i < Field_Cells.GetLength(0); i++ ) for (int j = 0; j < Field_Cells.GetLength(1); j++ ) { Cell_Point.X = i*Height_Cell + Control_Point.X; Cell_Point.Y = j*Height_Cell + Control_Point.Y; Field_Cells[i, j].Location = new Rectangle(Cell_Point, s_Cell); Field_Cells[i, j].Obj = 0; } Invalidate(); }
public static void GetPawnMoves(this Cell[,] board, Piece piece) { int loopCount = piece.MoveCount == 0 ? 3 : 2; if (ExternalRules.Instance.IsUnpassantAlowed()) { var previosPawnPosition = ExternalRules.Instance.TryReturnPreviosPawnPosition(); if (piece.IsWhite) { board[previosPawnPosition.x, piece.Coordinates.y + 1].AllowMove(); } else { board[previosPawnPosition.x, piece.Coordinates.y - 1].AllowMove(); } } if (piece.IsWhite) { // up for (int i = 1; i < loopCount; i++) { if (piece.Coordinates.y + i >= board.GetLength(0)) { break; } if (board[piece.Coordinates.x, piece.Coordinates.y + i].PlacedPiece) { break; } board[piece.Coordinates.x, piece.Coordinates.y + i].AllowMove(); } // up right for (int i = 1; i < 2; i++) { if (piece.Coordinates.x + i >= board.GetLength(0) || piece.Coordinates.y + i >= board.GetLength(0)) { break; } if (board[piece.Coordinates.x + i, piece.Coordinates.y + i].PlacedPiece) { board[piece.Coordinates.x + i, piece.Coordinates.y + i].AllowMove(); } } // up lef for (int i = 1; i < 2; i++) { if (piece.Coordinates.x - i < 0 || piece.Coordinates.y + i >= board.GetLength(0)) { break; } if (board[piece.Coordinates.x - i, piece.Coordinates.y + i].PlacedPiece) { board[piece.Coordinates.x - i, piece.Coordinates.y + i].AllowMove(); } } } else { //down for (int i = 1; i < loopCount; i++) { if (piece.Coordinates.y - i < 0) { break; } if (board[piece.Coordinates.x, piece.Coordinates.y - i].PlacedPiece) { break; } board[piece.Coordinates.x, piece.Coordinates.y - i].AllowMove(); } // down right for (int i = 1; i < 2; i++) { if (piece.Coordinates.x + i >= board.GetLength(0) || piece.Coordinates.y - i < 0) { break; } if (board[piece.Coordinates.x + i, piece.Coordinates.y - i].PlacedPiece) { board[piece.Coordinates.x + i, piece.Coordinates.y - i].AllowMove(); } } // down left for (int i = 1; i < 2; i++) { if (piece.Coordinates.x - i < 0 || piece.Coordinates.y - i < 0) { break; } if (board[piece.Coordinates.x - i, piece.Coordinates.y - i].PlacedPiece) { board[piece.Coordinates.x - i, piece.Coordinates.y - i].AllowMove(); } } } }
public void Generate(ITileMap map) { _random = new MersennePrimeRandom(_params.Seed); var w = map.Width / CellSize; var h = map.Height / CellSize; _cells = new Cell[w, h]; var startLoc = new Point { X = w / 2, Y = h / 2 }; _cells[startLoc.X, startLoc.Y] = Cell.FourWayRoom(); if (_params.Exits) { _cells[startLoc.X, startLoc.Y].Attributes = AttributeType.Entry; } var unprocessed = new Queue <Point>(); unprocessed.Enqueue(startLoc); while (unprocessed.Count > 0) { var location = unprocessed.Dequeue(); var cell = _cells[location.X, location.Y]; foreach (var opening in cell.Openings.ToDirectionsArray()) { var newLocation = opening.GetLocation(location); var newCell = DetermineCellType(newLocation, opening); if (newCell.Type != CellType.None) { _cells[newLocation.X, newLocation.Y] = ApplyAttributes(newCell); unprocessed.Enqueue(newLocation); } } } var secondExitPlaced = !_params.Exits; var chance = 10; for (var x = 0; x < _cells.GetLength(0); x++) { for (var y = 0; y < _cells.GetLength(1); y++) { var cell = _cells[x, y]; if (!secondExitPlaced) { var spawnExit = _random.Chance(chance); if (cell.Type != CellType.None && ((x <= w * 0.15) || (x >= w * 0.65)) && spawnExit) { cell.Attributes = AttributeType.Exit; secondExitPlaced = true; } else if (!spawnExit) { chance += (int)(chance * 0.25f); } } cell.Fill(x, y, map, _params); } } }
public static void GetHorseMoves(this Cell[,] board, Piece piece) { // up for (int i = 1; i < 3; i++) { if (piece.Coordinates.y + 2 >= board.GetLength(0)) { break; } if (piece.Coordinates.x + 1 < board.GetLength(0)) { board[piece.Coordinates.x + 1, piece.Coordinates.y + 2].AllowMove(); } if (piece.Coordinates.x - 1 >= 0) { board[piece.Coordinates.x - 1, piece.Coordinates.y + 2].AllowMove(); } } // down for (int i = 1; i < 3; i++) { if (piece.Coordinates.y - 2 < 0) { break; } if (piece.Coordinates.x + 1 < board.GetLength(0)) { board[piece.Coordinates.x + 1, piece.Coordinates.y - 2].AllowMove(); } if (piece.Coordinates.x - 1 >= 0) { board[piece.Coordinates.x - 1, piece.Coordinates.y - 2].AllowMove(); } } // rigth for (int i = 1; i < 3; i++) { if (piece.Coordinates.x + 2 >= board.GetLength(0)) { break; } if (piece.Coordinates.y + 1 < board.GetLength(0)) { board[piece.Coordinates.x + 2, piece.Coordinates.y + 1].AllowMove(); } if (piece.Coordinates.y - 1 >= 0) { board[piece.Coordinates.x + 2, piece.Coordinates.y - 1].AllowMove(); } } // left for (int i = 1; i < 3; i++) { if (piece.Coordinates.x - 2 < 0) { break; } if (piece.Coordinates.y + 1 < board.GetLength(0)) { board[piece.Coordinates.x - 2, piece.Coordinates.y + 1].AllowMove(); } if (piece.Coordinates.y - 1 >= 0) { board[piece.Coordinates.x - 2, piece.Coordinates.y - 1].AllowMove(); } } }
public List <Vector2Int> FindPathToTarget(Vector2Int startPos, Vector2Int endPos, Cell[,] grid) { /* * convert cells to Node * calculate positions from start to end position * use node to save calculated values which must include G and H score * * first conver cells to nodes * give H score * go through A* * calculate G * calculate F * return path * */ List <Node> OpenSet = new List <Node>(); //has to be filled OpenSet = CreateOpenList(grid, startPos, endPos); HashSet <Node> ClosedSet = new HashSet <Node>(); //final path width = grid.GetLength(0); height = grid.GetLength(1); Grid = grid; Node StartNode = new Node(startPos, null, 0, 0); Node EndNode = new Node(endPos, null, 0, 0); //change 0,0 to G and H foreach (Node item in OpenSet) //set start node and end node { if (item.position == startPos) { StartNode = item; StartNode.GScore = 0; } if (item.position == endPos) { EndNode = item; EndNode.HScore = 0; } } ClosedSet.Add(StartNode); while (OpenSet.Count > 0) //loop through all nodes in the open set { Node current = OpenSet[0]; for (int i = 1; i < OpenSet.Count; i++) { if (OpenSet[i].FScore < current.FScore || (OpenSet[i].FScore == current.FScore && OpenSet[i].HScore < current.HScore)) //find the lowest F cost using Current and index { current = OpenSet[i]; //lowest F cost found } } OpenSet.Remove(current); ClosedSet.Add(current); if (current.position == endPos) //found end node { return(RetracePath(StartNode, EndNode)); } var neighbours = OpenSet.Where(n => (n.position.x == current.position.x - 1 && n.position.y == current.position.y && !grid[current.position.x, current.position.y].HasWall(Wall.RIGHT)) || //credit to micheal smith (n.position.x == current.position.x + 1 && n.position.y == current.position.y && !grid[current.position.x, current.position.y].HasWall(Wall.LEFT)) || (n.position.x == current.position.x && n.position.y == current.position.y - 1 && !grid[current.position.x, current.position.y].HasWall(Wall.UP)) || (n.position.x == current.position.x && n.position.y == current.position.y + 1 && !grid[current.position.x, current.position.y].HasWall(Wall.DOWN))); foreach (Node node in neighbours) //credit to micheal smith { float tempGScore = current.GScore + GetDistance(current, node); if (tempGScore < node.GScore) {//the new path is shorter, update the GScore and the parent (for pathing) node.GScore = tempGScore; // node.HScore = GetDistance(node, EndNode); node.parent = current; if (!OpenSet.Contains(node)) { OpenSet.Add(node); } } } } return(null); }
public static void GetKingMoves(this Cell[,] board, Piece piece) { // up right for (int i = 1; i < 2; i++) { if (piece.Coordinates.x + i >= board.GetLength(0) || piece.Coordinates.y + i >= board.GetLength(0)) { break; } board[piece.Coordinates.x + i, piece.Coordinates.y + i].AllowMove(); if (board[piece.Coordinates.x + i, piece.Coordinates.y + i].PlacedPiece) { break; } } // down left for (int i = 1; i < 2; i++) { if (piece.Coordinates.x - i < 0 || piece.Coordinates.y - i < 0) { break; } board[piece.Coordinates.x - i, piece.Coordinates.y - i].AllowMove(); if (board[piece.Coordinates.x - i, piece.Coordinates.y - i].PlacedPiece) { break; } } // down right for (int i = 1; i < 2; i++) { if (piece.Coordinates.x + i >= board.GetLength(0) || piece.Coordinates.y - i < 0) { break; } board[piece.Coordinates.x + i, piece.Coordinates.y - i].AllowMove(); if (board[piece.Coordinates.x + i, piece.Coordinates.y - i].PlacedPiece) { break; } } // up lef for (int i = 1; i < 2; i++) { if (piece.Coordinates.x - i < 0 || piece.Coordinates.y + i >= board.GetLength(0)) { break; } board[piece.Coordinates.x - i, piece.Coordinates.y + i].AllowMove(); if (board[piece.Coordinates.x - i, piece.Coordinates.y + i].PlacedPiece) { break; } } // rigjt for (int i = 1; i < 2; i++) { if (piece.Coordinates.x + i >= board.GetLength(0)) { break; } board[piece.Coordinates.x + i, piece.Coordinates.y].AllowMove(); if (board[piece.Coordinates.x + i, piece.Coordinates.y].PlacedPiece) { break; } } // left for (int i = 1; i < 2; i++) { if (piece.Coordinates.x - i < 0) { break; } board[piece.Coordinates.x - i, piece.Coordinates.y].AllowMove(); if (board[piece.Coordinates.x - i, piece.Coordinates.y].PlacedPiece) { break; } } // up for (int i = 1; i < 2; i++) { if (piece.Coordinates.y + i >= board.GetLength(0)) { break; } board[piece.Coordinates.x, piece.Coordinates.y + i].AllowMove(); if (board[piece.Coordinates.x, piece.Coordinates.y + i].PlacedPiece) { break; } } // down for (int i = 1; i < 2; i++) { if (piece.Coordinates.y - i < 0) { break; } board[piece.Coordinates.x, piece.Coordinates.y - i].AllowMove(); if (board[piece.Coordinates.x, piece.Coordinates.y - i].PlacedPiece) { break; } } }
public Cell NextPosition(IMario mario) { int x = mario.X; int y = mario.Y; var m = mario.Direction; if (CheckEndCondition(x, y, m)) { return(Cell.Endgame); } if (scenario[x + 1, y].IsFloor() || scenario[x + 1, y].Type == CellType.JUMP) { if (mario.Direction == Movement.RIGHT && !scenario[x, y + 1].IsFloor()) { return(scenario[x, y + 1]); } if (mario.Direction == Movement.LEFT && !scenario[x, y - 1].IsFloor()) { return(scenario[x, y - 1]); } if (mario.Direction == Movement.JUMP && !scenario[x - 1, y].IsFloor()) { return(scenario[x - 1, y]); } if (mario.Direction == Movement.STOP && scenario[x + 1, y].Type == CellType.ELEVATOR_START) { int elevatorEnd = -1; for (int i = 0; i < scenario.GetLength(0); i++) { if (scenario[i, y].Type == CellType.ELEVATOR_END) { elevatorEnd = i; break; } } if (elevatorEnd == -1) { throw new Exception("Elevator without end"); } if (elevatorEnd < x) { mario.Direction = Movement.ELEVATOR_UP; return(scenario[x - 1, y]); } else { mario.Direction = Movement.ELEVATOR_DOWN; return(scenario[x + 1, y]); } } throw new Exception($"Mario got stuck at line {x+1}, column {y+1}"); } else if (mario.Direction == Movement.ELEVATOR_UP) { return(scenario[x - 1, y]); } else { return(scenario[x + 1, y]); } }
private void Start() { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); cells = new Cell[size.x, size.y]; for (int i = 0; i < size.x; i++) { for (int j = 0; j < size.y; j++) { GameObject tempCell = Instantiate(cellPrefab, new Vector2(i * cellDistance, j * cellDistance), Quaternion.identity); cells[i, j] = tempCell.GetComponent <Cell>(); } } for (int i = 0; i < cells.GetLength(0); i++) { for (int j = 0; j < cells.GetLength(1); j++) { if (i - 1 > -1) { cells[i, j].AddNeighbourCell(cells[i - 1, j]); if (j - 1 > -1) { cells[i, j].AddNeighbourCell(cells[i - 1, j - 1]); cells[i, j].AddNeighbourCell(cells[i, j - 1]); } if (j + 1 < cells.GetLength(1)) { cells[i, j].AddNeighbourCell(cells[i - 1, j + 1]); cells[i, j].AddNeighbourCell(cells[i, j + 1]); } } if (i + 1 < cells.GetLength(0)) { cells[i, j].AddNeighbourCell(cells[i + 1, j]); if (j - 1 > -1) { cells[i, j].AddNeighbourCell(cells[i + 1, j - 1]); } if (j + 1 < cells.GetLength(1)) { cells[i, j].AddNeighbourCell(cells[i + 1, j + 1]); } } } } cellsToKill = new List <Cell>(); cellsToTouch = new List <Cell>(); camera.transform.position = new Vector2((size.x * cellDistance) / 2, (size.y * cellDistance) / 2); speed = 1; PrintHint(); sw.Stop(); Debug.Log($"created in {sw.ElapsedMilliseconds} ms"); }
public Cell CellFromWorldPosSearch(Vector3 worldPos) { Cell c = null; Vector3 position = worldPos; int tries = 3; bool validCell = false; while (!validCell) { float xpos = position.x; float zpos = position.z; int z = 0; int x = 0; //search for the cell with the same z position. int t = 0; int b = grid.GetLength(0) - 1; //round up the z component of the world position so it matches with the Vector3 float approximatedUp = zpos + cellSize; float approximatedDown = zpos - cellSize; while (t <= b) { int m = (int)Mathf.Floor((t + b) / 2); if (grid[m, 0].worldPosition.z >= approximatedDown && grid[m, 0].worldPosition.z <= approximatedUp) { z = m; break; } if (grid[m, 0].worldPosition.z > zpos) { t = m + 1; } else { b = m - 1; } } //now, search for the cell with the same x position. int l = 0; int r = grid.GetLength(1) - 1; //round up the z component of the world position so it matches with the Vector3 approximatedUp = xpos + cellSize; approximatedDown = xpos - cellSize; while (l <= r) { int m = (int)Mathf.Floor((l + r) / 2); if (grid[z, m].worldPosition.x >= approximatedDown && grid[z, m].worldPosition.x <= approximatedUp) { x = m; break; } if (grid[z, m].worldPosition.x < xpos) { l = m + 1; } else { r = m - 1; } } c = grid[z, x]; if (c.isWalkable) { validCell = true; } else { position = grid[z, x].worldPosition; } tries--; if (tries < 0) { break; } } return(c); }
public void RandomEnemyGenerator() { List <Vector2Int> possibleSpawns = new List <Vector2Int>(); for (int x = 0; x < maze.GetLength(0); x++) { for (int y = 0; y < maze.GetLength(1); y++) { Vector2Int currentPos = new Vector2Int(x, y); //TODO USE A VARIABLE if (IsWalkable(currentPos) && Vector2.Distance(currentPos, startTile) > minimumDistanceMobStart) { bool toCloseFromAnOther = false; for (int i = 0; i < possibleSpawns.Count; i++) { if (Vector2.Distance(currentPos, possibleSpawns[i]) < minimumDistanceBetweenMobs) { toCloseFromAnOther = true; break; } } if (!toCloseFromAnOther) { possibleSpawns.Add(currentPos); } } ; } } int nbOfEnemies = Random.Range((int)GameManager.Instance.level, (int)GameManager.Instance.level + (int)GameManager.Instance.level * 3); if (nbOfEnemies >= possibleSpawns.Count) { nbOfEnemies = possibleSpawns.Count - 1; } for (int i = 0; i < nbOfEnemies; i++) { int randIndex = Random.Range(0, possibleSpawns.Count); enemies.Add(possibleSpawns[randIndex]); possibleSpawns.RemoveAt(randIndex); } }
public bool IsValidCell(int col, int row) { return(col < _cells.GetLength(0) && col >= 0 && row < _cells.GetLength(1) && row >= 0); }
public static Cell[] GetRow(Cell[,] matrix, int rowNumber) { return(Enumerable.Range(0, matrix.GetLength(1)) .Select(x => matrix[rowNumber, x]) .ToArray()); }
public void Generate(ITileMap map) { _random = new MersennePrimeRandom(_params.Seed); var w = map.Width / CellSize; var h = map.Height / CellSize; _cells = new Cell[w, h]; var startLoc = new Point { X = w / 2, Y = h / 2 }; _cells[startLoc.X, startLoc.Y] = Cell.FourWayRoom(); if (_params.Exits) { _cells[startLoc.X, startLoc.Y].Attributes = AttributeType.Entry; } var unprocessed = new Queue<Point>(); unprocessed.Enqueue(startLoc); while (unprocessed.Count > 0) { var location = unprocessed.Dequeue(); var cell = _cells[location.X, location.Y]; foreach (var opening in cell.Openings.ToDirectionsArray()) { var newLocation = opening.GetLocation(location); var newCell = DetermineCellType(newLocation, opening); if (newCell.Type != CellType.None) { _cells[newLocation.X, newLocation.Y] = ApplyAttributes(newCell); unprocessed.Enqueue(newLocation); } } } var secondExitPlaced = !_params.Exits; var chance = 10; for (var x = 0; x < _cells.GetLength(0); x++) for (var y = 0; y < _cells.GetLength(1); y++) { var cell = _cells[x, y]; if (!secondExitPlaced) { var spawnExit = _random.Chance(chance); if (cell.Type != CellType.None && ((x <= w * 0.15) || (x >= w * 0.65)) && spawnExit) { cell.Attributes = AttributeType.Exit; secondExitPlaced = true; } else if (!spawnExit) { chance += (int)(chance * 0.25f); } } cell.Fill(x, y, map, _params); } }
public static Cell[] GetColumn(Cell[,] matrix, int columnNumber) { return(Enumerable.Range(0, matrix.GetLength(0)) .Select(x => matrix[x, columnNumber]) .ToArray()); }
private void initDrawingZone(Panel drawingZone) { _blockSize = 60; // 960/10 //(drawingZone.Width / (_params.ColumnsQty+1)); //drawingZone.Width -= (drawingZone.Width % _blockSize); // Resize the drawing zone to be a multiple of _blockSize drawingZone.Height -= 25; // Resize the drawing zone to be a multiple of _blockSize //int matrixHeight = drawingZone.Height/_blockSize; _cellMatrix = new Cell[_columnsQty, 17]; _lineNoLabel = new Label[_cellMatrix.GetLength(HEIGHT)]; for (int i = 0; i < _cellMatrix.GetLength(WIDTH); i++) { for (int j = 0; j < _cellMatrix.GetLength(HEIGHT); j++) { _cellMatrix[i, j] = new Cell(new Rectangle( (i+1) * _blockSize, drawingZone.Size.Height - _blockSize - j * _blockSize, _blockSize, _blockSize)); drawingZone.Controls.Add(_cellMatrix[i, j].Panel); } } for (int i = 0; i < _cellMatrix.GetLength(HEIGHT); i++) { _lineNoLabel[i] = new Label(); _lineNoLabel[i].Location = new Point(0, drawingZone.Size.Height - _blockSize - i * _blockSize); _lineNoLabel[i].Size = new Size(_blockSize, _blockSize); _lineNoLabel[i].BackColor = ((i+1)%5==0) ? Color.MediumPurple : Color.LightGray; _lineNoLabel[i].ForeColor = Color.Black; _lineNoLabel[i].TextAlign = ContentAlignment.MiddleCenter; _lineNoLabel[i].Text = Convert.ToString(i + 1); _lineNoLabel[i].Font = new Font("Times New Roman", 20); _lineNoLabel[i].BorderStyle = BorderStyle.FixedSingle; drawingZone.Controls.Add(_lineNoLabel[i]); } drawActiveLine(); }
/// <summary> /// TODO: Implement this function so that it returns a list of Vector2Int positions which describes a path /// Note that you will probably need to add some helper functions /// from the startPos to the endPos /// </summary> /// <param name="startPos"></param> /// <param name="endPos"></param> /// <param name="grid"></param> /// <returns></returns> public List <Vector2Int> FindPathToTarget(Vector2Int startPos, Vector2Int endPos, Cell[,] grid) { List <Node> nodeGrid = new List <Node>(); Vector2Int gridSize = new Vector2Int(grid.GetLength(0), grid.GetLength(1)); for (int x = 0; x < gridSize.x; x++) { for (int y = 0; y < gridSize.y; y++) { Vector2Int pos = new Vector2Int(x, y); nodeGrid.Add(new Node(pos, null, int.MaxValue, CalculateDistanceCost(pos, endPos))); } } Node startNode = nodeGrid.Find(cell => cell.position == startPos); startNode.GScore = 0; List <Node> closedList = new List <Node>(); while (nodeGrid.Count > 0) { Node current = GetLowestFScoreNode(nodeGrid); if (current.position == endPos) { Debug.Log("met endpos"); break; } nodeGrid.Remove(current); closedList.Add(current); List <Node> neighbours = GetNeighbours(current, grid, nodeGrid, closedList); Debug.Log(neighbours.Count); foreach (Node neighbour in neighbours) { int tentativeGScore = (int)current.GScore + CalculateDistanceCost(current.position, neighbour.position); if (tentativeGScore < neighbour.GScore) { neighbour.parent = current; neighbour.GScore = tentativeGScore; } } } Node endNode = nodeGrid.Find(cell => cell.position == endPos); if (endNode.parent == null) { return(null); } return(CalculatePath(startNode, endNode)); #region oldCode //List<Node> nodeGrid = new List<Node>(); //Vector2Int gridSize = new Vector2Int(grid.GetLength(0), grid.GetLength(1)); //for (int x = 0; x < gridSize.x; x++) //{ // for (int y = 0; y < gridSize.y; y++) // { // Vector2Int pos = new Vector2Int(x, y); // nodeGrid.Add(new Node(pos, null, int.MaxValue, CalculateDistanceCost(pos, endPos))); // } //} //Node startNode = nodeGrid.Find(cell => cell.position == startPos); //startNode.GScore = 0; //List<Node> openList = new List<Node>(); //List<Node> closedList = new List<Node>(); //openList.Add(startNode); //while (openList.Count > 0) //{ // Node current = GetLowestFScoreNode(openList); // if (current.position == endPos) // { // Debug.Log("met endpos"); // break; // } // openList.Remove(current); // closedList.Add(current); // List<Node> neighbours = GetNeighbours(current, grid, nodeGrid, closedList); // Debug.Log(neighbours.Count); // foreach (Node neighbour in neighbours) // { // int tentativeGScore = (int)current.GScore + CalculateDistanceCost(current.position, neighbour.position); // if (tentativeGScore < neighbour.GScore) // { // neighbour.parent = current; // neighbour.GScore = tentativeGScore; // if (!openList.Contains(neighbour)) // { // openList.Add(neighbour); // } // } // } //} //Node endNode = nodeGrid.Find(cell => cell.position == endPos); //if (endNode.parent == null) //{ // return null; //} //return CalculatePath(startNode, endNode); #endregion }
private void transformToInternalForm() { Cell[,] tmp = cells; cells = new Cell[width + height / 2, height]; for (int i = 0; i < cells.GetLength(0); i++) for (int j = 0; j < cells.GetLength(1); j++) cells[i, j] = new Cell(); for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) cells[i + (j + 1) / 2, j] = tmp[i, j]; width = width + (height + 1) / 2; }
void Update() { // Update grid lines and cell size if (PreviousCellSize != CellSize || PreviousLineColor != LineColor || PreviousLineWidth != LineWidth) { RefreshGrid(); } // Convert mouse position to Grid Coordinates Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); int x = (int)((pos.x - this.transform.position.x) / (CellSize + LineWidth)); int y = -(int)((pos.y - this.transform.position.y) / (CellSize + LineWidth)); // Check if we are filling or erasing walls if (Input.GetMouseButtonDown(0)) { if ((x > 0 && x < Cells.GetLength(0)) && (y > 0 && y < Cells.GetLength(1))) { if (Cells [x, y].Type == CellType.Blank) { Fill = true; } else { Fill = false; } } } // Left click draws/erases walls if (Input.GetMouseButton(0)) { //不在边界,并且防止数组越界 if (x != 0 && y != 0 && x != Width - 1 && y != Height - 1) { if ((x > 0 && x < Cells.GetLength(0)) && (y > 0 && y < Cells.GetLength(1))) { if (Fill) { Cells [x, y].SetType(CellType.Solid); } else { Cells [x, y].SetType(CellType.Blank); } } } } // Right click places liquid if (Input.GetMouseButton(1)) { if ((x > 0 && x < Cells.GetLength(0)) && (y > 0 && y < Cells.GetLength(1))) { Cells [x, y].AddLiquid(5); } } //提高每帧的模拟速度 //for (int i = 0; i < 2; i++) //{ // LiquidSimulator.Simulate(ref Cells); //} LiquidSimulator.Simulate(ref Cells); }
public void Draw(SpriteBatch spritebatch) { List <IDrawable> SortDrawables() { List <IDrawable> drawables = new List <IDrawable>(); List <Pj> pjsToInsert = new List <Pj>(); pjsToInsert.AddRange(Pjs.Values); pjsToInsert.Sort((a, b) => b.y.CompareTo(a.y)); int mazeW = maze.GetLength(1); int mazeH = maze.GetLength(0); for (int y = 0; y < mazeH; y++) { for (int i = pjsToInsert.Count - 1; i >= 0; i--) { Pj pj = pjsToInsert[i]; Cell leftCell = maze[y, (int)((pj.x - pj.hw) / Tile.Size)]; Cell rightCell = maze[y, (int)((pj.x + pj.hw) / Tile.Size)]; if (pj.y < leftCell.GetSortY() && pj.y < rightCell.GetSortY()) { drawables.Add(pj); pjsToInsert.RemoveAt(i); } } for (int x = 0; x < mazeW; x++) { drawables.Add(maze[y, x]); } } return(drawables); } spritebatch.GraphicsDevice.Clear(new Color(77f / 255, 174f / 255, 183f / 255)); spritebatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, cameraMatrix); spritebatch.Draw(pixel, new Rectangle(0, 0, maze.GetLength(1) * Tile.Size, maze.GetLength(0) * Tile.Size), new Color(182f / 255, 186f / 255, 159f / 255)); foreach (AiPj pj in aiPjs) { Pathfinder.DrawPath(spritebatch, pixel, pj.path); } foreach (IDrawable drawable in SortDrawables()) { drawable.Draw(spritebatch, cameraMatrix); } /*foreach (PathfindingNode node in nodes) * { * node.DrawNavigationPosition(spritebatch, pixel); * }*/ spritebatch.End(); }
public bool IsLegalMove(Cell tool, int startingPoint, int targetPoint) { return(!IsPlayerHasEatenTool(tool) && IsInRangeOfBoard(startingPoint, targetPoint) && IsCorrectDirection(tool, startingPoint, targetPoint) && IsAccordingToDice(tool, startingPoint, targetPoint) && IsTargetPointLegal(tool, targetPoint) && _board[_board.GetLength(0) - 1, startingPoint] == tool); }
//resets our spreadsheet completely public void reset(int _c, int _r) { _cells = new Cell[_c, _r]; _references = new Dictionary<Cell, HashSet<Cell>>(); _undos = new Stack<UndoRedoCollection>(); _redos = new Stack<UndoRedoCollection>(); for (int i = 0; i < _cells.GetLength(0); i++) { for (int j = 0; j < _cells.GetLength(1); j++) { _cells[i, j] = new SpreadSheetCell(i, j); _references.Add(_cells[i, j], new HashSet<Cell>()); _cells[i, j].PropertyChanged += SpreadSheet_PropertyChanged; } } }
private void LoadLevel() { cell = level.LoadLevel(CurrentLevel); width = cell.GetLength(0); height = cell.GetLength(1); toolTextBoxSize.Text = width.ToString() + "x" + height.ToString(); panel.Controls.Clear(); InitPicture(); LoadPicture(); CalStat(); }
/// <summary> /// Wave-function-collapse algorithm /// TODO: Could be multithreaded to increase performance /// </summary> /// <param name="cells">The grid`s cells</param> /// <param name="seed">RNG seed</param> public void GenerateLevelWFC(ref Cell[,] cells, int seed) { // Set RNG seed Random.InitState(seed); // Instantiate cells heap OrderedCells = new Heap <Cell>(cells.GetLength(0) * cells.GetLength(1)); for (int i = 0; i < cells.GetLength(0); i++) { for (int j = 0; j < cells.GetLength(1); j++) { OrderedCells.Add(cells[i, j]); } } var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.LogWarning("Start Wave-function-collapse algorithm"); // Make sure the level fits our initial constraints ApplyInitialConstraints(ref cells); // Wave-function-collapse Algorithm while (true) { //Debug.Log("Starting another iteration! Removing next module."); // Remove finished cells from heap while (OrderedCells.Count > 0) { var cell = OrderedCells.GetFirst(); if (cell.SolvedScore == 1) { OrderedCells.RemoveFirst(); } else { break; } } // Remove random module from cell if (OrderedCells.Count > 0) { var cell = OrderedCells.GetFirst(); cell.RemoveModule(cell.possibleModulesIndices[Random.Range(0, cell.possibleModulesIndices.Count)]); } else { // Finished break; } } stopwatch.Stop(); Debug.LogWarning( $"Wave-function-collapse algorithm finished in {stopwatch.Elapsed.TotalMilliseconds}ms (Seed: {seed})"); }
public void SaveLevel(int level_nr, Cell[,] cell) { string[] lines; try { lines = File.ReadAllLines(filename); } catch { return; } int curr = 0; int currentLevelNr; int width = 0; int height = 0; while (curr < lines.Length) { ReadLevelHeader(lines[curr], out currentLevelNr, out width, out height); if (level_nr == currentLevelNr) { break; } else { curr = curr + 1 + height; } } int oldLength = lines.Length; int delta = cell.GetLength(1) - height; int newLength = oldLength + delta; if (newLength > oldLength) { Array.Resize(ref lines, newLength); for (int z = newLength - 1; z > curr; z--) { lines[z] = lines[z - delta]; } } if (newLength < oldLength) { for (int z = curr; z < newLength; z++) { lines[z] = lines[z - delta]; } Array.Resize(ref lines, newLength); } int w = cell.GetLength(0); int h = cell.GetLength(1); lines[curr] = level_nr.ToString() + " " + w.ToString() + " " + h.ToString(); for (int y = 0; y < h; y++) { lines[curr + 1 + y] = ""; for (int x = 0; x < w; x++) { lines[curr + 1 + y] += CellToChar(cell[x, y]); } } try { File.WriteAllLines(filename, lines); } catch { return; } }