/// <summary> /// Iterates over the players army by given type, returns the attacked unit by ID /// </summary> /// <param name="p2"></param> /// <param name="type"></param> /// <returns></returns> private ArmyUnit GetAttackedUnit(BaseCamp p2, Type type) { ArmyUnit selectedUnit = null; try { var units = p2.Army .Where(u => u.GetType() == type) .OrderByDescending(u => u.Health) .ThenByDescending(u => u.Defense) .ToList(); foreach (var unit in units) { Console.WriteLine($"Unit #{unit.Id} has {unit.Health} health, {unit.Defense} defense and {unit.Range} range"); } Console.Write("Choose a unit: "); var unitId = int.Parse(Console.ReadLine()); Console.WriteLine(); selectedUnit = units.FirstOrDefault(u => u.Id == unitId); } catch (Exception e) { ErrorLogging(e, "GetAttackedUnit"); Console.WriteLine(); Console.WriteLine("Something went wrong when choosing a unit (error 106)!"); Console.WriteLine(); this.GetAttackedUnit(p2, type); } return(selectedUnit); }
private void GainResource(BaseCamp p1, ArmyUnit armyUnit) { if (armyUnit != null && p1 != null) { p1.Resources += ( int )(armyUnit.Cost * 0.65); } }
public static HashSet <Vector3Int> GetMovePath(TerrainManager map, ArmyUnit unit) { Debug.Log(string.Format("Getting move path for map [{0}]", map.ToString())); Debug.Log(string.Format("Getting move path for unit [{0}]", unit.ToString())); HashSet <Vector3Int> viable = NeighbourPath(map, new HashSet <Vector3Int>(), unit.GetCurrentPos(), unit, unit.GetMobility()); Debug.Log(string.Format("Viable path: {0}", LogHashSet(viable))); return(viable); }
public override void Initialise(params VirtualDirectory[] db) { Dictionary <string, List <object> > land_units = new Dictionary <string, List <object> >(400); iterateDBs(land_unit => { string landUnit = land_unit["key"].Value; string range_weapon = land_unit["primary_missile_weapon"].Value; List <object> values; if (land_unit["primary_missile_weapon"].Value == "") { values = new List <object>(6); values.Add(land_unit["category"].Value); values.Add(land_unit["melee_attack"].Value); values.Add(land_unit["melee_defence"].Value); values.Add(land_unit["armour"].Value); values.Add(land_unit["charge_bonus"].Value); values.Add(land_unit["campaign_action_points"].Value); } else { values = new List <object>(10); values.Add(land_unit["category"].Value); values.Add(land_unit["melee_attack"].Value); values.Add(land_unit["melee_defence"].Value); values.Add(land_unit["armour"].Value); values.Add(land_unit["charge_bonus"].Value); values.Add(land_unit["campaign_action_points"].Value); values.Add(land_unit["primary_missile_weapon"].Value); values.Add(land_unit["accuracy"].Value); values.Add(land_unit["ammo"].Value); values.Add(land_unit["reload"].Value); } land_units[landUnit] = values; }, GameInfo.land_units_tables, db); iterateDBs(main_unit => { string key = main_unit["unit"].Value; string landUnit = main_unit["land_unit"].Value; bool isNaval = main_unit["is_naval"].Value.Equals(true.ToString()); string size = main_unit["num_men"].Value; var armyUnit = new ArmyUnit() { isNavy = isNaval, armySize = size }; armyUnit.name = (key); List <object> stats; bool found = land_units.TryGetValue(landUnit, out stats); if (found) { armyUnit.values = stats; } this[key] = armyUnit; }, GameInfo.main_units_tables, db); }
/// <summary> /// Return the selected unit with which the player wants attack /// </summary> /// <param name="p1"></param> /// <returns></returns> private ArmyUnit Ready(BaseCamp p1) { Console.WriteLine( $"Select a unit: (1){nameof( Airplane )}, (2){nameof( Artillery )}, (3){nameof( Infantry )}, (4){nameof( Tank )}"); ArmyUnit selectedUnit = null; try { var choice = int.Parse(Console.ReadKey().KeyChar.ToString()); Console.WriteLine(); switch (choice) { case 1: selectedUnit = this.GetSelectedUnit(p1, typeof(Airplane)); break; case 2: selectedUnit = this.GetSelectedUnit(p1, typeof(Artillery)); break; case 3: selectedUnit = this.GetSelectedUnit(p1, typeof(Infantry)); break; case 4: selectedUnit = this.GetSelectedUnit(p1, typeof(Tank)); break; default: Console.WriteLine("Please select one of the provided options!"); this.Ready(p1); break; } } catch (Exception e) { ErrorLogging(e, "Ready"); Console.WriteLine(); Console.WriteLine("Something went wrong when preparing the selected unit (error 107)!"); Console.WriteLine(); this.Ready(p1); } return(selectedUnit); }
// TODO: Implement this public static bool CanMoveOver(TerrainManager map, ArmyUnit unit, Vector3Int pos) { bool enemy = false; ArmyUnit nUnit = map.GetUnitAt(pos); // check if unit has stealth or other things that allow passing through if (nUnit != null && (nUnit.GetPlayer() == null || nUnit.GetPlayer().GetTeam() != unit.GetPlayer().GetTeam())) { enemy = true; } Debug.Log(string.Format("Can move over: [{0}]", enemy)); // Check if ControlZone or something else return(!enemy); }
void ClickState0(Vector3Int coord) { ArmyUnit u = map.GetUnitAt(coord); Territory t = map.GetTerritoryAt(coord); if (u != null) { // } else if (t.IsSummoningCircle()) { // you can build and if it's your turn open a menu // just open the menu menus.OpenShop(); } }
// TODO: review this fn private static bool IsZOC(TerrainManager map, ArmyUnit unit, Vector3Int pos) { bool nearbyEnemy = false; for (int i = 0; i < 6; i++) { Vector3Int n = GetNeighbour(pos, i); ArmyUnit nUnit = map.GetUnitAt(n); if (nUnit != null && (nUnit.GetPlayer() == null || nUnit.GetPlayer().GetTeam() != unit.GetPlayer().GetTeam())) { nearbyEnemy = true; } } Debug.Log(string.Format("Is ZoC: [{0}]", nearbyEnemy)); return(nearbyEnemy); }
/// <summary> /// Attack the selected enemy unit. /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="unit"></param> /// <param name="attackedUnit"></param> private void Fire(BaseCamp p1, BaseCamp p2, ArmyUnit unit, ArmyUnit attackedUnit) { try { var attackedUnitHealth = attackedUnit.Health; var damageDealt = unit.Attack(attackedUnit); int remainingDamage = 0; if (attackedUnitHealth - damageDealt < 0) { remainingDamage = Math.Abs(attackedUnitHealth - damageDealt); } Console.Write( $"{unit.GetType().Name}#{unit.Id} did {damageDealt} damage to {attackedUnit.GetType().Name}#{attackedUnit.Id}"); if (!attackedUnit.IsDead()) { Console.WriteLine($" which has {attackedUnit.Health} health left after the attack."); } else { this.GainResource(p1, attackedUnit); p2.RemoveFromArmy(attackedUnit); Console.WriteLine(" and killed it."); } if (p2.CanTakeDamage()) { Console.WriteLine($"The enemy's army numbers are dwindeling! His Base took {remainingDamage} damage!"); p2.TakeDamage(remainingDamage); } this.lastAttackingUnit = unit.Id; this.IsGameOver(); } catch (Exception e) { ErrorLogging(e, "Fire"); Console.WriteLine(); Console.WriteLine("Something went from when attacking the enemy (error 108)!"); Console.WriteLine(); this.Fire(p1, p2, unit, attackedUnit); } }
public ArmyTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, Func <ArmyUnit> getTooltipUnit) { widget.IsVisible = () => getTooltipUnit() != null; var nameLabel = widget.Get <LabelWidget>("NAME"); var descLabel = widget.Get <LabelWidget>("DESC"); var font = Game.Renderer.Fonts[nameLabel.Font]; var descFont = Game.Renderer.Fonts[descLabel.Font]; ArmyUnit lastArmyUnit = null; var descLabelPadding = descLabel.Bounds.Height; tooltipContainer.BeforeRender = () => { var armyUnit = getTooltipUnit(); if (armyUnit == null || armyUnit == lastArmyUnit) { return; } var tooltip = armyUnit.TooltipInfo; var name = tooltip?.Name ?? armyUnit.ActorInfo.Name; var buildable = armyUnit.BuildableInfo; nameLabel.Text = name; var nameSize = font.Measure(name); descLabel.Text = buildable.Description.Replace("\\n", "\n"); var descSize = descFont.Measure(descLabel.Text); descLabel.Bounds.Width = descSize.X; descLabel.Bounds.Height = descSize.Y + descLabelPadding; var leftWidth = Math.Max(nameSize.X, descSize.X); widget.Bounds.Width = leftWidth + 2 * nameLabel.Bounds.X; // Set the bottom margin to match the left margin var leftHeight = descLabel.Bounds.Bottom + descLabel.Bounds.X; widget.Bounds.Height = leftHeight; lastArmyUnit = armyUnit; }; }
/// <summary> /// Create and initialize a unit /// </summary> /// <param name="idx">Index of the unit to spawn in spawnableUnits array</param> private void SpawnUnit(int idx) { GameObject unit = Instantiate(spawnableUnits[idx].prefab); Vector3 spawnPos = spawn.position; spawnPos.z += Random.Range(-spawnZRange, spawnZRange); unit.transform.position = spawnPos; unit.transform.rotation = spawn.rotation; unit.tag = teamUnitTag; ArmyUnit script = unit.GetComponent <ArmyUnit>(); script.allyManager = this; script.enemyManager = enemyArmyManager; script.Initialize(); units.Add(script); }
void BasicSelection(Vector3Int coord) { ArmyUnit u = map.GetUnitAt(coord); Territory t = map.GetTerritoryAt(coord); if (u != null) { // Check the unit if (IsMyPlayer(u.GetPlayer())) { // } } else if (t != null) { // check for a base or do random GUI update if (t.IsSummoningCircle()) { // } } }
public async Task <IdentityResult> CreateArmy(object newArmy, int cityId) { var newArmyid = (_applicationDbContext.ArmyUnits .Select(a => a.ArmyId).DefaultIfEmpty(0).Max()) + 1; var armyUnit = new ArmyUnit { UnitId = 1, Number = 5, ArmyId = 117 }; _applicationDbContext.ArmyUnits.Add(armyUnit); var success = await _applicationDbContext.SaveChangesAsync() > 0; if (!success) { return(IdentityResult.Failed()); } return(IdentityResult.Success); }
void ClickOn(Vector3 pos) { Vector3Int coord = grid.WorldToCell(pos); Debug.Log("Click on: " + coord.ToString()); Territory t = map.GetTerritoryAt(coord); ArmyUnit u = map.GetUnitAt(coord); Player p = PlayerHandler.instance.GetCurrent(); // Probably work on states // State 1: nothing selected // Staet 2: Selected unit (waiting on move/atk) // State 3: selected ability (waiting on target) // State 4: multipoint ability (waiting on n targets) if (u != null) { // getThe Actions? Debug.Log("Found unit!"); } Dictionary <Territory.Type, int> mobMods = new Dictionary <Territory.Type, int>(); mobMods.Add(Territory.Type.PLAIN, 3); mobMods.Add(Territory.Type.FOREST, 3); mobMods.Add(Territory.Type.MOUNTAIN, 6); mobMods.Add(Territory.Type.CIRCLE, 4); // Onliy highlight path on selecting unit path.HighlightPath(coord, 1, 12, mobMods); switch (_state) { case 1: ClickState1(coord); break; case 2: ClickState2(coord); break; default: ClickState0(coord); break; } }
/// <summary> /// Return the target enemy unit by ID /// </summary> /// <param name="p2"></param> /// <param name="attacker"></param> /// <returns></returns> private ArmyUnit Aim(BaseCamp p2, string attacker) { var airplanes = p2.Army.Where(a => a.GetType() == typeof(Airplane)).ToList().Count; var artillery = p2.Army.Where(a => a.GetType() == typeof(Artillery)).ToList().Count; var infantry = p2.Army.Where(a => a.GetType() == typeof(Infantry)).ToList().Count; var tanks = p2.Army.Where(a => a.GetType() == typeof(Tank)).ToList().Count; ArmyUnit selectedUnit = null; Console.WriteLine( $"{attacker} has {airplanes} Airplanes, {artillery} Artilleries, {infantry} Infantries and {tanks} Tanks"); Console.WriteLine( $"Show more details about which unit devision: (1){nameof( Airplane )} (2){nameof( Artillery )} (3){nameof( Infantry )} (4){nameof( Tank )}"); try { var choice = int.Parse(Console.ReadKey().KeyChar.ToString()); Console.WriteLine(); switch (choice) { case 1: selectedUnit = this.GetAttackedUnit(p2, typeof(Airplane)); break; case 2: selectedUnit = this.GetAttackedUnit(p2, typeof(Artillery)); break; case 3: selectedUnit = this.GetAttackedUnit(p2, typeof(Infantry)); break; case 4: selectedUnit = this.GetAttackedUnit(p2, typeof(Tank)); break; default: Console.WriteLine("Please select one of the provided options!"); this.Aim(p2, attacker); break; } } catch (Exception e) { ErrorLogging(e, "Aim"); Console.WriteLine(); Console.WriteLine("Something went wrong when aiming the unit (error 107)!"); Console.WriteLine(); this.Aim(p2, attacker); } return(selectedUnit); }
private static HashSet <Vector3Int> PathFromNeighbours(TerrainManager map, HashSet <Vector3Int> visitedBefore, Vector3Int current, ArmyUnit unit, int mobilityLeft) { HashSet <Vector3Int> visited = visitedBefore; for (int i = 0; i < 6; i++) { Vector3Int neighbour = GetNeighbour(current, i); Territory t = map.GetTerritoryAt(neighbour); if (t != null) { // t we can move Territory.Type type = t.GetTerritoryType(); int cost = unit.TerrainCost(type); if (cost >= 0 && cost <= mobilityLeft && CanMoveOver(map, unit, current)) { visited.Add(current); visited = NeighbourPath(map, visited, neighbour, unit, mobilityLeft - cost); } } } return(visited); }
private static HashSet <Vector3Int> NeighbourPath(TerrainManager map, HashSet <Vector3Int> visitedBefore, Vector3Int current, ArmyUnit unit, int mobilityLeft) { // if (IsZOC(map, unit, current)) { // if (visitedBefore.Count > 0) { // return visitedBefore; // } else { // return PathFromNeighbours(m, visitedBefore, current, unit, mobilityLeft); // } // } else { // return PathFromNeighbours(m, visitedBefore, current, unit, mobilityLeft); // } return((IsZOC(map, unit, current) && visitedBefore.Count > 0) ? visitedBefore : PathFromNeighbours(map, visitedBefore, current, unit, mobilityLeft)); }
/// <summary> /// Возвращает новое значение для выбранного хранимого ресурса /// </summary> /// <param name="resourceName">Имя ресурса для прироста. Пример: 'EMax (См. GetResultEMax())'</param> /// <param name="resourceCurrentValue">Текущие значени для ресурса по имени resourceName </param> /// <param name="resourceValueAdded"> Добавляемое значение (прирост - источник индустриальный комплекс, мазер, юниты)</param> /// <returns></returns> private double GetNewResourceValue(string resourceName, double resourceCurrentValue, double resourceValueAdded) { //время в часах прошедшее после последнего добавления значний в базу var CurrentDate = DateTime.UtcNow; var duration = CurrentDate.Subtract(LastDate).TotalHours; string methodGetMax = "GetResult" + resourceName; Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(methodGetMax); double maxResourceValue = (double)theMethod.Invoke(this, null); var units = PlanetHelper.GetUnits(PlanetId); var unitClasses = units.Properties(); double armyBaseSumECost = 0; foreach (JProperty unitDiccionary in unitClasses) { var unitClassAlias = unitDiccionary.Name; if ("a" == unitClassAlias.Substring(0, 1)) { var unitClass = UnitHelper.GetUnitClass((string)unitClassAlias); if (unitClass != null) { var type = Type.GetType(unitClass); if (type != null) { ArmyUnit unit = (ArmyUnit)Activator.CreateInstance(type); armyBaseSumECost += unit.ArmyECoast * (int)units[unitClassAlias]; } } } } var mainCharacter = PlanetHelper.GetMainCharacter(1); var charSkillLevel = 0; double charSkillBaseValue = 0; if (null != mainCharacter) { var charSkills = mainCharacter.GetSkillLevels(); charSkillLevel = (int)charSkills["s20"]; charSkillBaseValue = mainCharacter.GetSkill("s20").GetValue(); } var armyResultSumECost = armyBaseSumECost; if (0 < charSkillLevel) { armyResultSumECost = armyBaseSumECost * (charSkillLevel * charSkillBaseValue); } double saldoResource = 0; saldoResource += resourceValueAdded; if ("EMax" == resourceName) { saldoResource -= armyResultSumECost; } double sumResourceValue = resourceCurrentValue + saldoResource * duration; double intSumResourceValue = sumResourceValue; return((intSumResourceValue < maxResourceValue) ? intSumResourceValue : maxResourceValue); }
/// <summary> /// Remove unit from internal list & destroy its gameobject /// </summary> /// <param name="unit"></param> public void KillUnit(ArmyUnit unit) { units.Remove(unit); Destroy(unit.gameObject); }
public async Task <IdentityResult> CreateCity(string cityName) { using (_applicationDbContext) { City newCity = new City { Name = cityName, Population = 1000, Pearl = 10000, Coral = 10000, Rank = 0 }; _applicationDbContext.Cities.Add(newCity); CityBuilding cityBuildingData1 = new CityBuilding { CityId = newCity.Id, BuildingId = (int)BuildingTypeEnum.Aramlasiranyito, Number = 0, RoundToFinish = 0, }; _applicationDbContext.CityBuildings.Add(cityBuildingData1); CityBuilding cityBuildingData2 = new CityBuilding { CityId = newCity.Id, BuildingId = (int)BuildingTypeEnum.Zatonyvar, Number = 0, RoundToFinish = 0, }; _applicationDbContext.CityBuildings.Add(cityBuildingData2); for (var i = 1; i <= 6; i++) { CityUpgrade cityUpgradeData = new CityUpgrade { CityId = newCity.Id, UpgradeId = i, Number = 0, RoundToFinish = 0, }; _applicationDbContext.CityUpgrades.Add(cityUpgradeData); } var newArmyid = (_applicationDbContext.Armies .Select(a => a.ArmyId).DefaultIfEmpty(0).Max()) + 1; var cityArmy = new Army { CityId = newCity.Id, ArmyId = newArmyid, EnemyCityId = null, }; _applicationDbContext.Armies.Add(cityArmy); await _applicationDbContext.SaveChangesAsync(); for (var i = 1; i <= 3; i++) { var Units = new ArmyUnit { UnitId = i, Number = 0, ArmyId = newArmyid, }; _applicationDbContext.ArmyUnits.Add(Units); } var success = await _applicationDbContext.SaveChangesAsync() > 0; if (!success) { return(IdentityResult.Failed()); } return(IdentityResult.Success); } }