public override void AI_move(cell moveto) { base.AI_move(moveto); if ((Location.y == 7 && Side == Eside.HUMAN) || (Location.y == 0 && Side == Eside.AI)) { if (BaseGameCTL.Current.CheckGameState() == Egame_state.PLAYING) { if (Player == Eplayer.WHITE) { GameObject chess_piece = GameObject.Instantiate <GameObject>(Resources.Load <GameObject>("Pieces/White_Q")); BasePiece p = chess_piece.GetComponent <BasePiece>(); p.SetOriginalLocation((int)Location.x, (int)Location.y); chess_piece.transform.parent = ChessBoard.Current.Chess_Pieces.transform; p.CurrentCell.SetPieces(p); ChessBoard.Current.White_Pieces.Add(p); ChessBoard.Current.All_piece.Add(p); } else { GameObject chess_piece = GameObject.Instantiate <GameObject>(Resources.Load <GameObject>("Pieces/Black_Q")); BasePiece p = chess_piece.GetComponent <BasePiece>(); p.SetOriginalLocation((int)Location.x, (int)Location.y); chess_piece.transform.parent = ChessBoard.Current.Chess_Pieces.transform; p.CurrentCell.SetPieces(p); ChessBoard.Current.Black_Pieces.Add(p); ChessBoard.Current.All_piece.Add(p); } Destroy(gameObject); } } }
public void ShiftLeft() { if (CurrentCell.prev != null) { CurrentCell = CurrentCell.prev; } }
public void CreateGrid(int n, GameObject btn, GameObject parent) { Algorithm.Node[,] nodes = new Algorithm.Node[n, n]; cell[,] clls = new cell[n, n]; for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { nodes [y, x] = new Algorithm.Node(); nodes [y, x].y = y; nodes [y, x].x = x; GameObject go = Spawn(btn); go.GetComponent <cell> ().assiggnedNode = nodes [y, x]; clls [y, x] = go.GetComponent <cell> (); go.transform.SetParent(parent.transform, false); go.GetComponent <RectTransform> ().localPosition = new Vector3(go.GetComponent <RectTransform> ().localPosition.x + x * 100, go.GetComponent <RectTransform> ().localPosition.y - y * 100, go.GetComponent <RectTransform> ().localPosition.z); go.GetComponent <cell> ().Init(); go.GetComponent <cell> ().gm = this; } } Nodes = nodes; cells = clls; }
static cell[,] GetInput(int rows, int columns) { char ch; cell[,] grid = new cell[10, 10]; for (int row = 0; row < rows; row++) { string s = Console.ReadLine(); for (int column = 0; column < columns; column++) { ch = s[column]; if (ch == '*') { grid[row, column].type = CellType.obstacle; } else { if (ch == '.') { grid[row, column].type = CellType.empty; } } } } return grid; }
public point[] findPath(Vector3 tC) { /*float dist = Vector3.Distance(this.getCoord(),target); int disp = System.Convert.ToInt32(dist) / levelSettings.lengthOt; if(disp == 0) disp++; point[] result = new point[disp]; result[0] = new point(this.getCoord().x,this.getCoord().y); float tmpX = this.getCoord().x; float difX = tmpX - tC.x; float tmpY = this.getCoord().y; float difY = tmpY - tC.y; for(int i = 1; i<disp; i++){ result[i] = new point(tmpX+(difX/disp),tmpY+(difY/disp)); } result[disp-1] = new point(tC.x,tC.y); return result;*/ cell conv = new cell(); ArrayList t = levelSettings.aStar.algAStar(conv.toGrid(this.getCoord()),conv.toGrid(tC)); point[] result = new point[t.Count]; for(int i = 0; i<t.Count; i++){ conv = (cell)t[i]; result[i] = conv.toPoint(conv); } return result; }
/// <summary> /// If name is null or invalid, throws an InvalidNameException. /// /// Otherwise, the contents of the named cell becomes number. The method returns a /// set consisting of name plus the names of all other cells whose value depends, /// directly or indirectly, on the named cell. /// /// For example, if name is A1, B1 contains A1*2, and C1 contains B1+A1, the /// set {A1, B1, C1} is returned. /// </summary> protected override ISet <string> SetCellContents(string name, double number) { if (name == null || checkName(name) == false) { throw new InvalidNameException(); } else { cell temp = new cell(name, number); temp.value = number; HashSet <String> result = new HashSet <string>(); graph.ReplaceDependents(name, result); HashSet <String> check = new HashSet <string>(GetCellsToRecalculate(name)); dictionary[name] = temp; //result.Add(name); //dictionary[name].value = number; foreach (String token in GetCellsToRecalculate(name)) { if (dictionary.ContainsKey(token)) { try { dictionary[token].value = calculate(token); } catch { dictionary[token].value = new FormulaError(); } } } Changed = true; return(check); } }
//using chebyshev distance heuristic public float CalculateHeuristic(cell from, cell to) { float xdif = (Math.Abs(to.m_x - from.m_x)); float ydif = (Math.Abs(to.m_y - from.m_y)); return(Math.Max(xdif, ydif)); }
void Awake() { pName = PlayerPrefs.GetString("Name", "Player"); playerCoins = 0; Instance = this; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { blocks[i, j] = new cell(); blocks[i, j].x = i; blocks[i, j].y = j; } } for (int i = 1; i < height - 1; i++) { for (int j = 1; j < width - 1; j++) { if ((i % 2 != 0 && j % 2 != 0) && //если ячейка нечетная по x и y, (i < height - 1 && j < width - 1)) //и при этом находится в пределах стен лабиринта { blocks[i, j].isWall = false; //то это КЛЕТКА } else { blocks[i, j].isWall = true; //в остальных случаях это СТЕНА. } } } ChangeBox(); Checker(); SpawnMass(); StartCoroutine(SpawnCoin()); }
public static bool CheckCellIsRight(List <cell> cells, cell cel) { bool right = false; bool righth = false; bool rightb = false; List <cell> lists = cells.FindAll(x => x.horizontal == cel.horizontal && x.solution == cel.solution); if (lists.Count == 1) { right = true; //Debug.Log("H:" + lists.Count + right + i); } List <cell> listsv = cells.FindAll(x => x.vertical == cel.vertical && x.solution == cel.solution); if (listsv.Count == 1) { righth = true; //Debug.Log("v:" + listsv.Count + right + i); } List <cell> listsb = cells.FindAll(x => x.box == cel.box && x.solution == cel.solution); if (listsb.Count == 1) { rightb = true; //Debug.Log("b:" + listsb.Count + right + i); } if ((right && righth && rightb)) { return(true); } return(false); }
public int GetGDist(cell from, cell to) { int xdiff = (int)(Math.Abs(to.m_x - from.m_x)); int ydiff = (int)(Math.Abs(to.m_y - from.m_y)); return(xdiff + ydiff); }
public void CreateCounter(cell input) { if (!GameIsWon) { if (GameManager.player_switch == true) { print("filled red " + input.RowValue + "/" + input.ColumnValue); input.isFilled = true; input.filledWithTeam = 1; cn.team = 1; Instantiate(cn, input.transform.position, Quaternion.identity); GameManager.player_switch = false; } else if (GameManager.player_switch == false) { print("filled blue " + input.RowValue + "/" + input.ColumnValue); input.isFilled = true; input.filledWithTeam = 2; cn.team = 2; Instantiate(cn, input.transform.position, Quaternion.identity); GameManager.player_switch = true; } } }
/// <summary> /// If name is null or invalid, throws an InvalidNameException. /// Otherwise, returns the contents (as opposed to the value) of the named cell. The return /// value should be either a string, a double, or a Formula. public override object GetCellContents(string name) { //if the name is valid gets the cell and returns its contents //this method also throws exceptions isValidName(name); name = Normalize(name); //if named cell is present gets it contents if (dictionary.ContainsKey(name)) { cell cell = new cell(); dictionary.TryGetValue(name, out cell); double doubleCheck; //for double content if (cell.getContent().GetType() == typeof(Double)) { return(cell.getContent()); } //for formula content bool isFormula = cell.getContent().GetType() == typeof(Formula); if (isFormula) { Formula f = (Formula)cell.getContent(); return(f); } //for string content bool isString = cell.getContent().GetType() == typeof(String); if (isString) { return((String)cell.getContent()); } } //for empty cell return(""); }
public void FloodFill(cell[,] matrix, cell source, cell dest) { var r = matrix.GetLength(0); var l = matrix.GetLength(1); var visited = new Boolean[9, 9]; Queue <cell> q = new Queue <cell>(); q.enqueue(source); visited[source.x, source.y] = true; while (q.length > 0) { var cur = q.dequeue(); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (IsSafe(cur.x + i, cur.y + j, matrix, visited)) { matrix[cur.x + i, cur.x + i].dist = cur.dist + 1; visited[cur.x + i, cur.x + i] = true; } } } } }
public cell(cell p, int position) { value = 0; pos = position; prev = p; next = null; }
public cell startCell() { cell myCell = new cell(); myGrid.cellValueExistsReplace(ref myCell, 2, 4); return(myCell); }
public cell(int nx,int ny) { this.x = nx; this.y = ny; parent = null; passed = false; }
private void Button_Click_10(object sender, RoutedEventArgs e) { string identifier = id.Text; transfer t = new transfer(); cell info = new cell(); int count = info.num_inmates; t.cell = cell1.Text.ToString(); t.firstname = fname.Text.ToString(); t.lastname = lname.Text.ToString(); con.Open(); SqlCommand command = con.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "update cell set num_inmates = num_inmates + 1 where cellnum = '" + cell1.Text + "'"; command.ExecuteNonQuery(); MessageBox.Show("Updated"); con.Close(); t.inmatenum = identifier; t.celltrans_add(); this.Close(); }
Vector2 findNextNode(Vector2 currentNode,cell[,] map) { int x = (int)currentNode.x; int z = (int)currentNode.y; int smallestValue = staringSmallestValue; int nextX =0, nextZ =0; nextX = 1; nextZ = 0; Vector2 nextNode = Vector2.zero; if(checkIndex(nextX + x)&& checkIndex(nextZ+ z) ) { if(map[x + nextX,z + nextZ].value < smallestValue && map[x + nextX,z + nextZ].walkable == true) { nextNode = new Vector2(x + nextX,z + nextZ); smallestValue = myCells[x + nextX,z + nextZ].value; } } nextX = -1; nextZ = 0; if(checkIndex(nextX + x)&& checkIndex(nextZ+ z) ) { if(map[x + nextX,z + nextZ].value < smallestValue && map[x + nextX,z + nextZ].walkable == true) { nextNode = new Vector2(x + nextX,z + nextZ); smallestValue = myCells[x + nextX,z + nextZ].value; } } nextX = 0; nextZ = 1; if(checkIndex(nextX + x)&& checkIndex(nextZ+ z) ) { if(map[x + nextX,z + nextZ].value < smallestValue && map[x + nextX,z + nextZ].walkable == true) { nextNode = new Vector2(x + nextX,z + nextZ); smallestValue = myCells[x + nextX,z + nextZ].value; } } nextX = 0; nextZ = -1; if(checkIndex(nextX + x)&& checkIndex(nextZ+ z) ) { if(map[x + nextX,z + nextZ].value < smallestValue && map[x + nextX,z + nextZ].walkable == true) { nextNode = new Vector2(x + nextX,z + nextZ); smallestValue = myCells[x + nextX,z + nextZ].value; } } return nextNode; }
public void initCells() //to init cell { for (int j = 0; j < 3; j++) { buffers[j] = new cell(); } }
private void Finds(int rowStart, int colStart, int rev = 1) { string find_str = SearchStripTextBox.Text.Trim(); if (find_str.Length == 0) { MessageBox.Show("Nothing found."); return; } cell findPosition = new cell(); findPosition.col = -1; if (rev == -1 && rowStart == 0) { rowStart = dgvMessage.RowCount - 1; } for (int row = rowStart; row < dgvMessage.RowCount; row += rev) { if (row < 0) { break; } for (int col = colStart; col < dgvMessage.ColumnCount; col++) { if (dgvMessage.Rows[row].Cells[col].Value == null) { continue; } string value = dgvMessage.Rows[row].Cells[col].Value.ToString(); if (value.IndexOf(find_str, 0, StringComparison.OrdinalIgnoreCase) != -1) { findPosition.row = row; findPosition.col = col; break; } } if (findPosition.col != 0) { break; } colStart = 0; } if (findPosition.col != 0) { dgvMessage.FirstDisplayedScrollingRowIndex = (findPosition.row <= 5) ? findPosition.row : findPosition.row - 5; dgvMessage.Rows[findPosition.row].Cells[findPosition.col].Selected = true; } if (findPosition.col == -1) { System.Media.SystemSounds.Exclamation.Play(); } else { SelectLine = findPosition; } }
//Called on button press //Creates the grid, runs the maze generation algorithm, //braids the maze and initialises walls public void RunGeneration() { if (CellPrefab != null && WallPrefab != null) { //initialise cells mCells = new List <cell> (); for (int jj = 0; jj < Height; jj++) { for (int ii = 0; ii < Width; ii++) { GameObject obj = Instantiate(CellPrefab, transform.position, Quaternion.identity, this.transform); cell cCell = obj.GetComponent <cell> (); cCell.Initialise(Size, ii, jj, Width, Height); mCells.Add(cCell); } } //Run chosen algorithm - switch statement switch (Algorithm) { case SelectAlgorithm.None: break; case SelectAlgorithm.RecursiveBacktracker: recursiveBacktracker(); break; case SelectAlgorithm.Prims: primsAlgorithm(); break; case SelectAlgorithm.Kuskals: kruskalsAlgorithm(); break; default: this.ClearMaze(); return; } //Remove deadends (if applicable) braid(); //Create walls mWalls = new List <GameObject> (); foreach (cell cCell in mCells) { if (cCell != null) { List <GameObject> walls = cCell.CreateWalls(WallPrefab); foreach (GameObject wall in walls) { mWalls.Add(wall); } } } } }
/// <summary> /// If name is null or invalid, throws an InvalidNameException. /// /// Otherwise, returns the value (as opposed to the contents) of the named cell. The return /// value should be either a string, a double, or a SpreadsheetUtilities.FormulaError. /// </summary> public override object GetCellValue(string name) { //if the name is valid gets the cell and returns its value isValidName(name); if (dictionary.ContainsKey(name)) { cell cell = new cell(); dictionary.TryGetValue(name, out cell); double doubleCheck; //gets double value and returns it if (double.TryParse(cell.getContent().ToString(), out doubleCheck)) { return(doubleCheck); } //gets evaluates formaule and returns is calculated value and returns it bool isFormula = cell.getContent().GetType() == typeof(Formula); if (isFormula) { Formula f = (Formula)cell.getContent(); return(f.Evaluate(lookup)); } //returns string value of cell bool isString = cell.getContent().GetType() == typeof(String); if (isString) { return((String)cell.getContent()); } } //if cell is empty return(""); }
static cell[,] GetInput(int rows, int columns) { char ch; cell[,] grid = new cell[10, 10]; for (int row = 0; row < rows; row++) { string s = Console.ReadLine(); for (int column = 0; column < columns; column++) { ch = s[column]; if (ch == '*') { grid[row, column].type = CellType.obstacle; } else { if (ch == '.') { grid[row, column].type = CellType.empty; } } } } return(grid); }
public IEnumerator GenerateDungeon() { //Init dungeon = new cell[width+1,height+1]; regions = new ArrayList(); for (int pWidth = 0; pWidth <= width; pWidth++){ for (int pHeight = 0; pHeight <= height; pHeight++){ dungeon[pWidth,pHeight] = new cell(CellType.empty,new Vector2(pWidth,pHeight)); dungeon[pWidth,pHeight].walls[0] = true; dungeon[pWidth,pHeight].walls[1] = true; dungeon[pWidth,pHeight].walls[2] = true; dungeon[pWidth,pHeight].walls[3] = true; } } // Place Rooms yield return StartCoroutine (GenerateRoom()); // Place Maze yield return StartCoroutine (GenerateMaze()); // Place doors to rooms yield return StartCoroutine (OpenDoors()); // Reduce dead ends yield return StartCoroutine (ReduceDeadEnds()); Debug.Log ("DONE!"); }
public void add_cell(cell c) { while (cells_.Count <= c.row) { cells_.Add(new List <cell>()); for (int i = 0; i < columns_; ++i) { cells_.Last().Add(null); } } if (columns_ <= c.col) { foreach (var row in cells_) { while (row.Count <= c.col) { row.Add(null); } } columns_ = c.col + 1; } cells_[c.row][c.col] = c; }
//if any neighbors are valid bool hasValidNeighbor(cell curr) { cell left = new cell(curr.r, curr.c - 1); if (isValidNeighbor(left)) { return(true); } cell right = new cell(curr.r, curr.c + 1); if (isValidNeighbor(right)) { return(true); } cell up = new cell(curr.r - 1, curr.c); if (isValidNeighbor(up)) { return(true); } cell down = new cell(curr.r + 1, curr.c); if (isValidNeighbor(down)) { return(true); } return(false); }
public void InitGrid(cell[,] grid) { m_gridarr = grid; m_pathfinder = new pathfinding(m_gridarr); cell target = m_gridarr[5, 9]; PathFind(target); }
//if cell is within width and height of maze, and has not been visited bool isValidNeighbor(cell neighbor) { if (neighbor.r >= 0 && neighbor.r < mazeHeight_ && neighbor.c >= 0 && neighbor.c < mazeWidth_ && maze_[neighbor.r, neighbor.c].GetComponent <MazeCell>().visited() == false) { return(true); } return(false); }
/// <summary> /// Create all cells within the Grid, based on the Grid's side lengths. /// </summary> public void CreateCells() { for (int i = 0; i < GetCapacity(); i++) { ICell cell = new cell(GetCoordinatesFromLinearPosition(i)); _solutionTracker.Grid.Cells.Add(cell); } }
public void ShiftRight() { if (CurrentCell.next == null) { CurrentCell.next = new cell(CurrentCell, CurrentCell.pos + 1); } CurrentCell = CurrentCell.next; }
// Concluding the maze in the last row by checking if any cells belong to different sets void conclude(cell[,] cells) { for (int i=0; i<S-1; i++) { if (cells [S-1, i].set.index != cells [S-1, i + 1].set.index) { merge_cells (cells [S-1, i], cells [S-1, i + 1], cells [S-1, i].r_bline, cells); } } }
static List<int> SetRightDiagonals(int rows, int columns, cell[,] grid) { int diagonalsNumber = 0; List<int> rightDiagonals = new List<int>(); for (int row = 0; row < rows; row++) { int column = 0; int tmpRow = row; bool isObstacle = true; while (tmpRow > -1) { if (grid[tmpRow, column].type == CellType.obstacle) { isObstacle = true; } else { if (isObstacle) { isObstacle = false; diagonalsNumber++; rightDiagonals.Add(diagonalsNumber - 1); } grid[tmpRow, column].rightDiagonal = diagonalsNumber - 1; } tmpRow--; column++; } } for (int column = 1; column < columns; column++) { int row = rows - 1; int tmpColumn = column; bool isObstacle = true; while (tmpColumn < columns) { if (grid[row, tmpColumn].type == CellType.obstacle) { isObstacle = true; } else { if (isObstacle) { isObstacle = false; diagonalsNumber++; rightDiagonals.Add(diagonalsNumber - 1); } grid[row, tmpColumn].rightDiagonal = diagonalsNumber - 1; } tmpColumn++; row--; } } return rightDiagonals; }
public Vector3 startPosition() { cell myCell = new cell(); myGrid.cellValueExistsReplace(ref myCell, 1, 2); Vector3 myPos = new Vector3(myCell.x * voxel.transform.localScale.x, myCell.y * voxel.transform.localScale.y, myCell.z * voxel.transform.localScale.z); return(myPos); }
private void test_draw_MouseDown(object sender, MouseEventArgs e) { if (selected_cell != null) { movine_cell = selected_cell; movine_offset_x = movine_cell.start_point.X - e.X; movine_offset_y = movine_cell.start_point.Y - e.Y; } }
public cell(Vector3 c) { cell conc = new cell(); conc = conc.toGrid(c); this.x = conc.x; this.y = conc.y; parent = null; passed = false; }
/// <summary> /// Writes the contents of this spreadsheet to the named file using an XML format. /// The XML elements should be structured as follows: /// /// <spreadsheet version="version information goes here"> /// /// <cell> /// <name> /// cell name goes here /// </name> /// <contents> /// cell contents goes here /// </contents> /// </cell> /// /// </spreadsheet> /// /// There should be one cell element for each non-empty cell in the spreadsheet. /// If the cell contains a string, it should be written as the contents. /// If the cell contains a double d, d.ToString() should be written as the contents. /// If the cell contains a Formula f, f.ToString() with "=" prepended should be written as the contents. /// /// If there are any problems opening, writing, or closing the file, the method should throw a /// SpreadsheetReadWriteException with an explanatory message. /// </summary> public override void Save(string filename) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = ("\t"); try { //Opens writer and creates a file to write too then closes file using (XmlWriter writer = XmlWriter.Create(filename, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("spreadsheet"); writer.WriteAttributeString(null, "version", null, Version); //goes through dictionary getting names and cells foreach (string name in dictionary.Keys) { cell cell = new cell(); dictionary.TryGetValue(name, out cell); //if empty cell dont write it to xml if (GetCellContents(name) == "") { continue; } writer.WriteStartElement("cell"); writer.WriteElementString("name", name); double doubleCheck; //if double sets that to contents element if (double.TryParse(GetCellContents(name).ToString(), out doubleCheck)) { writer.WriteElementString("contents", doubleCheck.ToString()); writer.WriteEndElement(); } //if formula puts that as element content else if (GetCellContents(name).ToString().ElementAt(0) == '=') { Formula f = (Formula)cell.getContent(); writer.WriteElementString("contents", "=" + f.ToString()); writer.WriteEndElement(); } //if string sets that to element content else if (GetCellContents(name).ToString().ElementAt(0) != '=') { writer.WriteElementString("contents", (String)cell.getContent()); writer.WriteEndElement(); } } //ends document writer.WriteEndDocument(); Changed = false; } } catch { throw new SpreadsheetReadWriteException("Saving file failed, file path may be incorrect"); } }
private void Loop(int value) { bool flag = false; if (value > 900) { BaseGameCTL.Current.SwitchTurn(); } foreach (BasePiece item in ChessBoard.Current.AI_Pieces) { if (item.getLegalMoves().Count == 0) { continue; } else { cell old_cell = item.CurrentCell; foreach (cell move in item.getLegalMoves().ToArray()) { BasePiece piece = move.CurrentPiece; item.Calculate_move(move); foreach (BasePiece human_item in ChessBoard.Current.HUMAN_Pieces) { if (human_item.getLegalMoves().Contains(item.CurrentCell) && item.Value > value) { flag = true; break; } } if (ChessBoard.Current.AI_King.isInCheck() || flag) { item.Return(old_cell, move, piece); flag = false; continue; } if (depth > 1) { Loop1(item, move); } else { cal(item, move); } item.Return(old_cell, move, piece); } } } if (best_piece != null) { best_piece.AI_move(best_move); } else { Loop(value + 200); } }
private void Human_cal(BasePiece item, cell move) { compare0 = heuristic.calculate(ChessBoard.Current, Eside.HUMAN, 1); if (s0 < compare0) { s0 = compare0; Human_best_piece = item; Human_best_move = move; } }
public bool Equals(cell p) { // If parameter is null return false: if ((System.Object)p == null) { return false; } // Return true if the fields match: return (this.x == p.x) && (this.y == p.y); }
private void button1_Click(object sender, EventArgs e) { //===============Image loading area=======================// buttonclick.Play(); pictureBox8.Location = new Point(690, 321); pictureBox7.Location = new Point(691, 151); if (textBox1.Enabled == true || textBox2.Enabled == true) { textBox1.Enabled = false; textBox2.Enabled = false; }; imagearray[0] = new Bitmap(Properties.Resources._1); imagearray[1] = new Bitmap(Properties.Resources._2); imagearray[2] = new Bitmap(Properties.Resources._3); imagearray[3] = new Bitmap(Properties.Resources._4); imagearray[4] = new Bitmap(Properties.Resources._5); imagearray[5] = new Bitmap(Properties.Resources._6); //---------------------Location array of Player 1------------// for (int i = 0, flag = 0, level = 0, x1 = 5, y1 = 585; i < row; i++) for (int j = 0; j < col;j++ ) { loc_arr[i, j] = new cell(x1,y1); if (flag == 0 && level == 0) { x1 += pixel_multiplier; if (x1 == 590) { flag = 1; level = 1; } } else if(flag==1 && level==1){ y1 -= pixel_multiplier; flag = 0; } else if(flag==0 && level==1){ x1 -= pixel_multiplier; if (x1 == 5) { flag = 1; level = 0; } } else if(flag==1 && level==0){ y1 -= pixel_multiplier; flag = 0; level = 0; } } // MessageBox.Show(loc_arr[8,5].x_cord +","+loc_arr[8,5].y_cord); // button1.Enabled = false; radioButton1.Enabled = true; radioButton2.Enabled = true; }
// Убирает стену между двумя ячейками (превращает в посещенную ячейку) void removeWall(cell f, cell t, ref byte[,] mazeMatrix) { // Клетки либо на одной строке if (f.x == t.x) if (f.y > t.y) mazeMatrix[f.y - 1, f.x] = 2; else mazeMatrix[f.y + 1, f.x] = 2; // Либо в одном столбце else if (f.y == t.y) if (f.x > t.x) mazeMatrix[f.y, f.x - 1] = 2; else mazeMatrix[f.y, f.x + 1] = 2; }
public void add_cell(cell c) { while (cells_.Count <= c.row) { cells_.Add(new List<cell>()); for ( int i = 0; i < columns_; ++i) cells_.Last().Add(null); } if (columns_ <= c.col) { foreach (var row in cells_) while (row.Count <= c.col) row.Add(null); columns_ = c.col + 1; } cells_[c.row][c.col] = c; }
// Возвращает массив непосещенных соседей клетки List<cell> getNeighbours(cell c, ref byte[,] mazeMatrix) { var res = new List<cell>(); int x = c.x, y = c.y; // Проверяем четыре направления (вверх, вправо, вниз, влево) if ((y - 2 > 0) && (mazeMatrix[y - 2, x] == 0)) res.Add(new cell(x, y-2)); if ((x + 2 < width) && (mazeMatrix[y, x + 2] == 0)) res.Add(new cell(x+2, y)); if ((y + 2 < height) && (mazeMatrix[y + 2, x] == 0)) res.Add(new cell(x, y+2)); if ((x - 2 > 0) && (mazeMatrix[y, x - 2] == 0)) res.Add(new cell(x-2, y)); return res; }
static void Main(String[] args) { int[,] map = new int[100, 100]; int n = int.Parse(Console.ReadLine()); List<cell> caves = new List<cell>(); for (int row = 0; row < n; row++) { string str = Console.ReadLine(); for (int column = 0; column < n; column++) { map[row, column] = int.Parse(str[column].ToString()); } // Console.ReadLine(); } for (int row = 0; row < n; row++) { for (int column = 0; column < n; column++) { if ((row != 0) && (column != 0) && (row != n - 1) && (column != n - 1)) { if ((map[row, column] > map[row - 1, column]) && (map[row, column] > map[row + 1, column]) && (map[row, column] > map[row, column + 1]) && (map[row, column] > map[row, column - 1])) { cell c = new cell(); c.col = column; c.row = row; caves.Add(c); } } } } for (int row = 0; row < n; row++) { for (int column = 0; column < n; column++) { if (!isInList(row, column, caves)) Console.Write(map[row, column]); else Console.Write("X"); } Console.WriteLine(); } }
void assign_cells(cell[,] cells, Grid g) { int cell_count = 1; // To keep a count of the no. of cells and assign them their indices accordingly for (int i=0; i<S; i++) { for (int j=0; j<S; j++, cell_count++) { cells [i, j].a_bline = g.blineH [i, j]; cells [i, j].b_bline = g.blineH [i + 1, j]; cells [i, j].l_bline = g.blineV [i, j]; cells [i, j].r_bline = g.blineV [i, j + 1]; cells [i, j].set = new set_i(cell_count); cells [i, j].cell_count = cell_count; cells [i, j].break_wall = true; is_down[cell_count-1] = new wentdown(); is_down[cell_count-1].reply = false; } } }
//sets our grid based on the maps data private void setGrid() { dungeon = GetComponent<myDungeongen> (); sizeX = dungeon.sizeX; sizeZ = dungeon.sizeZ; map = new cell[sizeX,sizeZ]; for(int z = 0; z < sizeZ; z++) { for(int x = 0; x < sizeX; x++) { if(dungeon.map[x,z].tileAlias == myDungeongen.empty || dungeon.map[x,z].tileAlias == myDungeongen.roomCenter) { map[x,z] = new cell(); //impassible as these cells are coupied by gameobjects } else { map[x,z] = new cell(true); } } } }
switch_ create_switch_at(cell cell, int ind) { Transform t = cell.a_bline.Baseline.transform;; switch_ s; s.Switch = GameObject.CreatePrimitive (PrimitiveType.Cube); Rigidbody r = s.Switch.AddComponent<Rigidbody> (); s.Switch.transform.position = t.position - t.forward * 3 + t.up * 6; s.Switch.transform.localScale = new Vector3 (1.5f, 2, .5f); r.useGravity = false; r.isKinematic = true; s.trigger = false; s.index = ind; GameObject rod = GameObject.CreatePrimitive (PrimitiveType.Cube); rod.transform.parent = s.Switch.transform; rod.transform.localPosition = -1.5f * rod.transform.up; rod.transform.localScale = new Vector3 (.25f, 3, .25f); rod.GetComponent<Renderer> ().material.color = Color.grey; GameObject button = GameObject.CreatePrimitive (PrimitiveType.Cylinder); button.transform.parent = s.Switch.transform; button.transform.localPosition = -.5f * s.Switch.transform.forward; button.transform.localScale = new Vector3 (.5f, .5f, .5f); button.transform.localRotation = Quaternion.Euler(-90, 0, 0); button.GetComponent<Renderer> ().material.color = Color.red; Light light = s.Switch.AddComponent<Light> (); light.type = LightType.Point; //light.areaSize = new Vector2 (10, 10); light.intensity = 5; light.color = Color.red; light.range = 20; s.det = new Ray(button.transform.position, new Vector3(0, 0, -1)); return s; }
//builds an array of the necicary size and returns it to whom ever called this function public cell[,] getArea(int lineOfSight,Vector3 worldCorrdinates) { int xOffset = (Mathf.RoundToInt(worldCorrdinates.x) -lineOfSight/2); //bottom left if the world corrdinates are the center int zOffset = (Mathf.RoundToInt(worldCorrdinates.z) -lineOfSight/2); cell[,] output = new cell[lineOfSight,lineOfSight]; for(int x=0; x < lineOfSight; x++) { for(int z =0; z < lineOfSight; z++) { if((x + xOffset) < sizeX && x + xOffset >= 0 && (z + zOffset) < sizeZ && z + zOffset >= 0 ) //if the element does not lie on the map do not try to check the map rather give a new cell and assume the empty space is not walkable { output[x, z] = map[x + xOffset, z + zOffset]; } else { output[x,z] = new cell(); } } } return(output); }
//ýòîò ìåòîä íàõîäèò âñå òî÷êè, ðàñïîëîæåííûå ðÿäîì ñ öåëåâîé òî÷êîé ArrayList allcellsNearX(ArrayList openset, ArrayList closedset, cell a) { ArrayList result = new ArrayList(); cell b = new cell(0,0); /*foreach(cell b in allset) { if((b.x == a.x - 1)&&(b.y == a.y + 1)){result.Add(b);} if((b.x == a.x)&&(b.y == a.y + 1)){result.Add(b);} if((b.x == a.x + 1)&&(b.y == a.y + 1)){result.Add(b);} if((b.x == a.x - 1)&&(b.y == a.y)){result.Add(b);} if((b.x == a.x + 1)&&(b.y == a.y)){result.Add(b);} if((b.x == a.x - 1)&&(b.y == a.y - 1)){result.Add(b);} if((b.x == a.x)&&(b.y == a.y - 1)){result.Add(b);} if((b.x == a.x - 1)&&(b.y == a.y - 1)){result.Add(b);} }*/ point p = a.toPoint(a); Vector3 vect = p.getCoord(); int ob = levelSettings.objectSize; cell t; t = b.toGrid(vect.x+ob,vect.y); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x+ob,vect.y+ob); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x,vect.y+ob); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x-ob,vect.y); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x-ob,vect.y-ob); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x,vect.y-ob); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x+ob,vect.y-ob); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } t = b.toGrid(vect.x-ob,vect.y+ob); if(!(isInSet(t,openset)) && !(isInSet(t,closedset))){ result.Add(t); }else{ if(isInSet(t,openset)){result.Add(openset[indexOfCell(t,openset)]);} } return result; }
bool isInSet(cell x, ArrayList rset) { foreach(cell b in rset){ if(b.x == x.x && b.y == x.y){ return true; } } return false; }
//ýòîò ìåòîä íàõîäèò òî÷êó ñ íàèìåíüøèì F â ïåðåäàííîì åìó ìàññèâå òî÷åê cell lowestF(ArrayList goal_set) { cell resultP = new cell(); int min_f = int.MaxValue; foreach(cell x in goal_set) { if(min_f>x.f) { min_f = x.f; resultP = x; } } return resultP; }
// Генерация лабиринта public void GenerateLevels (bool regenerate_current = false, byte level = 0, bool dynamically = false) { int c_x = 0, c_y = 0; if (dynamically) { circleInstance = GameObject.Find("Circle").GetComponent<Circle>(); c_x = (int)circleInstance.transform.position.x; c_y = (int)circleInstance.transform.position.y; } // Генерируем 8 уровней for (int lev = 1; lev <= 8; lev++) { if (regenerate_current) lev = level; width = height = base_sum + lev * 4; var mazeTemp = new byte[width, height]; var goodCells = new Stack<cell>(); // Стек клеток с непосещенными соседями for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if ((i % 2 != 0 && j % 2 != 0) && // Если ячейка нечетная по x и y, (i < height - 1 && j < width - 1)) // И при этом находится в пределах стен лабиринта mazeTemp[i, j] = 0; // То это пустая КЛЕТКА else mazeTemp[i, j] = 1; // Иначе это СТЕНА } } // Непосредственно генерация лабиринта методом поиска в глубину int unvisitedCells = ((width - 2) / 2 + 1) * ((height - 2) / 2 + 1); // Кол-во непосещенных ячеек var currentCell = new cell(width / 2, height / 2); // Начальная ячейка bool first = true; int rand; mazeTemp[currentCell.y, currentCell.x] = 2; // Начальная ячейка - посещенная unvisitedCells--; do { var neighbours = getNeighbours(currentCell, ref mazeTemp); // Получаем соседей текущей точки if (neighbours.Count > 0) { // Если есть соседи goodCells.Push(currentCell); // Первую ячейку выбираем верхней от центра if (first) { rand = 0; first = false; } else rand = Random.Range(0, neighbours.Count); removeWall(currentCell, neighbours[rand], ref mazeTemp); currentCell = neighbours[rand]; mazeTemp[currentCell.y, currentCell.x] = 2; unvisitedCells--; } else if (goodCells.Count > 0) { // Если нет соседей, берем ячейку из стека currentCell = goodCells.Pop(); } } while (unvisitedCells > 0); if (dynamically) { if (mazeTemp[c_y, c_x] != 1) { Levels[level - 1] = mazeTemp; circleInstance.Move(new Vector2(c_x, c_y)); return; } } else if (regenerate_current) { Levels[level - 1] = mazeTemp; return; } else Levels.Add(mazeTemp); } }
// Generate The MAZE void MazeGeneration(cell[,] cells) { int i; for (i=0; i<S-1; i++) { merge_row (i, cells); go_down (i, cells); } conclude (cells); }
//ïðèìåðíîå ðàññòîÿíèå äî öåëåâîé òî÷êè âû÷èñëÿåòñÿ êàê ìàíõýòýíñêîå ðàññòîÿíèå public float estimate_cost(cell p) { int result; result = Math.Abs(this.x-p.x)-Math.Abs(this.y-p.y); return result; }
void put_all_switches(cell[,] cells, switch_[] S_) { int[] switches = new int[4]; int i, j; switches [0] = Random.Range (1, S * S + 1); switches [1] = (switches [0] + 1449) % (S * S); switches [2] = (switches [1] + 1449) % (S * S); int[] temp = new int[4]; temp [0] = 1; temp [1] = S; temp [2] = S * S - S + 1; temp [3] = S * S; for (i=0; i<4; i++) { for (j=0; j<3; j++) { if (temp [i] == switches [j]) break; else if (j == 2) switches [3] = temp [i]; } } int r, c; for (i=0; i<4; i++) { int N = switches[i]; r = (N-1) / S; if(N % S != 0) c = N % S - 1; else c = S - 1; S_[i] = create_switch_at(cells[r, c], i); } }
// Randomly merging any sets of a given row. void merge_row(int row, cell[,] cells) { for (int i=0; i<S-1; i++) { if (Random.Range (0, Random.Range(1,3)) == 0) { merge_cells (cells [row, i], cells [row, i + 1], cells [row, i].r_bline, cells); } } }
// Function to merge any 2 cells given their line of intersection void merge_cells(cell cell1, cell cell2, bLine comm_bline, cell[,] cells) { int i1 = cell1.set.index, i2 = cell2.set.index; if (i1 > i2) merge_cells (cell2, cell1, comm_bline, cells); else { if(comm_bline.toggle.val && cell1.break_wall){ Destroy(comm_bline.Baseline); Destroy(comm_bline.wall); comm_bline.toggle.val = false; } cell2.break_wall = false; if(cell2.set.index != cell1.set.index){ cell2.set.index = i1; int N = cell2.cell_count; int i, j; i = (N-1) / S; if(N % S != 0) j = N % S - 1; else j = S - 1; if(i > 0){ if(cells[i-1, j].set.index == i2) merge_cells(cell2, cells[i-1, j], cell2.a_bline, cells); } if(j < S-1){ if(cells[i, j+1].set.index == i2) merge_cells(cell2, cells[i, j+1], cell2.r_bline, cells); } if(j > 0){ if(cells[i, j-1].set.index == i2) merge_cells(cell2, cells[i, j-1], cell2.l_bline, cells); } if(i < S-1){ if(cells[i+1, j].set.index == i2) merge_cells(cell2, cells[i+1, j], cell2.b_bline, cells); } cell2.break_wall = true; } // System.String s = string.Format("{0}, {1} : {2}", i, j, is_down[cells[i,j].set.index - 1].reply); // Debug.Log(s); } }
public cell() { parent = null; passed = false; }
int indexOfCell(cell x, ArrayList rset) { int i = 0; foreach(cell b in rset){ if(b.x == x.x && b.y == x.y){ return i; } i++; } return -1; }
// Function to randomly merge a cell from a given row with the one just below it void go_down(int row, cell[,] cells) { if (Y.reply == no) { temp = Y; N.reply = yes; Y = N; N = temp; temp = null; } else { Y.reply = true; N.reply = false; } int i; for (i=0; i<S; i++) { //if (is_down [cells [row, i].set.index - 1] == N) { if (Random.Range (0, Random.Range (3, 5)) == 0) { merge_cells (cells [row, i], cells [row + 1, i], cells [row, i].b_bline, cells); is_down [cells [row, i].set.index - 1] = Y; } //} } //Checking if any set is left without being given a downward path for (i=0; i<S; i++) { if (!is_down[cells [row, i].set.index - 1].reply) { merge_cells (cells [row, i], cells [row + 1, i], cells [row, i].b_bline, cells); is_down[cells [row, i].set.index - 1] = Y; } } Y.reply = no; }