public float calculateATBIncrement(BattleState state) { if (state.getState() == BattleState.State.Idle) return (Time.deltaTime); return 0; }
public WinRenderer(BattleState battleState) : base(battleState) { whitePixelTextureData = ResourceManager.GetTextureData("white_pixel"); minScale = Game1.MinScreenScaleFactor; visibleItemCount = (int)Math.Floor(10 * minScale.Y); }
// Update is called once per frame void Update() { var nextstate = _state.Update(); if (nextstate != null) { // state transition requested _state.OnExit(); _state = nextstate; } }
public void HandleTileClick(TerrainTile tile) { var nextstate = _state.HandleTileClick(tile); if (nextstate != null) { // state transition requested _state.OnExit(); _state = nextstate; } }
public override void Resume(BattleState previousBattleState) { base.Resume(previousBattleState); if (previousBattleState is Attack || previousBattleState is UseItem) currentThinkActionFinished = true; else if (previousBattleState is HandleStatusEffects) statusEffectsCompleteForAction = true; removeDeadPartyMembers(); }
/// <summary> /// Initialize the modify event. /// </summary> /// <param name="timeline">The timeline this event is part of.</param> /// <param name="start">The start of the event.</param> /// <param name="dependentOn">An optional event to be dependent upon, ie. wait for.</param> /// <param name="character">The character who health will be modified.</param> /// <param name="state">The state to change into.</param> protected virtual void Initialize(Timeline timeline, float start, TimelineEvent dependentOn, Creature character, BattleState state) { //Call the base method. base.Initialize(timeline, start, dependentOn); //Initialize the variables. _Character = character; _ChangeState = state; }
// Use this for initialization void Start () { currentState = BattleState.START; battleGenerator = new BattleGenerator(); this.turnQueue = battleGenerator.generateBattle(); this.alliedCharacters = battleGenerator.alliedCharacters; this.enemies = battleGenerator.enemies; currentState = BattleState.START; }
public BattleScreen(String filename, EnemyEntity starter, GameScreen previous) { TransitionOnTime = TimeSpan.Zero; TransitionOffTime = TimeSpan.Zero; currentBattleState = BattleState.Starting; previousScreen = previous; creator = starter; battleFile = filename; }
void ReceiveBattleState(int state) { Debug.Log ("BattleNetwork:ReceiveBattleState"); this.state = (BattleState)state; if ((BattleState)state != BattleState.Standby) { if (StandbyView.instance.IsShow()) { StandbyView.instance.Hide(); } } }
// Use this for initialization void Start() { var stage = parameter.Stages [0]; var left = new Team (toUnits(stage)); var right = new Team (player.Units); battleState = new BattleState (left, right); LeftUnits = deploy (battleState.Left.Units, leftRoot, Side.Left); RightUnits = deploy (battleState.Right.Units, rightRoot, Side.Right); StartCoroutine (turnUpdate()); }
void Update() { if (lastState != _state) { Debug.Log("BATTLE STATE is " + _state.ToString()); lastState = _state; } StateMachine(_state); }
private void changePlayer() { ClearGUI(); if (currentPlayerTurn == players.Count - 1) { currentBattleState = BattleState.EnemyState; return; } currentPlayerTurn++; GameObject.Find("HeroName").GetComponent<Text>().text = players[currentPlayerTurn].name; currentPanelState = PanelState.Actions; currentMenuChoise = 0; foreach (var act in actions) { act.GetComponent<Text>().enabled = true; } }
void StateMachine(BattleState curState) { switch (curState) { case BattleState.START: // Start the battle by loading the necessary resources Debug.Log("Starting the Battle!"); // Load the Player Characters if (Battle_Loader.Instance.isPlayerSquadLoaded == false) { Battle_Loader.Instance.SpawnPlayerSquad(); } else if (Battle_Loader.Instance.isEnemiesLoaded == false) { // Load the Enemies Battle_Loader.Instance.SpawnEnemies(); } else { _state = BattleState.PLAYER_TURN; Battle_Controller.Instance.StartPlayerTurn(); } break; case BattleState.PLAYER_TURN: // Start the player's turn with the first available Squad member selected break; case BattleState.ENEMY_TURN: // Start the enemy's turn with first available enemy, then continue with the rest of the enemy unit's until they have all taken an action break; case BattleState.LOSE: // Tell the player they have lost the battle and give them an option to restart the level break; case BattleState.WIN: // Tell the player they have won and go back to the ship level showing the results of the battle break; case BattleState.NEXT: // Reset all unit movement and action point values then go to Player's turn again default: // Default: do nothing break; } }
void ReceiveBattleState(int state) { Debug.Log ("BattleController:ReceiveBattleState"); this.state = (BattleState)state; switch (this.state) { case BattleState.Standby: break; case BattleState.PrepareResult: if (WaitingView.instance.IsShow()) { WaitingView.instance.Hide(); } break; default: if (StandbyView.instance.IsShow()) { StandbyView.instance.Hide(); } break; } }
public ThinkRenderer(BattleState battleState) : base(battleState) { menuOptions = new List<ThinkRendererOuterMenuOption>(Think.OuterMenuOptions.Length); sortedMenuOptions = new List<ThinkRendererOuterMenuOption>(Think.OuterMenuOptions.Length); for (int i = 0; i < Think.OuterMenuOptions.Length; ++i) { string optionName = Think.OuterMenuOptions[i].ToLower(); ThinkRendererOuterMenuOption menuOption = new ThinkRendererOuterMenuOption(ResourceManager.GetTextureData("battle_ui/icons/" + optionName), menuOptionColors[optionName], i); menuOptions.Add(menuOption); sortedMenuOptions.Add(menuOption); } iconContainerTextureData = ResourceManager.GetTextureData("battle_ui/icons/container"); iconContainerGlowTextureData = ResourceManager.GetTextureData("battle_ui/icons/container_glow"); actionIconTextureData = new TextureData[actionIconNames.Length]; for (int i = 0; i < actionIconNames.Length; ++i) actionIconTextureData[i] = ResourceManager.GetTextureData("battle_ui/icons/" + actionIconNames[i]); ResetOuterMenuTransitions(); anglePerOption = MathHelper.TwoPi / Think.OuterMenuOptions.Length; halfOptionsLength = Think.OuterMenuOptions.Length / 2; whitePixelTextureData = ResourceManager.GetTextureData("white_pixel"); }
/// <summary> /// Launch an attack on a creature with a move. /// </summary> /// <param name="move">The move to attack with.</param> /// <param name="target">The target to attack.</param> public void LaunchAttack(Move move, Creature target) { //Stop here if the move or target isn't valid, or if a move already has been set in motion. if (move == null || target == null || _BattleState != BattleState.Idle) { return; } //Prepare for the attack. _BattleState = BattleState.Waiting; //Create the activated form of the move. BattleMove active = new BattleMove(move, this, target); //Attack. BattleCoordinator.Instance.QueueMove(active); }
// Start is called before the first frame update void Start() { state = BattleState.START; StartCoroutine(SetupBattle()); }
IEnumerator EnemyTurn() { dialogueText.text = enemyUnit.name + " attacks!"; if (extracting_simulation_data) { yield return(new WaitForSeconds(0f)); } else { yield return(new WaitForSeconds(1f)); } float damage_taken = playerUnit.selected_minion.CalculateTakenDamage(enemyUnit.selected_minion); playerUnit.currentHP -= damage_taken; bool isDead = false; if (playerUnit.currentHP <= 0) { isDead = true; } else { isDead = false; } playerHUD.SetHP(playerUnit.currentHP); if (extracting_simulation_data) { yield return(new WaitForSeconds(0f)); } else { yield return(new WaitForSeconds(1f)); } if (isDead) { state = BattleState.LOST; EndBattle(); yield break; } if (enemyUnit.selected_minion.speed > playerUnit.selected_minion.speed) { playerAttack = true; state = BattleState.PLAYERTURN; StartCoroutine(PlayerAttack()); } else { state = BattleState.ENDTURN; StartCoroutine(EndTurn()); } }
public void EndPlayerTurn() { if (_state == BattleState.PLAYER_TURN) { Debug.Log("STATE: Ending Player turn"); // Check if there are any enemies left! _state = BattleState.ENEMY_TURN; Battle_Controller.Instance.StartEnemyTurn(); } }
private void checksIfDead(Entity[] entities, BattleState newState) { foreach (Entity e in entities) { if (!e.isDead()) { return; } } currentState = newState; }
// Update is called once per frame void Update() { switch (battleState) { case BattleState.waiting: if (characterSpeedManager.PlayerProcess()) { selectedPlayer = characterSpeedManager.selectedPlayer; battleState = BattleState.playerChoosingCommand; break; } characterSpeedManager.EnemyProcess(); /* for (int i = 0; i < enemyList.Length; i++) { if (enemyList[i].gameObject.activeSelf) { enemyList[i].Process(); } } for (int i = 0; i < playerList.Length; i++) { if (playerList[i].gameObject.activeSelf) { playerList[i].Process(); } } */ break; case BattleState.playerChoosingCommand: ChoosingCommandManagement(); break; } }
/// <summary> /// Process a character that has been selected by the player, showing a radial menu of options. /// </summary> /// <param name="character">The character whose options are to be displayed.</param> public void SelectCharacter(Combatant character) { // if they clicked on the character already being shown, assume they want to close the menu if (character == _selectedCharacter) { DeselectCharacter(); return; } // you can only click on your characters during your turn if (_state != BattleState.PlayerTurn) { return; } if (character.Faction != 0) { return; } if (_radialMenuControl != null) { Gui.Screen.Desktop.Children.Remove(_radialMenuControl); _radialMenuControl = null; } var menu = new RadialMenuControl(((IInputService)Game.Services.GetService(typeof(IInputService))).GetMouse()) { CenterX = (int)character.Avatar.Sprite.X + character.Avatar.Sprite.Width / 2 - 10, CenterY = (int)character.Avatar.Sprite.Y + character.Avatar.Sprite.Height / 2, OnExit = DeselectCharacter }; // move icon, plus event handlers var icon = new RadialButtonControl { ImageFrame = "move", Bounds = new UniRectangle(0, 0, 64, 64) }; if (character.CanMove) { icon.MouseOver += () => { if (!character.CanMove) { return; } _battleBoardLayer.SetTargettingGrid( character.GetMovementGrid(BattleBoard.GetAccessibleGrid(character.Faction)), new Grid(1, 1) ); }; icon.MouseOut += () => { if (_aimAbility == null) { _battleBoardLayer.ResetGrid(); } }; icon.MouseClick += () => { SelectAbilityTarget(character, Ability.Factory(Game, "move")); _aimTime = DateTime.Now; }; } else { // if they can't move, this icon does nothing icon.MouseOver = () => { }; icon.MouseOut = () => { }; icon.MouseClick = () => { }; icon.MouseRelease = () => { }; icon.Enabled = false; } menu.AddOption("move", icon); //// attack icon, plus handlers icon = new RadialButtonControl { ImageFrame = "attack", Bounds = new UniRectangle(0, 0, 64, 64) }; if (character.CanAct) { var ability = Ability.Factory(Game, "attack"); ability.Character = character; icon.MouseOver += () => { if (!character.CanAct) { return; } _battleBoardLayer.SetTargettingGrid( ability.GenerateTargetGrid(BattleBoard.Sandbag.Clone()), new Grid(1, 1) ); }; icon.MouseOut += () => { if (_aimAbility == null) { _battleBoardLayer.ResetGrid(); } }; icon.MouseRelease += () => { SelectAbilityTarget(character, ability); _aimTime = DateTime.Now; }; } else { // if they can't act, this icon does nothing icon.MouseOver = () => { }; icon.MouseOut = () => { }; icon.MouseClick = () => { }; icon.MouseRelease = () => { }; icon.Enabled = false; } menu.AddOption("attack", icon); //// special abilities icon, plus event handlers icon = new RadialButtonControl { ImageFrame = "special", Bounds = new UniRectangle(0, 0, 64, 64) }; if (character.CanAct) { icon.MouseRelease += () => SelectSpecialAbility(character); } else { // if they can't act, this icon does nothing icon.MouseOver = () => { }; icon.MouseOut = () => { }; icon.MouseClick = () => { }; icon.MouseRelease = () => { }; icon.Enabled = false; } menu.AddOption("special", icon); icon = new RadialButtonControl { ImageFrame = "item", Bounds = new UniRectangle(0, 0, 64, 64), Enabled = false }; menu.AddOption("item", icon); _radialMenuControl = menu; Gui.Screen.Desktop.Children.Add(_radialMenuControl); _selectedCharacter = character; _state = BattleState.CharacterSelected; }
protected override IEnumerator doAttackAnimation(BattleState.State nextState) { coroutines.doAnimation = true; this.transform.LookAt(combatSettings.target.transform); anim.SetFloat(animHash.getHash("moveSpeedFloat"), 0.1f); Ability.AnimationSequence[] animSequence = null; switch (combatSettings.ability.getAbilityType()) { case "Physical": animSequence = new Ability.AnimationSequence[1]; if (damageDone.crit) { animSequence[0].animState = animHash.getHash("criticalAttackState"); animSequence[0].animTrigger = animHash.getHash("criticalAttackTrigger"); animSequence[0].nextStateTime = 0.3f; } else { animSequence[0].animState = animHash.getHash("attackState"); animSequence[0].animTrigger = animHash.getHash("attackTrigger"); animSequence[0].nextStateTime = 0.4f; } break; case "Magic": animSequence = new Ability.AnimationSequence[1]; animSequence[0].animState = animHash.getHash("castState"); animSequence[0].animTrigger = animHash.getHash("castTrigger"); animSequence[0].nextStateTime = 0.8f; break; case "Wait": animSequence = new Ability.AnimationSequence[1]; animSequence[0].animState = animHash.getHash("stockState"); animSequence[0].animTrigger = animHash.getHash("stockTrigger"); animSequence[0].nextStateTime = 0.5f; break; default: break; } while (!combatSettings.ability.doAnimation(this.gameObject, combatSettings.target, animSequence)) { yield return null; } combatSettings.attack = false; state.setState(nextState); coroutines.doAnimation = false; }
/// <summary> /// Initialize a battle sequence by name. This call happens at the start of a battle and is required /// for this scene to not die a horrible death. /// </summary> /// <param name="battleName">Name of the battle to be initialized</param> public void SetBattle(string battleName) { // set up defaults BattleBoard = new BattleBoard(); RoundNumber = 0; FactionTurn = 0; _state = BattleState.PlayerTurn; var partyGrid = new List <Point>(); _battleBoardLayer = new BattleBoardLayer(this, null); _battleBoardLayer.CharacterSelected += SelectCharacter; Components.Add(_battleBoardLayer); switch (battleName) { case "coliseum/halls": _battleBoardLayer.SetBackground("Zones/Coliseum/Halls/north"); _battleBoardLayer.SetGrid("Zones/Coliseum/Halls/battle"); BattleBoard.Sandbag = Grid.FromBitmap(Game.Services, "Zones/Coliseum/Halls/battle"); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/Halls/north")); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/pillar") { X = 393, Y = 190, DrawOrder = 248 }); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/pillar") { X = 393, Y = 390, DrawOrder = 448 }); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/pillar") { X = 393, Y = 590, DrawOrder = 648 }); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/pillar") { X = 593, Y = 190, DrawOrder = 248 }); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/pillar") { X = 593, Y = 390, DrawOrder = 448 }); _battleBoardLayer.AddImage(new ImageObject(Game, _battleBoardLayer, "Zones/Coliseum/pillar") { X = 593, Y = 590, DrawOrder = 648 }); partyGrid.Add(new Point(10, 13)); partyGrid.Add(new Point(11, 13)); partyGrid.Add(new Point(9, 13)); partyGrid.Add(new Point(10, 12)); partyGrid.Add(new Point(11, 12)); partyGrid.Add(new Point(9, 12)); BattleBoard.Characters.Add(GenerateCombatant("Guard 1", "coliseum/guard", new Vector2(9, 3))); BattleBoard.Characters.Add(GenerateCombatant("Guard 2", "coliseum/guard", new Vector2(11, 3))); BattleBoard.Characters.Add(GenerateCombatant("Guard Captain", "coliseum/guard", new Vector2(10, 3))); BattleBoard.Characters.Add(GenerateCombatant("Guard 3", "coliseum/guard", new Vector2(9, 10))); BattleBoard.Characters.Add(GenerateCombatant("Guard 4", "coliseum/guard", new Vector2(11, 10))); BattleBoard.Characters.Add(GenerateCombatant("Guard 5", "coliseum/guard", new Vector2(10, 10))); _startingDialog = Dialog.Fetch("coliseum", "guards"); break; default: throw new Exception("unknown battle " + battleName); } // add party to the party grid for this battle, in order for (var i = 0; i < ((SRPGGame)Game).Party.Count; i++) { var character = ((SRPGGame)Game).Party[i]; character.Avatar.Location.X = partyGrid[i].X; character.Avatar.Location.Y = partyGrid[i].Y; BattleBoard.Characters.Add(character); } _battleBoardLayer.SetBoard(BattleBoard); _commander.BattleBoard = BattleBoard; // center camera on partyGrid[0] UpdateCamera( 0 - partyGrid[0].X * 50 + Game.GraphicsDevice.Viewport.Width / 2, 0 - partyGrid[0].Y * 50 + Game.GraphicsDevice.Viewport.Height / 2 ); ChangeFaction(0); }
/// <summary> /// Process a command given by either the AI or the player. These commands can be attacking, casting a spell, /// using an item or moving. /// </summary> /// <param name="command">The command to be executed.</param> public void ExecuteCommand(Command command) { _state = BattleState.ExecutingCommand; switch (command.Ability.Name) { case "Move": { // special case for movement var grid = BattleBoard.GetAccessibleGrid(command.Character.Faction); // run an A* pathfinding algorithm to get a route var coords = grid.Pathfind(new Point((int)command.Character.Avatar.Location.X, (int)command.Character.Avatar.Location.Y), command.Target); // remove any points on the path that don't require a direction change for (var i = coords.Count - 2; i > 0; i--) { if (coords[i - 1].X == coords[i + 1].X || coords[i - 1].Y == coords[i + 1].Y) { coords.RemoveAt(i); } } _movementCoords = coords; _state = BattleState.MovingCharacter; command.Character.CanMove = false; if (FactionTurn == 1) { break; } // if this character has any queued commands, cancel them upon moving var queuedCommands = (from c in QueuedCommands where c.Character == command.Character select c).ToArray(); if (queuedCommands.Length > 0) { QueuedCommands.Remove(queuedCommands[0]); command.Character.CanAct = true; } } break; default: var hits = command.Ability.GenerateHits(BattleBoard, command.Target); // remove any hits on characters that no longer exist for (var i = hits.Count - 1; i >= 0; i--) { if (BattleBoard.GetCharacterAt(hits[i].Target) == null) { hits.RemoveAt(i); } } _commander.RecordCommand(command, hits); // if this ability still has hits left, process them normally if (hits.Count > 0) { command.Character.CanAct = false; DisplayHits(hits); command.Character.CurrentMana -= command.Ability.ManaCost; } break; } }
/// <summary> /// Receive a list of hits and change state to display those hits on screen, as well /// as process the damage. /// </summary> /// <param name="hits"></param> public void DisplayHits(List <Hit> hits) { _hits = hits; _state = BattleState.DisplayingHits; }
/// <summary> /// Change state to execute commands /// </summary> public void ExecuteQueuedCommands() { _state = BattleState.ExecutingCommand; }
IEnumerator EnemyTurn() { yield return(new WaitForSeconds(1f)); float randomNumber = Random.value; // pega numero aleatorio pra definir a acao do inimigo // A seguir a inteligencia artificial do inimigo if (randomNumber <= 0.5 || playerCarUnit.backWheelCurrentHP == 0 || playerCarUnit.frontWheelCurrentHP == 0) // aqui ele ataca o dano total do jogador { bool isTotalDead = playerCarUnit.TakeDamageTotalHP(enemyCarUnit.mainWeaponDamage); playerHUD.SetTotalHP(playerCarUnit); Instantiate(explosion, playerInitialPosition); if (isTotalDead) { state = BattleState.LOST; restartScreen.SetActive(true); } else { EnablePlayerActions(); state = BattleState.PLAYERTURN; } } else if (randomNumber > 0.5 && randomNumber <= 0.75) // aqui ele ataca as rodas da frente { bool isFrontWheelDead = playerCarUnit.TakeDamageFrontWheelHP(enemyCarUnit.mainWeaponDamage); playerHUD.SetFrontWheelHP(playerCarUnit); Instantiate(littleExplosion, playerInitialPosition); if (isFrontWheelDead) { StartCoroutine(PlayerWheelDestroyed()); repairFrontWheelHPButton.gameObject.SetActive(false); if (playerCarUnit.ReturnCarCurrentHP(playerCarUnit.carCurrentHP)) { state = BattleState.LOST; restartScreen.SetActive(true); } else { EnablePlayerActions(); state = BattleState.PLAYERTURN; } } else { EnablePlayerActions(); state = BattleState.PLAYERTURN; } } else // aqui ele ataca as rodas de trás { bool isBackWheelDead = playerCarUnit.TakeDamageBackWheelHP(enemyCarUnit.mainWeaponDamage); playerHUD.SetBackWheelHP(playerCarUnit); Instantiate(littleExplosion, playerInitialPosition); if (isBackWheelDead) { StartCoroutine(PlayerWheelDestroyed()); repairBackWheelHPButton.gameObject.SetActive(false); if (playerCarUnit.ReturnCarCurrentHP(playerCarUnit.carCurrentHP)) { state = BattleState.LOST; restartScreen.SetActive(true); } else { EnablePlayerActions(); state = BattleState.PLAYERTURN; } } else { EnablePlayerActions(); state = BattleState.PLAYERTURN; } } }
IEnumerator FishTurn() { // pick a random action // if so, do the thing var fishAct = Random.Range(0, 2); if (fishAct == 0) { bool fishSwam = fishUnit.SwimAway(); if (fishSwam) { fish_motion.SetTrigger("swim"); mainText.text = "The fish struggles against the line."; } else { fish_motion.SetTrigger("rest"); mainText.text = "The fish recovers its energy."; } UIman.updateUI(fishUnit); } if (fishAct == 1) { bool fishDove = fishUnit.DiveDeep(); if (fishDove) { fish_motion.SetTrigger("dive"); mainText.text = "The fish dives away from the boat."; } else { fish_motion.SetTrigger("rest"); mainText.text = "The fish recovers its energy."; } UIman.updateUI(fishUnit); } if (fishAct == 2) { bool fishJuke = fishUnit.JukeSide(); if (fishJuke) { fish_motion.SetTrigger("juke"); mainText.text = "The fish flaisl wildly!"; } else { fish_motion.SetTrigger("rest"); mainText.text = "The fish recovers its energy."; } UIman.updateUI(fishUnit); } yield return(new WaitForSeconds(2f)); bool caught = fishUnit.caught; bool escaped = fishUnit.escaped; if (caught == true) { state = BattleState.WON; EndBattle(); } if (escaped == true) { state = BattleState.LOST; EndBattle(); } if (caught == false && escaped == false) { state = BattleState.PLAYERTURN; PlayerTurn(); } }
public override IPlayedCard Play(int memberId, BattleState battleState, AIStrategy strategy) { var me = battleState.Members[memberId]; var playableCards = battleState.GetPlayableCards(memberId); var allies = me.TeamType == TeamType.Enemies ? battleState.Enemies.Where(m => m.IsConscious()) : battleState.Heroes.Where(m => m.IsConscious()); var maybeCard = new Maybe <CardTypeData>(); IEnumerable <CardTypeData> cardOptions = playableCards; // TODO: Dealing killing blow if possible with an attack card var attackCards = cardOptions.Where(c => c.Is(CardTag.Attack)).ToList(); if (allies.Count() == 1 && attackCards.Any()) { maybeCard = new Maybe <CardTypeData>(attackCards.MostExpensive()); } // Don't play a heal if all allies are very healthy if (allies.All(a => a.CurrentHp() >= a.MaxHp() * 0.9)) { cardOptions = cardOptions.Where(c => !c.Is(CardTag.Healing)); } // Don't play a shield if all allies are already shielded if (allies.All(a => a.RemainingShieldCapacity() > a.MaxShield() * 0.7)) { cardOptions = cardOptions.Where(x => !x.Is(CardTag.Defense, CardTag.Shield)); } var card = maybeCard.IsPresent ? maybeCard.Value : cardOptions .ToArray() .Shuffled() .OrderByDescending(c => c.Cost.Amount) .ThenBy(c => CardTypePriority[c.Tags.First()]) // Maybe needs a better way to prioritze .First(); var targets = card.ActionSequences.Select(action => { var possibleTargets = battleState.GetPossibleConsciousTargets(me, action.Group, action.Scope); if (card.Is(CardTag.Healing)) { return(possibleTargets.MostDamaged()); } if (card.Is(CardTag.Defense, CardTag.Shield)) { if (possibleTargets.Any(x => !x.HasShield())) { return(possibleTargets.Where(x => !x.HasShield()) .MostVulnerable()); } // Or, use shield to whomever could use the most return(possibleTargets.OrderByDescending(x => x.TotalRemainingShieldCapacity()).First()); } if (card.Is(CardTag.Attack)) { return(strategy.AttackTargetFor(action)); } return(possibleTargets.Random()); }); var cardInstance = card.CreateInstance(battleState.GetNextCardId(), me); return(new PlayedCardV2(me, targets.ToArray(), cardInstance)); }
public virtual bool Call(GameTime gameTime, BattleState battleState) { return(true); }
void Update() { switch (currentState) { case BattleState.STARTING: if (allSkills == null) { allSkills = new Skill[15]; allSkills[0] = idols[0].skills[0]; allSkills[1] = idols[0].skills[1]; allSkills[2] = idols[0].skills[2]; allSkills[3] = idols[0].skills[3]; allSkills[4] = idols[0].skills[4]; allSkills[5] = idols[1].skills[0]; allSkills[6] = idols[1].skills[1]; allSkills[7] = idols[1].skills[2]; allSkills[8] = idols[1].skills[3]; allSkills[9] = idols[1].skills[4]; allSkills[10] = idols[2].skills[0]; allSkills[11] = idols[2].skills[1]; allSkills[12] = idols[2].skills[2]; allSkills[13] = idols[2].skills[3]; allSkills[14] = idols[2].skills[4]; } currentState = BattleState.WAITING; break; case BattleState.WAITING: int a, b, c, d, e; a = Random.Range(0, 14); b = Random.Range(0, 14); while (a == b) { b = Random.Range(0, 14); } c = Random.Range(0, 14); while (c == a || c == b) { c = Random.Range(0, 14); } d = Random.Range(0, 14); while (d == a || d == b || d == c) { d = Random.Range(0, 14); } e = Random.Range(0, 14); while (e == a || e == b || e == c || e == d) { e = Random.Range(0, 14); } skillCards[0].setSkill(allSkills[a]); skillCards[1].setSkill(allSkills[b]); skillCards[2].setSkill(allSkills[c]); skillCards[3].setSkill(allSkills[d]); skillCards[4].setSkill(allSkills[e]); selectedSkills.Clear(); currentState = BattleState.PLAYER_SELECTING_ACTIONS; //skillHUDPanel.transform.localPosition = originalHUDPos; break; case BattleState.PLAYER_SELECTING_ACTIONS: //hudTimeTraveling = 0; if (hudTimeTraveling > 0) { hudTimeTraveling -= Time.deltaTime; float t = hudTimeTraveling / timeForUIOffscreen; Vector3 newPos = Vector3.Lerp(originalHUDPos, hudOffscreenPos, t); skillHUDPanel.transform.localPosition = newPos; } break; case BattleState.PERFORMING_ACTIONS: if (hudTimeTraveling < timeForUIOffscreen) { hudTimeTraveling += Time.deltaTime; float t = hudTimeTraveling / timeForUIOffscreen; Vector3 newPos = Vector3.Lerp(originalHUDPos, hudOffscreenPos, t); skillHUDPanel.transform.localPosition = newPos; } if (currentActor.currentState != IdolStateMachine.IdolState.ACTION) { if (nextActor < selectedSkills.Count) { currentSkillCard.setSkill(selectedSkills[nextActor]); currentActor = selectedSkills[nextActor++].readyPerformance(); } else { currentSkillPanel.SetActive(false); // Idols finished their actions currentState = BattleState.CROWD_ACTIONS; } } break; case BattleState.CROWD_ACTIONS: //CrowdStateMachine crowd = GameObject.Find("CrowdMember").GetComponent<CrowdStateMachine>(); //crowd.startAction(); crowdMan.update(); break; } }
/* TODO: CHANGE THIS SO IT WORKS WITH ABILITIES return value indicates if action could have been carried out */ public void performAction(PossibleAction posAc) { switch (posAc) { case PossibleAction.ATTACK: currentState = BattleState.CALCDAMAGE; break; case PossibleAction.CHARACTER_DIED: currentState = BattleState.WAITING; break; default: break; } }
void Start() { //positionHolders = new List<GameObject>(GameObject.FindGameObjectsWithTag("PositionPlaceholder")); idolHUDPanel = GameObject.Find("IdolHUDs"); skillHUDPanel = GameObject.Find("SkillHUD"); originalHUDPos = skillHUDPanel.transform.localPosition; RectTransform rt = skillHUDPanel.transform.GetComponent <RectTransform>(); hudOffscreenPos = originalHUDPos; //hudOffscreenPos.x += rt.sizeDelta.x * rt.localScale.x; hudOffscreenPos.x = rt.rect.width; print(hudOffscreenPos.x + ""); skillCards[0] = GameObject.Find("SkillCard (0)").GetComponent <SkillCardController>(); skillCards[1] = GameObject.Find("SkillCard (1)").GetComponent <SkillCardController>(); skillCards[2] = GameObject.Find("SkillCard (2)").GetComponent <SkillCardController>(); skillCards[3] = GameObject.Find("SkillCard (3)").GetComponent <SkillCardController>(); skillCards[4] = GameObject.Find("SkillCard (4)").GetComponent <SkillCardController>(); currentSkillPanel = GameObject.Find("CurrentSkill"); currentSkillPanel.SetActive(false); currentSkillCard = currentSkillPanel.GetComponentInChildren <SkillCardController>(); position1 = GameObject.Find("position1"); position1.gameObject.GetComponent <SpriteRenderer>().sortingLayerName = backgroundLayer; position2 = GameObject.Find("position2"); position2.gameObject.GetComponent <SpriteRenderer>().sortingLayerName = backgroundLayer; position3 = GameObject.Find("position3"); position3.gameObject.GetComponent <SpriteRenderer>().sortingLayerName = backgroundLayer; idols = new List <IdolStateMachine>(); GameObject idol = (GameObject)UnityEditor.AssetDatabase.LoadAssetAtPath <Object>("Assets/Prefabs/Idol Achan.prefab"); GameObject clone = GameObject.Instantiate(idol, position1.transform.position, idol.transform.rotation); IdolStateMachine ism = clone.GetComponent <IdolStateMachine>(); ism.setHUD(GameObject.Find("IdolHUD (1)").transform); idols.Add(ism); idol = (GameObject)UnityEditor.AssetDatabase.LoadAssetAtPath <Object>("Assets/Prefabs/Idol Bchan.prefab"); clone = GameObject.Instantiate(idol, position2.transform.position, idol.transform.rotation); ism = clone.GetComponent <IdolStateMachine>(); ism.setHUD(GameObject.Find("IdolHUD (2)").transform); idols.Add(ism); idol = (GameObject)UnityEditor.AssetDatabase.LoadAssetAtPath <Object>("Assets/Prefabs/Idol Cchan.prefab"); clone = GameObject.Instantiate(idol, position3.transform.position, idol.transform.rotation); ism = clone.GetComponent <IdolStateMachine>(); ism.setHUD(GameObject.Find("IdolHUD (3)").transform); idols.Add(ism); currentState = BattleState.STARTING; crowdMan = new CrowdController(); }
/* Update is called once per frame The function works like this: - The turnQueue is queried to see if someone's turn should begin - Depending on the state of the battle, a turn is executed, nothing happens...etc - Finally, the waiting times are updated according to Time.Delta */ void Update () { //The current battle state determines what actions can be taken. checkForTurn(); checkEndOfBattle(); switch(currentState) { case BattleState.START: // Start of the battle. UIStateController.Instance.enableMenu("waiting"); UIStateController.Instance.updateCharacterAndEnemiesText(); currentState = BattleState.WAITING; break; case BattleState.WAITING: // Idle phase, nothing happens. /* DIFFERENTS EFFECTS COUlD BE APPLIED: - Check if buffs / debuffs end (speed up, poison...) - Apply effects such as poison - Regeneration (Perhaps armor fell off and is being regenerated) */ break; case BattleState.PLAYERTURN: // Player turn starts and // Start GUI showing the "initial" menu state. if (allyTurnReady == null) { QueuedEntity allyqe = turnQueue.Dequeue(); allyTurnReady = (BaseCharacterClass)allyqe.entity; UIStateController.Instance.enableMenu("initial"); UIStateController.Instance.personaliseMenuToCharacter(allyTurnReady); } currentState = BattleState.WAITING; break; case BattleState.ENEMYTURN: // Enemy's turn starts QueuedEntity enemyqe = turnQueue.Dequeue(); BaseEnemy enemy = (BaseEnemy)enemyqe.entity; // To ensure that dead units are not targeted, filter them out. Entity target = enemy.strategy(Array.FindAll(alliedCharacters, e => !e.isDead()), Array.FindAll(enemies, e => !e.isDead())); Debug.Log(enemy.getName() + " Attacks " + target.getName() + " for " + enemy.attack + " damage"); target.takeDamage(enemy.attack); turnQueue.Enqueue(new QueuedEntity(enemy), enemy.speed); UIStateController.Instance.updateCharacterAndEnemiesText(); currentState = BattleState.WAITING; break; case BattleState.CALCDAMAGE: // Calculates dmg to target(s) BattleAbilityUseHandler abilityHandler = new BattleAbilityUseHandler(ref allyTurnReady, playerTargetIndex, ref alliedCharacters, ref enemies); abilityHandler.calculateDamage(); int castingTIme = abilityHandler.calculateCastingTime(); this.playerTargetIndex = -1; turnQueue.Enqueue(new QueuedEntity(allyTurnReady), castingTIme); this.allyTurnReady = null; currentState = BattleState.WAITING; UIStateController.Instance.updateCharacterAndEnemiesText(); break; case BattleState.ADDSTATUSEFFECT: // Adds special status such as poison. break; case BattleState.WIN: /* All enemies have been defeated, we store the relevant information in GameInformation and we get back to the map */ //GameInformation.alliedCharacters = alliedCharacters; Debug.Log("GAME WON"); break; case BattleState.LOSE: // All allied characters have been defeated. Debug.Log("GAME LOST"); break; default: break; } // If it's a character's turn, check if he / she has died checkIfAllyTurnReadyIsDead(); // Update the turnque in order to reflect time passing. updateTurnQueue(Time.deltaTime); }
private void SendMessageToManager(ICharactersManager manager, BattleState _state) { manager.RecieveMessage(_state); }
//开始战斗 private void Fight() { battleState = BattleState.Fighting; BattleUnit actionUnit = null; do { //连接渲染器,则一步一更新 //没有连接渲染器,则一直计算直到结束 actionUnit = actionQueue.Peek(); if (firstFight) { firstFight = false; } else { if (actionUnit.BPStage) { UtilityHelper.Log("We are in BP stage, continue to fight"); actionUnit.battleUnitAttribute.BPUsed(); } else { UtilityHelper.Log("change queue order"); if (actionUnit.battleUnitAttribute.BPUsingStage()) { actionUnit.battleUnitAttribute.OutOfBPAction(); } actionQueue.Dequeue(); CalculateNextAction(actionUnit); actionUnit = actionQueue.Peek(); } } //增加BP值 if (actionUnit.battleUnitAttribute.manualOperation && actionUnit.battleUnitAttribute.BPUsingStage() == false) { if (actionUnit.battleUnitAttribute.BP < EGameConstL.BPMax) { actionUnit.battleUnitAttribute.BP++; } } if (actionUnit == null) { battleState = BattleState.End; break; } if (actionUnit.CanAction) { HeroActionState state = actionUnit.BattleAction(); switch (state) { case HeroActionState.Normal: battleState = BattleState.Fighting; break; case HeroActionState.WaitForPlayerChoose: battleState = BattleState.WaitForPlayer; break; case HeroActionState.Error: battleState = BattleState.Exception; break; case HeroActionState.Warn: battleState = BattleState.Exception; UtilityHelper.LogWarning(string.Format("Warning: battle action state warning -> {0}", actionUnit.ToString())); break; default: break; } } if (battleFieldEvents.Count > EGameConstL.BattleFieldMaxActions) { UtilityHelper.LogError("Battle actions overflow max limit."); battleState = BattleState.Exception; } else { //只在这种情况下做战斗结束的判断 if (!actionUnit.CanAction || actionUnit.targetBattleUnit == null || !actionUnit.targetBattleUnit.CanAction) { CheckBattleEnd(); } } } while (battleFieldRenderer == null && battleState != BattleState.End && battleState != BattleState.Exception); //连接了渲染器,一步一表现 if (battleFieldRenderer != null) { if (battleState == BattleState.WaitForPlayer) { battleFieldRenderer.PlayBattle(null); } else { battleFieldRenderer.PlayBattle(Run); } } else { Run(); } }
IEnumerator glassCannonAttacks() { //glass cannon has the chance to 'hold an attack' by lighting its fuse. we need to make sure not to do typical //attack sequence if it needs to use this other attack. System.Random getRandom = new System.Random(); if (isLoading) { isLoading = false; int totalDamage = (enemyUnit.stats [2] * 2) - playerLevel.stats [3]; int randomNum = getRandom.Next(0, 11); if (randomNum != 1) { dialogueText.text = "Glass Cannon fires."; bool isDead = playerUnit.TakeDamage(totalDamage); playerHUD.SetHP(playerUnit.currentHP); yield return(new WaitForSeconds(2f)); if (isDead) { state = BattleState.LOST; StartCoroutine(EndBattle()); yield break; } else { state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } } else { dialogueText.text = "Glass Cannon misfires."; bool isDead = enemyUnit.TakeDamage(totalDamage); enemyHUD.SetHP(enemyUnit.currentHP); yield return(new WaitForSeconds(2f)); if (isDead) { state = BattleState.WON; StartCoroutine(EndBattle()); yield break; } else { state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } } } else if (!isLoading) { int randomNum = getRandom.Next(1, 5); //IDLE if (randomNum == 1) { dialogueText.text = "Glass Cannon loosens up."; yield return(new WaitForSeconds(2f)); state = BattleState.PLAYERTURN; PlayerTurn(); //ATTACK } else if (randomNum == 2) { //Flavor text dialogueText.text = "Glass Cannon cuts you with its sharp edges."; } else { dialogueText.text = "Glass Cannon lights its fuse."; isLoading = true; yield return(new WaitForSeconds(2f)); Debug.Log("lit fuse"); state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } if (randomNum == 2) { //Determine hit chance System.Random hitRandom = new System.Random(); randomNum = hitRandom.Next(0, 101); int hitChance = 95 - (playerLevel.stats [4] - enemyUnit.stats [4]); if (hitChance < 50) { hitChance = 50; } //Determine if attack hits bool doesHit; if (randomNum < hitChance) { Debug.Log("Glass Cannon hits!"); doesHit = true; } else { Debug.Log("Glass Cannon misses :("); doesHit = false; } //If attack does not hit, inform player and then switch back to PLAYERTURN if (!doesHit) { yield return(new WaitForSeconds(2f)); dialogueText.text = "The attack missed!"; state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } //If attack does hit, calculate damage //For Glass cannon, it only does standard attack damage except for inside of its firing section int totalDamage = (enemyUnit.stats [2] * 2) - playerLevel.stats [3]; if (totalDamage < 1) { totalDamage = 1; } Debug.Log("Total Enemy Damage by Glass Cannon: " + totalDamage); //Use this TakeDamage() function to deal the proper amount of damage to player bool isDead = playerUnit.TakeDamage(totalDamage); playerHUD.SetHP(playerUnit.currentHP); yield return(new WaitForSeconds(2f)); if (isDead) { state = BattleState.LOST; StartCoroutine(EndBattle()); yield break; } else { state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } } } }
IEnumerator PlayerAttack() { if (bot_vs_bot && !playerAttack) //If the combat is simulated or spected by the player { enemyUnit.ChooseMinion(); playerUnit.ChooseMinion(true); } if (playerUnit.selected_minion.speed >= enemyUnit.selected_minion.speed || playerAttack) { float damage_taken = enemyUnit.selected_minion.CalculateTakenDamage(playerUnit.selected_minion); enemyUnit.currentHP -= damage_taken; bool isDead = false; if (enemyUnit.currentHP <= 0) { isDead = true; } else { isDead = false; } enemyHUD.SetHP(enemyUnit.currentHP); dialogueText.text = playerUnit.selected_minion.name + ", attack!"; if (extracting_simulation_data) { yield return(new WaitForSeconds(0f)); } else { yield return(new WaitForSeconds(2f)); } if (isDead) { state = BattleState.WON; enemyUnit.RestMinion(); EndBattle(); yield break; } if (playerAttack) { state = BattleState.ENDTURN; StartCoroutine(EndTurn()); } else { state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); } playerAttack = false; } else { state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); } }
IEnumerator caplingAttacks() { //There is a lot of randomness in enemy attacks, so it needs to start with randomly picking between x enemy attacks System.Random getRandom = new System.Random(); int randomNum = getRandom.Next(1, 5); bool causesBubblebutt = false; //IDLE if (randomNum == 1) { dialogueText.text = "Capling tries to hoist a flag that is no longer there."; yield return(new WaitForSeconds(2f)); state = BattleState.PLAYERTURN; PlayerTurn(); yield break; //ATTACK } else { if (randomNum == 2) { //Flavor text dialogueText.text = "Capling jumps down your throat."; randomNum = getRandom.Next(1, 5); if (randomNum == 4) { Debug.Log("bubblebutt :P"); causesBubblebutt = true; } } else { dialogueText.text = "Capling scratches you with its hook hand."; } //Determine hit chance System.Random hitRandom = new System.Random(); randomNum = hitRandom.Next(0, 101); int hitChance = 95 - (playerLevel.stats [4] - enemyUnit.stats [4]); if (hitChance < 50) { hitChance = 50; } //Determine if attack hits bool doesHit; if (randomNum < hitChance) { Debug.Log("Capling hits!"); doesHit = true; } else { Debug.Log("Capling misses :("); doesHit = false; } //If attack does not hit, inform player and then switch back to PLAYERTURN if (!doesHit) { yield return(new WaitForSeconds(2f)); dialogueText.text = "The attack missed!"; yield return(new WaitForSeconds(2f)); state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } //If attack does hit, calculate damage //For Capling, damage changes depending on which of its two attacks it uses. If the randomNum generated is 2, it needs //to do skill damage and check for bubblebutt. 50% of the time is regular attack damage (randomNums 3 and 4) int totalDamage = 1; if (randomNum == 2) { Debug.Log(" a throat jump"); totalDamage = (enemyUnit.stats [2] * 2) - playerLevel.stats [3]; } else { totalDamage = (enemyUnit.stats [0] * 2) - playerLevel.stats [1]; } if (totalDamage < 1) { totalDamage = 1; } Debug.Log("Total Enemy Damage by Capling: " + totalDamage); //Use this TakeDamage() function to deal the proper amount of damage to player bool isDead = playerUnit.TakeDamage(totalDamage); playerHUD.SetHP(playerUnit.currentHP); yield return(new WaitForSeconds(2f)); if (causesBubblebutt) { dialogueText.text = "You have been inflicted with Bubblebutt. Gases built up inside of you cause you to float! Your mobility is reduced to 0."; playerLevel.stats [4] = 0; hasBubbleButt = true; yield return(new WaitForSeconds(2f)); } if (isDead) { state = BattleState.LOST; StartCoroutine(EndBattle()); yield break; } else { state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } } }
public override void BattleStateChanged(BattleState bState) { //Debug.Log (this.Identifier + "BattleState: " + bState); if(bState == BattleState.CONFUSING) { panelText.text = this.Entity.Identifier + " is confusing and hit himself"; } ExecuteChangeBattleState(); }
IEnumerator PlayerAttack(Button button) { //damage the enemy bool isDead; Attack thisAttack = button.GetComponent <Attack>(); //if the character uses a 'skill' attack vs an 'attack' attack, we need to remove SP so it's important to have a variable let //us know. //After the character selects a skill, we stop displaying them and instead display dialogue skills.SetActive(false); dialogueBox.SetActive(true); //Hit chance: 95% - (Opponent Mobility - Your Mobility) to a minimum of 50% bool doesHit; //need to check for hit before we can determine damage System.Random getRandom = new System.Random(); int randomNum = getRandom.Next(0, 101); dialogueText.text = "You attack the enemy!"; int hitChance = 95 - (enemyUnit.stats [4] - playerLevel.stats [4]); if (hitChance < 50) { hitChance = 50; } if (randomNum < hitChance) { Debug.Log("Player hits!"); doesHit = true; } else { Debug.Log("Player misses :("); doesHit = false; } //If the player's attack misses, all we need to do is let them know and then proceed with the enemy's turn if (!doesHit) { yield return(new WaitForSeconds(2f)); dialogueText.text = "The attack missed!"; yield return(new WaitForSeconds(2f)); state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); } int totalDamage = 1; //On a hit, we need to start with calculating base damage for the attack if (doesHit) { //Uses this formula: (Your Attack * 2) - (Opponent Defense) to a minimum of 1. if (!thisAttack.isSkill) { totalDamage = (playerLevel.stats [0] * 2) - enemyUnit.stats [1]; } else { totalDamage = (playerLevel.stats [2] * 2) - enemyUnit.stats [3]; } if (totalDamage < 1) { totalDamage = 1; } Debug.Log("Total Damage " + totalDamage); if (enemyUnit.type == "trash") { if (thisAttack.type == "trash") { isDead = enemyUnit.TakeDamage(totalDamage * 2 * thisAttack.damage); dialogueText.text = "You deal extra damage with the correct waste disposal method!"; } else { isDead = enemyUnit.TakeDamage(totalDamage * thisAttack.damage); dialogueText.text = "There may be a more proper way to handle this enemy"; } } else if (enemyUnit.type == "recycle") { print(thisAttack.type); if (thisAttack.type == "recycle") { isDead = enemyUnit.TakeDamage(totalDamage * 2 * thisAttack.damage); dialogueText.text = "You deal extra damage with the correct waste disposal method!"; } else { isDead = enemyUnit.TakeDamage(totalDamage * thisAttack.damage); dialogueText.text = "There may be a more proper way to handle this enemy"; } } else { if (thisAttack.type == "compost") { isDead = enemyUnit.TakeDamage(totalDamage * 2 * thisAttack.damage); dialogueText.text = "You deal extra damage with the correct waste disposal method!"; } else { isDead = enemyUnit.TakeDamage(totalDamage * thisAttack.damage); dialogueText.text = "There may be a more proper way to handle this enemy"; } } //We need to reset enemy HP after they take damage enemyHUD.SetHP(enemyUnit.currentHP); yield return(new WaitForSeconds(2f)); //check if the enemy is dead //change state based on result if (isDead) { //End the battle state = BattleState.WON; StartCoroutine(EndBattle()); } else { //Enemy Turn state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); } } }
/// <summary> /// Initialize the creature. /// </summary> private void Initialize() { //Initialize the class. _Gender = Gender.Male; _Types = new List<PokemonType>(); _Moves = new List<Move>(); _Sprite = new SpriteManager(); _MaxEnergy = 100; _CurrentEnergy = _MaxEnergy; _Position = Vector2.Zero; _Velocity = Vector2.Zero; _TimeBetweenMoving = .01f; _ElapsedMovementTime = 0; _ElapsedEnergyTime = 0; _EnergyRecoverySpeed = .1f; _BattleState = BattleState.Idle; _FacingDirection = Direction.Down; _MovementSpeed = InsipidusEngine.SpeedType.Still; }
public MoveActorRenderer(BattleState battleState, ThinkRenderer thinkRenderer) : base(battleState) { tintOtherPartyMembers(new Color(Color.White.ToVector3() * 0.7f)); this.thinkRenderer = thinkRenderer; }
/// <summary> /// Constructor for a modify event. /// </summary> /// <param name="timeline">The timeline this event is part of.</param> /// <param name="start">The start of the event.</param> /// <param name="dependentOn">An optional event to be dependent upon, ie. wait for.</param> /// <param name="character">The character who health will be modified.</param> /// <param name="state">The state to change into.</param> public ModifyStateEvent(Timeline timeline, float start, TimelineEvent dependentOn, Creature character, BattleState state) { Initialize(timeline, start, dependentOn, character, state); }
public void OnBackSelected() { state = BattleState.PLAYERTURN; PlayerTurn(); }
// Update is called once per frame public override void Reset() { bs = GameObject.FindGameObjectWithTag("battlestate").GetComponent<BattleState>(); }
IEnumerator SetupBattle() { //Instantiate both player and enemy into the battle global = GameObject.Find("GlobalObject"); isLoading = false; GameObject player = Instantiate(playerPrefab, playerBattleStation); GlobalControl globalObject = global.GetComponent <GlobalControl> (); GameObject enemy = (GameObject)Instantiate(Resources.Load(globalObject.nextFight), enemyBattleStation); //Get the information about the enemy and player playerUnit = player.GetComponent <Player> (); enemyUnit = enemy.GetComponent <Enemy> (); playerLevel = player.GetComponent <PlayerLevel> (); LoadPlayerData(); //playerStats = player.GetComponent<PlayerStats> (); playerHUD.SetPlayerHUD(playerUnit); storeMobility = playerLevel.stats [4]; Debug.Log("Current player level: " + playerLevel.Level); Debug.Log("Player's HP when level is set: " + playerUnit.currentHP); playerUnit.attackList = new List <Attack> (); Attack trash = gameObject.AddComponent <Attack>(); trash.damage = 1; trash.type = "trash"; trash.name = "Dump"; trash.spCost = 3; trash.isSkill = true; Attack recycle = gameObject.AddComponent <Attack>(); recycle.damage = 1; recycle.type = "recycle"; recycle.name = "Shred"; recycle.spCost = 3; recycle.isSkill = true; Attack compost = gameObject.AddComponent <Attack>(); compost.damage = 1; compost.type = "compost"; compost.name = "Worm Strike"; compost.spCost = 3; compost.isSkill = true; playerUnit.addAttack(trash); playerUnit.addAttack(recycle); playerUnit.addAttack(compost); Debug.Log(playerUnit.attackList.Count); for (int i = 0; i < playerUnit.attackList.Count; i++) { GameObject newButton = Instantiate(skillPrefab, skillContent); Attack thisAttack = newButton.GetComponent <Attack>(); thisAttack.SetValue(playerUnit.attackList [i].damage, playerUnit.attackList [i].type, playerUnit.attackList [i].name, playerUnit.attackList [i].isSkill, playerUnit.attackList[i].spCost); newButton.GetComponentInChildren <Text> ().text = thisAttack.name; newButton.SetActive(true); print(thisAttack.type); } print(playerUnit.attackList.Count); dialogueText.text = enemyUnit.unitName + " is here to fight!"; playerUnit.unitLevel = playerLevel.Level; //passes in the information about player and enemy unit to set their hud displays playerHUD.SetPlayerHUD(playerUnit); enemyHUD.SetEnemyHUD(enemyUnit); //This waits a small amount of time before giving the dialogue to the player that they should choose an action yield return(new WaitForSeconds(2f)); //Attack: 0 //Defense: 1 //Skill: 2 //Technique: 3 //Mobility: 4 Debug.Log("Current Attack stat: " + playerLevel.stats[0]); Debug.Log("Current Defense stat: " + playerLevel.stats[1]); Debug.Log("Current Skill stat: " + playerLevel.stats[2]); Debug.Log("Current Technique stat: " + playerLevel.stats[3]); Debug.Log("Current Mobility stat: " + playerLevel.stats[4]); //Now the state is set to player's turn, and we move on to the PlayerTurn function if (playerLevel.stats [4] >= enemyUnit.stats [4]) { Debug.Log("Player attacks first"); state = BattleState.PLAYERTURN; PlayerTurn(); } else { state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); Debug.Log("Enemy attacks first"); } }
void ReceiveChangingTurn(int stoneType) { Debug.Log ("BattleController:ReceiveChangingTurn"); BattleManager.instance.turn = (StoneType)stoneType; this.state = BattleState.PrepareShowTurn; }
//Methods for each enemy's attacks IEnumerator wrapuchinAttacks() { //There is a lot of randomness in enemy attacks, so it needs to start with randomly picking between x enemy attacks System.Random getRandom = new System.Random(); //Wrapuchin has 2 attacks, so we will pick between those. int randomNum = getRandom.Next(1, 3); //IDLE if (randomNum == 1) { dialogueText.text = "Wrapuchin thinks about what it did"; yield return(new WaitForSeconds(2f)); state = BattleState.PLAYERTURN; PlayerTurn(); yield break; //ATTACK } else { //Flavor text dialogueText.text = "Wrapuchin swings towards you!"; //Determine hit chance System.Random hitRandom = new System.Random(); randomNum = hitRandom.Next(0, 101); int hitChance = 95 - (playerLevel.stats [4] - enemyUnit.stats [4]); if (hitChance < 50) { hitChance = 50; } //Determine if attack hits bool doesHit; if (randomNum < hitChance) { Debug.Log("Player hits!"); doesHit = true; } else { Debug.Log("Player misses :("); doesHit = false; } //If attack does not hit, inform player and then switch back to PLAYERTURN if (!doesHit) { yield return(new WaitForSeconds(2f)); dialogueText.text = "The attack missed!"; state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } int totalDamage = (enemyUnit.stats [0] * 2) - playerLevel.stats [1]; //If attack does hit, calculate damage if (totalDamage < 1 && isGuarding) { totalDamage = 0; } else if (isGuarding) { totalDamage = totalDamage / 2; Debug.Log("player is guarding"); } if (totalDamage < 1 & isGuarding == false) { totalDamage = 1; Debug.Log("Player is not guarding"); } Debug.Log("Total Enemy Damage by Wrapuchin: " + totalDamage); //Use this TakeDamage() function to deal the proper amount of damage to player bool isDead = playerUnit.TakeDamage(totalDamage); playerHUD.SetHP(playerUnit.currentHP); yield return(new WaitForSeconds(2f)); if (isDead) { state = BattleState.LOST; StartCoroutine(EndBattle()); yield break; } else { state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } } }
protected override IEnumerator moveToTarget(Vector3 target, BattleState.State nextState, IAbility ability, float optionalDelay = 0, float stopDist = 1.5F) { coroutines.moveToTarget = true; agent.ResetPath(); if (optionalDelay > 0) yield return new WaitForSeconds(optionalDelay); while (anim.GetCurrentAnimatorStateInfo(0).fullPathHash != animHash.getHash("idleState")) yield return null; while (!ability.moveToTarget(this.gameObject, target, stopDist)) { float moveSpeed = agent.velocity.magnitude; anim.SetFloat(animHash.getHash("moveSpeedFloat"), moveSpeed); yield return null; } agent.Stop(); agent.ResetPath(); anim.SetFloat(animHash.getHash("moveSpeedFloat"), 0.1f); state.setState(nextState); coroutines.moveToTarget = false; }
IEnumerator twocanAttacks() { //There is a lot of randomness in enemy attacks, so it needs to start with randomly picking between x enemy attacks System.Random getRandom = new System.Random(); int randomNum = getRandom.Next(1, 4); //IDLE: Jokes (: if (randomNum == 1) { randomNum = getRandom.Next(1, 11); String dialogue = "The twocan says, "; switch (randomNum) { case (1): dialogue += "'Hey calm down. There's no need to get emoceanal'"; break; case (2): dialogue += "'You need to work on getting out of your shell.'"; break; case (3): dialogue += "'It’s cool to get out of can school and meet all the alumni.'"; break; case (4): dialogue += "'Water you doing? I can’t sea how this helps you.'"; break; case (5): dialogue += "'Hey, I can see Seattle from here. We should sail further out.'"; break; case (6): dialogue += "'I can not believe I have two fight you.'"; break; case (7): dialogue += "'I’m gonna beach ya.'"; break; case (8): dialogue += "'This place is as big a dump as your mom’s house.'"; break; case (9): dialogue += "'It’s a good thing my material’s recyclable.'"; break; case (10): dialogue += "'I’ve seen better turtling playing Risk.'"; break; default: break; } dialogueText.text = dialogue; yield return(new WaitForSeconds(2f)); state = BattleState.PLAYERTURN; PlayerTurn(); yield break; //ATTACK } else if (randomNum == 2) { //Flavor text dialogueText.text = "The Twocan scratches off part of its label."; yield return(new WaitForSeconds(1f)); randomNum = getRandom.Next(1, 4); if (randomNum == 3) { dialogueText.text = "Something has made you sick. Every turn, you take damage equal to 5% of your max health, rounded down."; yield return(new WaitForSeconds(2f)); state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } else { dialogueText.text = "The Twocan punches down at you."; //Determine hit chance System.Random hitRandom = new System.Random(); randomNum = hitRandom.Next(0, 101); int hitChance = 95 - (playerLevel.stats [4] - enemyUnit.stats [4]); if (hitChance < 50) { hitChance = 50; } //Determine if attack hits bool doesHit; if (randomNum < hitChance) { Debug.Log("Twocan hits!"); doesHit = true; } else { Debug.Log("Twocan misses :("); doesHit = false; } //If attack does not hit, inform player and then switch back to PLAYERTURN if (!doesHit) { yield return(new WaitForSeconds(2f)); dialogueText.text = "The attack missed!"; state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } //If attack does hit, calculate damage int totalDamage = (enemyUnit.stats [0] * 2) - playerLevel.stats [1]; if (totalDamage < 1 && !isGuarding) { totalDamage = 1; } Debug.Log("Total Enemy Damage by Twocan: " + totalDamage); //Use this TakeDamage() function to deal the proper amount of damage to player bool isDead = playerUnit.TakeDamage(totalDamage); playerHUD.SetHP(playerUnit.currentHP); yield return(new WaitForSeconds(2f)); if (isDead) { state = BattleState.LOST; StartCoroutine(EndBattle()); yield break; } else { state = BattleState.PLAYERTURN; PlayerTurn(); yield break; } } }
/* Checks if any Entity is ready to play a tudrn and changes the battle state accordingly. NOTE: makes use of the property that the queue contains either characters or enemies. */ private void checkForTurn() { QueuedEntity head = turnQueue.peek(); if (head.Priority <= 0 && !(currentState == BattleState.CALCDAMAGE || currentState == BattleState.ENEMYTURN)) { /* Taking out an entity from the queue happens in checking turn. This reduces code cluttering and slightly increases speed, as we don't have to traverse all the turn queue list (this could change, as the list is very small (only 8 elements) */ if (head.entity.isDead()) { turnQueue.Dequeue(); } else { currentState = (head.entity is BaseCharacterClass) ? BattleState.PLAYERTURN : BattleState.ENEMYTURN; } } }
public PatrolStatus TickMovement(float dt) { Vector2 currentPos = transform.position; PathNode node = grid.NodeFromWorldPoint(currentPos); if (node != currentTile) { node.entitiesCurrentlyOnTile.Add(gameObject); if (node.entitiesCurrentlyOnTile.Count > 1) { foreach (GameObject obj in node.entitiesCurrentlyOnTile) { if (obj.GetComponent <Entity>().isPlayer&& !node.battling) { BattleState state = new BattleState(obj.GetComponent <Entity>(), boundEntity, gameManager, node); battleEntryScreen.Open(transform.position, boundEntity.soldierAmount, obj.GetComponent <Entity>().soldierAmount, state); gameManager.currentBattleState = state; gameManager.openMenuLockActions(transform.position); node.battling = true; } } } if (currentTile != null) { currentTile.entitiesCurrentlyOnTile.Remove(gameObject); } currentTile = node; } if (!usingPathfinding) { Vector2 sameZcheckpoint = currentCheckpoint; Vector2 sameZ = transform.position; if (Vector2.Distance(sameZ, sameZcheckpoint) > distanceToEnablePathfinding) { pathNodes = grid.FindPath(sameZ, sameZcheckpoint, boundEntity); pathNodes[pathNodes.Count - 1] = sameZcheckpoint; currentPathNodeIndex = 0; usingPathfinding = true; return(PatrolStatus.Ongoing); } else if (!sameZ.FuzzyEquals(sameZcheckpoint, 0.01f)) { Vector3 direction = sameZcheckpoint - sameZ; direction.z = 0; direction.Normalize(); GameWorld.Terrain currentTerrain = grid.NodeFromWorldPoint(transform.position).weight; if (currentTerrain == GameWorld.Terrain.Forest) { GetComponent <Entity>().SetHidden(true); } else { GetComponent <Entity>().SetHidden(false); } float movementModifier = boundEntity.terrainModifiers[currentTerrain] * boundEntity.pace * boundEntity.speed; Vector3 newPosition = transform.position + direction * movementModifier * gameManager.timeMultiplier * Time.deltaTime; transform.position = newPosition; return(PatrolStatus.Ongoing); } else { //REACHED THE DESTINATION return(PatrolStatus.Finished); } } else if (usingPathfinding) { Vector3 checkpointPosition = pathNodes[currentPathNodeIndex]; Vector2 sameZEnd = currentCheckpoint; Vector2 sameZCheckpoint = checkpointPosition; Vector2 sameZPlayer = transform.position; if (!sameZCheckpoint.FuzzyEquals(sameZPlayer, 0.025f)) { Vector2 direction2D = sameZCheckpoint - sameZPlayer; Vector3 direction = direction2D; direction.Normalize(); GameWorld.Terrain currentTerrain = grid.NodeFromWorldPoint(transform.position).weight; if (currentTerrain == GameWorld.Terrain.Forest) { GetComponent <Entity>().SetHidden(true); } else { GetComponent <Entity>().SetHidden(false); } float movementModifier = boundEntity.terrainModifiers[currentTerrain] * boundEntity.pace * boundEntity.speed; Vector3 newPosition = transform.position + direction * movementModifier * gameManager.timeMultiplier * Time.deltaTime; transform.position = newPosition; } else { transform.position = new Vector3(sameZCheckpoint.x, sameZCheckpoint.y, transform.position.z); if (currentPathNodeIndex + 1 <= pathNodes.Count - 1) { ++currentPathNodeIndex; } else { usingPathfinding = false; } } } return(PatrolStatus.Ongoing); }
internal virtual List <SpriteBase> GetTargets(BattleState battleState) { return(new List <SpriteBase>()); }
public void AddEvent(BattleEvent _event) { eventQueue.Add(_event); battleState = BattleState.DoingActions; }
void CommandValidationManagement(BattleCommandAction.commandActionType actionType) { switch(actionType) { case BattleCommandAction.commandActionType.attack: if (enemyList.Length > 0) selectedTarget = enemyList[0]; else selectedTarget = playerList[0]; battleState = BattleState.playerChoosingAtkTarget; break; case BattleCommandAction.commandActionType.skill: //Activer le menu skills SkillSelect(); break; case BattleCommandAction.commandActionType.summon: //Invoque les Gardiens en combat! break; case BattleCommandAction.commandActionType.defend: Debug.Log("DEFENSE!"); //Creer un defend factor pour le tour -> force*defendFactor pendant l'attaque, 0.5 ou 1, réinitialiser au début de chaque tour pour chaque perso, ennemi comme allié selectedPlayer.defending = true; break; case BattleCommandAction.commandActionType.escape: //Mettre fin au combat en fonction d'on ne sait pas encore quoi break; } }
void IdleUpdate() { if (eventQueue.Count > 0) { battleState = BattleState.DoingActions; return; } foreach (Battler i in activeBattlers) { // Check fainted if (i.isTargetable) { if (i.creature.currentHP <= 0) { AddEvent(new BE_Fainted(this, i)); return; } if (i.coolDown <= 0 && i.actionTime <= 0) { if (i.preparingAction == true && i.creature.currentEnergy >= Calc.EnergyCost(i, i.commandedAttack)) { BattlerTakeAction(i); battleState = BattleState.DoingActions;//CHANGE BATTLE STATE i.preparingAction = false; return; } } // // hp regen while (i.HPRestore >= 60) { i.creature.currentHP += 1; i.HPRestore -= 60; } // regen energy if (i.creature.currentEnergy < i.FinalStats.Energy && i.coolDown <= 0) { i.energyRestore += (i.creature.Stats.Energy * 0.05f) * 1; } while (i.energyRestore >= 60) { i.creature.currentEnergy += 1; i.energyRestore -= 60; } // action time if (i.actionTime > 0 && i.notOnCooldown) { i.actionTime -= 1; } // cooldown if (i.coolDown > 0) { i.coolDown -= 1; } } TotalBattleTime += 1; } foreach (BattleEffector i in BattleEffectors) { i.OnIdle(this); } }
IEnumerator Hit() { state = BattleState.PLAYERACTION; bool doesHit; //need to check for hit before we can determine damage System.Random getRandom = new System.Random(); int randomNum = getRandom.Next(0, 101); dialogueText.text = "You attack the enemy!"; int hitChance = 95 - (enemyUnit.stats [4] - playerLevel.stats [4]); if (hitChance < 50) { hitChance = 50; } if (randomNum < hitChance) { Debug.Log("Player hits!"); doesHit = true; } else { Debug.Log("Player misses :("); doesHit = false; } //If the player's attack misses, all we need to do is let them know and then proceed with the enemy's turn if (!doesHit) { yield return(new WaitForSeconds(2f)); dialogueText.text = "The attack missed!"; state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); } //On a hit, we need to start with calculating base damage for the attack //Uses this formula: (Your Attack * 2) - (Opponent Defense) to a minimum of 1. int totalDamage = (playerLevel.stats [0] * 2) - enemyUnit.stats [1]; if (totalDamage < 1) { totalDamage = 1; } bool isDead = enemyUnit.TakeDamage(totalDamage); enemyHUD.SetHP(enemyUnit.currentHP); //dialogueText.text = "You hit the enemy!"; yield return(new WaitForSeconds(2f)); //check if the enemy is dead //change state based on result if (isDead) { //End the battle state = BattleState.WON; StartCoroutine(EndBattle()); } else { //Enemy Turn state = BattleState.ENEMYTURN; StartCoroutine(EnemyTurn()); } }
static void Main() { //var MainGame = new MAAGame(); using (var games = new BattleState()) games.Run(); }