/// <summary> /// Calculate the score of the current grid, adding it to the state's cumulative score /// and checking if the game is over /// </summary> /// <returns> The score of the current grid in the simulation </returns> public int CalculateScore() { // get the current grid of units in the simulation Unit[,] grid = currentState.UnitGrid; //keeps track of the board's current score int gridScore = 0; //loop through the entire grid for (int j = 0; j < grid.GetLength(GridHelper.ROW); j++) { for (int k = 0; k < grid.GetLength(GridHelper.COLUMN); k++) { //check if block is a virus or not a cell - if so, add the block's species complexity to the total if (!(grid[j, k] is Virus) && grid[j, k] != null) { //add the product of the unit's species complexity and age, or just the species complexity if they are new, to the grid score gridScore += Math.Max((grid[j, k] as LivingUnit).SpeciesComplexity * (grid[j, k] as LivingUnit).Age, (grid[j, k] as LivingUnit).SpeciesComplexity); } } } // if the current score of the board is higher than the highest recorded concurrent score, it becomes the new highest concurrent score if (gridScore > HighestConcurrentScore) { HighestConcurrentScore = gridScore; } // add the score of the board to the tracker of the current board's score CurrentScore += gridScore; return(gridScore); }
public BoardData(Unit[,] boardData) { sizeX = boardData.GetLength(0); sizeY = boardData.GetLength(1); _boardData = (Unit[, ])boardData.Clone(); }
/// <summary> /// Ввывести матрицу смежности в консоль /// </summary> public void ViewGraph() { for (int i = 0; i < Graph.GetLength(0); i++) { for (int j = 0; j < Graph.GetLength(1); j++) { ResetColor(); if (Graph[i, j].weight != int.MaxValue) { #region Подкрасить вершины в консоле; //Белый - не обнаруженна; //Желтый - обнруженна; //Зеленый - обработана; switch (Graph[i, j].status) { case 0: ForegroundColor = System.ConsoleColor.White; break; case 1: ForegroundColor = System.ConsoleColor.Yellow; break; case 2: ForegroundColor = System.ConsoleColor.Green; break; default: break; } #endregion Write($"{Graph[i, j].weight:D2} "); } else { Write($" - "); } } Write("\n"); } }
/// <summary> /// Gets the number of neighbors of the same type as this Multicellular /// in a 5x5 square centered on the organism. /// </summary> /// <param name="grid"></param> /// <returns> an integer representing the number of neighbours of the same species that this unit has </returns> protected int NumberOfSameSpeciesNeighbors(Unit[,] grid) { // Create a counter to store the number of same species neighbours int numNeighbors = 0; // Compute the boundaries of the area to check for same species neighbours int rowLowerBound = Math.Max(0, Location.r - EXTENDED_NEIGHBORHOOD_SIZE / 2), colLowerBound = Math.Max(0, Location.c - EXTENDED_NEIGHBORHOOD_SIZE / 2); int rowUpperBound = Math.Min(grid.GetLength(GridHelper.ROW), Location.r + EXTENDED_NEIGHBORHOOD_SIZE / 2 + 1), colUpperBound = Math.Min(grid.GetLength(GridHelper.COLUMN), Location.c + EXTENDED_NEIGHBORHOOD_SIZE / 2 + 1); // Loop through all rows in the area to be checked to check each grid cell for (int i = rowLowerBound; i < rowUpperBound; i++) { // Loop through all columns in the area to be checked to check each grid cell for (int j = colLowerBound; j < colUpperBound; j++) { // Check if the current grid cell is in the grid and holds a unit if (grid.InGridBounds(i, j) && grid[i, j] != null) { // Increase the number of same species neighbour in the community // only if the type of the unit in the current grid cell matches the type of the current unit numNeighbors += grid[i, j].GetType() == this.GetType() ? 1 : 0; } } } // Return the number of same species neighbours in the area surrounding this unit return(numNeighbors); }
//methods public Genetic(List <Unit> units, int size) { this.units = units; SetMaxNumber(); SetPopulation(); population.OrderPopulationByFitness(); Unit[,] us = population.Chromosomes.First().GetArray(size); int count = 0; while (!population.Chromosomes.Exists(x => x.Fitness == 0) && count < Consts.FILL_GCOUNT) { Crossover(); population.OrderPopulationByFitness(); us = population.Chromosomes.First().GetArray(size); for (int i = 0; i < us.GetLength(0); i++) { string s = ""; for (int j = 0; j < us.GetLength(1); j++) { s += us[i, j].Number; } Debug.WriteLine(s); } Debug.WriteLine(""); count++; } FillBusinessLogic.FillArray = us; }
private void GetEmptyFields(int x, int y) { if (x + 1 < FillArray.GetLength(0)) { if (!FillArray[x + 1, y].HasValue) { emptyFields.Add(FillArray[x + 1, y].Point); } } if (y + 1 < FillArray.GetLength(1)) { if (!FillArray[x, y + 1].HasValue) { emptyFields.Add(FillArray[x, y + 1].Point); } } if (x - 1 >= 0) { if (!FillArray[x - 1, y].HasValue) { emptyFields.Add(FillArray[x - 1, y].Point); } } if (y - 1 >= 0) { if (!FillArray[x, y - 1].HasValue) { emptyFields.Add(FillArray[x, y - 1].Point); } } }
//Загрузка матрицы состояния public static void Load_Matrix(Unit[,] matrix_state, Unit[,] saved_state) { for (int i = 0; i < saved_state.GetLength(0); i++) { for (int j = 0; j < saved_state.GetLength(1); j++) { matrix_state[i, j] = new Unit(saved_state[i, j].Get_Unit_Type(), saved_state[i, j].Get_Position_I(), saved_state[i, j].Get_Position_J()); } } }
public void Clear() { for (int x = 0, m = data.GetLength(0); x < m; x++) { for (int y = 0, n = data.GetLength(1); y < n; y++) { data[x, y] = null; } } }
public void Show() { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { Console.Write("{0} ", arr[i, j]); } Console.WriteLine(); } }
public static Unit getUnitOnTable(int column, int row, Unit[,] unitsTable) { if (-1 < column && column < unitsTable.GetLength(0) && -1 < row && row < unitsTable.GetLength(1)) { return(unitsTable [column, row]); } else { return(null); } }
public Computer() { for (int i = 0; i < Matrix_Com_Enemy.GetLength(0); i++) { for (int j = 0; j < Matrix_Com_Enemy.GetLength(1); j++) { Matrix_Com_Enemy[i, j] = new Unit(unit_type.sea, i, j); Matrix_Com_My[i, j] = new Unit(unit_type.sea, i, j); } } AutoAction.AutoSetShips(ref Matrix_Com_My); }
public void InitBoardSwap(Unit[,] table) { unitsTable = table; inputCtr = GetComponent <InputControl_board>(); Unit tempU = GetFirstValidUnit_onTable(table); inputCtr.createBoardBoundary(unitsTable.GetLength(0), unitsTable.GetLength(1), tempU.transform.position.z); Transform board = tempU.transform.parent; offX = board.position.x; offY = board.position.y; }
/// <summary> /// Написать рекурсивную функцию обхода графа в глубину /// </summary> static void RoundDepth(ref int[,] array, int start) { array[start, 0] += 1; array[start, 1] = 1; for (int i = 0; i < unitsGraph.GetLength(0); i++) { if (unitsGraph[start, i].weight != int.MaxValue && array[i, 1] == 0) { array[i, 0] = array[start, 0]; RoundDepth(ref array, i); } } }
private Unit FindUnitToFill(Unit[,] newFillArray) { for (int i = 0; i < newFillArray.GetLength(1); i++) { for (int j = 0; j < newFillArray.GetLength(0); j++) { if (!newFillArray[i, j].HasValue && IsThereAVariationToFillUnit(newFillArray[i, j])) { return(newFillArray[i, j]); } } } return(null); }
public override void UseBoost(Player player, Unit[,] units) { BoostRandomizeVisitor visitor = new BoostRandomizeVisitor(); for (int x = 0; x < units.GetLength(0); x++) { for (int y = 0; y < units.GetLength(1); y++) { if (units[x, y] != null) { units[x, y].Accept(visitor); } } } }
/// <summary> /// Apply the ruleset to all blocks on the grid, either creating a new unit or killing one /// </summary> public void ApplyRuleset() { //loop through grid and apply the ruleset to each block Unit[,] grid = currentState.UnitGrid; // Grid representing the new state Unit[,] newGrid = new Unit[grid.GetLength(GridHelper.ROW), grid.GetLength(GridHelper.COLUMN)]; //loop through the rows and columns of the grid, updating all blocks for (int j = 0; j < grid.GetLength(GridHelper.ROW); j++) { for (int k = 0; k < grid.GetLength(GridHelper.COLUMN); k++) { //get the new state of the block newGrid[j, k] = Ruleset.NewBlockState(grid, j, k); } } // Update the state's grid currentState.UnitGrid = newGrid; }
// Достигли ли мы конца игры public static bool IsEndGame(Unit[,] matrix_state) { bool is_end = true; // рассматриваем матрицу состояния for (int line = 0; line < matrix_state.GetLength(0); line++) { for (int column = 0; column < matrix_state.GetLength(1); column++) { // ищем в ней целые кусочки кораблей if (matrix_state[line, column].Get_Unit_Type() == unit_type.ship) { is_end = false; // если нашли - значит еще не конец игры } } } return(is_end); }
/// <summary> /// Tell every unit to update, updating multiple parameters and checking if they merge /// </summary> public void UpdateAllUnits() { //the unit grid Unit[,] grid = currentState.UnitGrid; //loop through the entire grid for (int j = 0; j < grid.GetLength(GridHelper.ROW); j++) { for (int k = 0; k < grid.GetLength(GridHelper.COLUMN); k++) { //check if there is a unit in the block being checked if (grid[j, k] != null) { //if there is, tell that unit to update grid[j, k].Update(grid, currentState.GameEnvironment); } } } }
public static void UpdateTilesGrid() { //reset all tiles for (int x = 0; x < unitsGrid.GetLength(0); x++) { for (int y = 0; y < unitsGrid.GetLength(1); y++) { if (unitsGrid[x, y] != null) { if (tilesGrid[x, y].blocked) { return; } tilesGrid[x, y].occupied = true; tilesGrid[x, y].selectable = false; } } } }
public void fall(Unit[,] units) { // print ("fall"); originalTable = units; /*List of groups of units to fall, separate by columns*/ readyToFallColumnGroups.Clear(); /*list of column indexes, should be the same length as readyToFallColumnGroups*/ skyfallColumnIndexes.Clear(); reusableUnits.Clear(); unitsTable = new Unit[originalTable.GetLength(0), originalTable.GetLength(1)]; unitsTable = convertTable(originalTable, unitsTable); groupFallingUnitsByColumn_onBoard(unitsTable); addSkyfallUnits_toFallingColumns(readyToFallColumnGroups); StartCoroutine(unitsFall()); }
/*mark inactive units on table as null, then add it to reusableUnits for later use as skyfall units*/ Unit[,] convertTable(Unit[,] fromT, Unit[,] toT) { for (int y = 0; y < fromT.GetLength(1); y++) { for (int x = 0; x < fromT.GetLength(0); x++) { if (fromT [x, y].gameObject.activeSelf) { toT [x, y] = fromT [x, y]; } else { toT [x, y] = null; reusableUnits.Add(fromT [x, y]); } } } return(toT); }
/// <summary> /// Helper method for checking whether a cordiante is within one dimension of the grid /// </summary> /// <param name="grid">The unit grid</param> /// <param name="dimension">The dimension of the grid to check</param> /// <param name="coordinate">The coordinate of the point within the given dimension</param> /// <returns> /// True if the given coordinate is within the given dimension /// False if the given coordinate is not within the given dimension</returns> public static bool InDimension(this Unit[,] grid, int dimension, int coordinate) { //check that the given dimension matches either the row or column index if (dimension != ROW && dimension != COLUMN) { //if not, return false return(false); } //ohterwise return whether the coordinate is within the size of the dimension return(coordinate < grid.GetLength(dimension) && coordinate >= 0); }
//Метод переводящий матрицу состояния кораблей в строку, для отправки на сервер public static string ParseMatric(Unit[,] state) { string parsematrix = ""; for (int i = 0; i < state.GetLength(0); i++) { for (int j = 0; j < state.GetLength(1); j++) { if (state[i, j].Get_Unit_Type() == 0) { parsematrix = parsematrix + "0"; } else { parsematrix = parsematrix + "1"; } } } return(parsematrix); }
static bool CompareBoard_withBlueprint(Unit[,] table, string[,] bp) { int column = table.GetLength(0); int row = table.GetLength(1); for (int c = 0; c < column; c++) { for (int r = 0; r < row; r++) { bool isSocket = bp[c, r] != null; bool isNotMatch_WithBlueprint = table[c, r].GetUnitID() != bp[c, r]; if (isSocket && isNotMatch_WithBlueprint) { return(false); } //otherwise means the unit on socket matches with blueprint, pass } } //if all passes, then success return(true); }
public override void UseBoost(Player player, Unit[,] units) { PlayerControlManager pcm = new PlayerControlManager(0, 0, null, null); int[] playerCenter = pcm.getCenterPlayer(new int[] { player.x, player.y }); int[] playerTile = pcm.getTile(playerCenter[0], playerCenter[1]); Teleporter t = new Teleporter(playerTile[0], playerTile[1]); TeleporterChangeVisitor visitor = new TeleporterChangeVisitor(t); for (int x = 0; x < units.GetLength(0); x++) { for (int y = 0; y < units.GetLength(1); y++) { if (units[x, y] != null) { units[x, y].Accept(visitor); } } } }
Unit GetKing(string _team, MapBoard _mcBoard, string _text) { Unit tmp_king = null; Unit[,] unit_board = _mcBoard.map_Board_Unit; for (int i = 0; i < unit_board.GetLength(0); i++) { for (int j = 0; j < unit_board.GetLength(1); j++) { if (unit_board[i, j] == null) { continue; } if (unit_board[i, j].enemy_team == _team) { continue; } if (unit_board[i, j].type == "KING") { tmp_king = unit_board[i, j]; break; } } } if (_text == "KING") { return(tmp_king); } // 自分のチームなら,そいつのターゲットを返す。なければそいつ自身を返す if (_team == this.team) { Unit tmp_unit = tmp_king.GetNearUnit(this.enemy_team); if (tmp_unit != null) { tmp_king = tmp_unit; } } return(tmp_king); }
void groupFallingUnitsByColumn_onBoard(Unit[,] unitsTable) { for (int x = 0; x < unitsTable.GetLength(0); x++) { firstEmpty = null; readyToFallUnitsInColumn = new List <Unit> (); for (int y = 0; y < unitsTable.GetLength(1); y++) { if (unitsTable [x, y] == null && !firstEmpty.HasValue) { firstEmpty = y; } else if (firstEmpty.HasValue && unitsTable [x, y] != null) { Unit fallingU = unitsTable [x, y]; /*mark Falling Unit Start and End position Coords, for animation later*/ fallingU.FallFrom = new Vector2Int(x, y); fallingU.FallTo = new Vector2Int(x, firstEmpty.Value); readyToFallUnitsInColumn.Add(fallingU); /*shift table coords*/ unitsTable [x, firstEmpty.Value] = unitsTable [x, y]; unitsTable [x, y] = null; firstEmpty++; } } /*as long as firstEmpty has value, meaning there a empty cell in the column, * if the empty cells on the very top, still add a empty list to the group, for add skyfall later*/ if (firstEmpty.HasValue) { // print (readyToFallUnitsInColumn.Count); readyToFallColumnGroups.Add(readyToFallUnitsInColumn); // print (readyToFallColumnGroups.Count + "=="); skyfallColumnIndexes.Add(x); } } }
int countEmptyCell_inColumn_onBoard(int c, Unit[,] unitsTable) { int tempN = 0; for (int y = 0; y < unitsTable.GetLength(1); y++) { if (unitsTable [c, y] == null) { tempN++; } } return(tempN); }
public Tuple <float, float> GetBonus(Unit[,] board, List <Unit> PlayersUnits) { int[,] bonusneighbourhood = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 }, //{0,0}, { 1, 1 }, { -1, 1 }, { 1, -1 }, { -1, -1 }, }; int gridSizeX = board.GetLength(0); int gridSizeY = board.GetLength(1); float currentHpBonus = 0.0f; float currentAttackBonus = 0.0f; for (int i = 0; i < bonusneighbourhood.GetLength(0); i++) { int checkX = this.x + bonusneighbourhood[i, 0]; int checkY = this.y + bonusneighbourhood[i, 1]; if (checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY) { Unit neighbour = board[checkX, checkY]; if (neighbour != null && !neighbour.IsDead() && PlayersUnits.Contains(neighbour)) { Protector prot = neighbour as Protector; if (prot != null) { currentHpBonus += prot.hpbonus * this.hp; } Warrior warr = neighbour as Warrior; if (warr != null) { currentAttackBonus += warr.attackbonus * this.attack; } } } } return(new Tuple <float, float>(currentHpBonus, currentAttackBonus)); }
/// <summary> /// Нахожденние самых коротких путей от одной вершины до всех вершин /// </summary> /// <param name="point">Начальная вершина</param> /// <returns></returns> void AllWayOnePoint(int point) { result = new int[graph.GetLength(0)]; queue = new Queue <int>(); for (int i = 0; i < graph.GetLength(0); i++) { if (graph[point, i].weight != int.MaxValue) { result[i] = graph[point, i].weight; queue.Enqueue(i); } else { result[i] = int.MaxValue; } } while (queue.Count != 0) { point = queue.Dequeue(); for (int i = 0; i < graph.GetLength(0); i++) { if (result[point] != int.MaxValue && graph[point, i].weight != int.MaxValue) { if (result[point] + graph[point, i].weight < result[i]) { result[i] = result[point] + graph[point, i].weight; queue.Enqueue(i); } } } } }