상속: MonoBehaviour
예제 #1
0
파일: AIManager.cs 프로젝트: hmason55/B
    public void CreateRandomEnemies()
    {
        // TEMP create a few enemies
        for (int i = 0; i < EnemyNumber; i++)
        {
            float      min   = Mathf.Max(Mathf.Lerp(0, EnemyPrefabs.Length - 3, _difficulty * 0.01f), 0);
            float      max   = Mathf.Min(Mathf.Lerp(3, EnemyPrefabs.Length, _difficulty * 0.01f), EnemyPrefabs.Length);
            GameObject go    = Instantiate(EnemyPrefabs[(int)Random.Range(min, max)]);
            EnemyUnit  enemy = go.GetComponent <EnemyUnit>();
            enemy.name += " (" + i + ")";
            _enemies.Add(enemy);

            int pos = Random.Range(9, 18);
            while (Battleground.Instance.GetUnitOnTile(pos) != null)
            {
                pos = Random.Range(9, 18);
            }
            Battleground bg = FindObjectOfType <Battleground>();
            bg.PlaceUnitAt(enemy, pos);

            //create UI
            CharacterUI UI = Instantiate(EnemyUIPrefab).GetComponent <CharacterUI>();
            enemy.AssignUI(UI);
            UI.SetEnemyTell(true);

            enemy.DealAnotherCard();
        }
    }
예제 #2
0
파일: Bullet.cs 프로젝트: ck7683/Solider
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.transform.name == "Enemy")
     {
         Transform tf = collision.transform;
         EnemyUnit eu = tf.GetComponent <EnemyUnit>();
         if (Random.Range(0, 6) == 0)
         {
             eu.Hit(dmgCritical);
         }
         else
         {
             eu.Hit(dmg);
         }
     }
     else if (collision.transform.name == "Player")
     {
         Transform  tf = collision.transform;
         PlayerUnit eu = tf.GetComponent <PlayerUnit>();
         if (Random.Range(0, 6) == 0)
         {
             eu.Hit(dmgCritical);
         }
         else
         {
             eu.Hit(dmg);
         }
     }
     op.Disable(gameObject);
 }
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.GetComponent <EnemyUnit>() != null)
        {
            EnemyUnit eu  = other.gameObject.GetComponent <EnemyUnit>();
            int       dir = Random.Range(0, 2);

            eu.GetComponent <Rigidbody>().velocity = Vector3.zero;
            eu.GetComponent <Rigidbody>().rotation = Quaternion.identity;

            if (eu != null)
            {
                if (dir == 0)
                {
                    eu.velocity.x = newDirection1.x * eu.speed;
                    eu.velocity.y = newDirection1.y * eu.speed;
                    eu.velocity.z = newDirection1.z * eu.speed;

                    eu.rotation.x = newRotation1.x;
                    eu.rotation.y = newRotation1.y;
                    eu.rotation.z = newRotation1.z;
                }
                else if (dir == 1)
                {
                    eu.velocity.x = newDirection2.x * eu.speed;
                    eu.velocity.y = newDirection2.y * eu.speed;
                    eu.velocity.z = newDirection2.z * eu.speed;

                    eu.rotation.x = newRotation2.x;
                    eu.rotation.y = newRotation2.y;
                    eu.rotation.z = newRotation2.z;
                }
            }
        }
    }
예제 #4
0
    // Use this for initialization
    void Start()
    {
        anim  = GetComponent <Animator> ();
        rbody = GetComponent <Rigidbody2D> ();
        Transform temp = GetComponent <Transform> ();

        startLocation.x = temp.position.x;
        startLocation.y = temp.position.y;
        gameObject.name = gameObjectPlayerName;

        interactionTriggerCollider           = gameObject.AddComponent <PolygonCollider2D> ();
        interactionTriggerCollider.pathCount = 1;
        thisEnemyUnit = gameObject.GetComponent <EnemyUnit> ();


        // create a polygon if we don't have one for collision triggering

        /*if (polygon == null)
         * {
         *      polygon = new Vector2[] {
         *              new Vector2 (0.00f, 1.5f),
         *              new Vector2 (-1.5f, -0.1f),
         *              new Vector2 (0.00f, -1.5f),
         *              new Vector2 (1.5f, -0.1f)
         *      };
         * }
         *
         * interactionTriggerCollider.points = polygon;
         * interactionTriggerCollider.isTrigger = true;*/
    }
예제 #5
0
    protected virtual void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Enemy" && !HitTarget)
        {
            switch (MoveDirection)
            {
            case E_MOVE_DIRECTION.DOWN:
                SoundManager.Instance.PlayImpact(true);
                break;

            case E_MOVE_DIRECTION.RIGHT:
                SoundManager.Instance.PlayImpact( );
                break;
            }

            HitTarget = true;
            if (SpawnImpact && ImpactEffect != null)
            {
                Quaternion randomRot = UnityEngine.Random.rotation;
                randomRot.x = randomRot.y = 0f;
                GameObject effect = Instantiate(ImpactEffect, transform.position, randomRot) as GameObject;
                Destroy(effect, 2.0f);
            }

            EnemyUnit enemy = other.GetComponent <EnemyUnit>( );
            if (enemy == null)
            {
                return;
            }

            enemy.ApplyDamage(Damage);
            Destroy(gameObject);
        }
    }
예제 #6
0
 public override void NextDestination(EnemyUnit e)
 {
     if (lastSawPlayer > 4)
     {
         SetNewIntriguePt(e);
     }
 }
예제 #7
0
    // Use this for initialization
    void Start()
    {
        spawnPoints = new List <Transform>(spawnPointsContainer.GetComponentsInChildren <Transform> ());
        spawnPoints.RemoveAt(0);

        deathSound = this.GetComponent <AudioSource> ();

        currentHealth = startingHealth;
        WaveSize      = 1;
        //EnemyClassList = new List<EnemyUnit>();
        int randomPick = Random.Range(0, spawnPoints.Count - 1);

        TotalCount = TotalCount + 1;

        CurentEnemy = new EnemyUnit();
        CurentEnemy.enemyInstance = Instantiate(myPrefab, spawnPoints[randomPick].position, spawnPoints[randomPick].rotation) as GameObject;
        CurentEnemy.enemyInstance.SetActive(true);
        CurentEnemy.tagName            = "Enemy" + TotalCount;
        CurentEnemy.enemyInstance.name = CurentEnemy.tagName;
        CurentEnemy.currentHealth      = currentHealth;
        CurentEnemy.maxHealth          = currentHealth;
        CurentEnemy.active             = true;

        CurentEnemy.enemyInstance.transform.position = spawnPoints [randomPick].position;
        EnemyClassList.Add(CurentEnemy);

        Vector2    direction = player.transform.position - CurentEnemy.enemyInstance.transform.position;
        float      angle     = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation  = Quaternion.AngleAxis(angle, Vector3.forward);

        CurentEnemy.enemyInstance.transform.rotation = rotation;
    }
예제 #8
0
 public ShootState(EnemyUnit owner)
     : base(owner, AIStateType.Shoot)
 {
     // Add transition back to Patrol and Follow Target.
     AddTransition(AIStateType.FollowTarget);
     AddTransition(AIStateType.Patrol);
 }
예제 #9
0
    // this method iterates through the entire storage of dead Units
    // it converts all of the Units that meet the conditions of the parameter function into EnemyUnits
    // it also removes the original Units from the graveyard and sends out the final converted EnemyUnits
    public void ConvertToEnemies(ConversionCondition comparator)
    {
        List <Unit> result = new List <Unit>();

        // iterate backwards through the units, because we may remove them as we go
        for (int i = deadUnits.Count - 1; i >= 0; i--)
        {
            // if the given conditions are met with this particular unit
            if (comparator(deadUnits[i]))
            {
                Debug.Log("Converting Unit " + deadUnits[i].GetName() + " at Location " + deadUnits[i].GetMapPosition() + " into EnemyUnit...");

                // Get references
                var        oldComponent  = deadUnits[i];
                GameObject unitToConvert = deadUnits[i].gameObject;

                // convert the GameObject: add an EnemyUnit component, transfer data over, and then delete the old component
                EnemyUnit newEnemyComponent = unitToConvert.AddComponent <EnemyUnit>() as EnemyUnit;
                UnitConversions.UnitToEnemy(oldComponent, newEnemyComponent);
                deadUnits.RemoveAt(i);
                Destroy(oldComponent);

                // put it away to return at the end
                result.Add(newEnemyComponent);
            }
        }
        // "I've made new enemies, if anyone wants them"
        NewEnemiesEvent.Invoke(result);
    }
    IEnumerator RunSequence()
    {
        mCanvas.SetActive(false);
        mCanvas.SetActive(false);
        while (CheckMoving())
        {
            yield return(null);
        }
        mCanvas.SetActive(true);
        mInMotion = false;
        mCamera.StartGameplayCamera();
        GameObject.Find("Enemies").GetComponent <EnemyController>().BuildMovement();

        // Fix hitboxes for player clicks
        foreach (GameObject FriendlyUnit in mFriendlyUnits)
        {
            if (FriendlyUnit != null)
            {
                FriendlyUnit.GetComponent <BoxCollider2D>().size  = new Vector2(.95f, .95f);
                FriendlyUnit.GetComponent <Movement>().mMoveCount = 0;
            }
        }

        foreach (GameObject EnemyUnit in mEnemyUnits)
        {
            if (EnemyUnit != null)
            {
                EnemyUnit.GetComponent <BoxCollider2D>().size  = new Vector2(.95f, .95f);
                EnemyUnit.GetComponent <Movement>().mMoveCount = 0;
            }
        }
    }
    private void UpdateUnitDisplay()
    {
        for (int i = 0; i < owner.playerUnits.Count; i++)
        {
            PlayerUnit unit = owner.playerUnits[i];
            if (unit.GetComponent <UnitStats>().IsDead())
            {
                owner.battleUI.Die(unit.GetComponent <UnitStats>().playerUnitInfo);
                owner.playerUnits.Remove(unit);
                unit.Die();
            }
        }

        for (int i = 0; i < owner.enemyUnits.Count; i++)
        {
            EnemyUnit unit = owner.enemyUnits[i];
            if (unit.GetComponent <UnitStats>().IsDead())
            {
                owner.enemyUnits.Remove(unit);
                unit.Die();

                board.DeselectForecast(unit.GetNextMove());
            }
        }
    }
예제 #12
0
 private void OnEnable()
 {
     unit                         = this.GetComponent <EnemyUnit>();
     rebirthAction                = this.GetComponentInChildren <IncarnateRebirthAttackAction>();
     animationStateUpdater        = this.GetComponentInChildren <AnimationStateUpdater>();
     EnemyUnit.EnemyWithTypeDied += EnemyDied;
 }
예제 #13
0
    public float judgeHeal(EnemyUnit judged, int healingOutput, float expectedHPC)
    {
        Debug.Log("Judging the dps performance of" + judged.name + ".");
        float maxChangeFactor = .15f;

        float curCost   = cTable.lookUp(judged.name);
        float maxChange = curCost * maxChangeFactor;

        float healingPerCredit = healingOutput / curCost;
        float extra            = (healingPerCredit - expectedHPC);
        float increaseAmt      = extra * maxChangeFactor * curCost;

        //Unit achieved or exceeeded value
        if (extra >= 0)
        {
            if (increaseAmt > maxChange)
            {
                cTable.raiseCost(judged, maxChange);
            }
            else
            {
                cTable.raiseCost(judged, increaseAmt);
            }
        }
        else
        {
            if (extra >= expectedHPC)
            {
                cTable.raiseCost(judged, maxChange);
            }
        }
        return(healingPerCredit / expectedHPC);
    }
    IEnumerator PlayerAtk1()
    {
        if (State == BattleState.PLAYERTURN)
        {
            atk1 = Random.Range(atk1Min, atk1Max);
            bool isDead = EnemyUnit.TakeDamage(atk1);
            //ACHIEVED MULTIPLE SOUNDS ON ONE SCRIPT!!
            GetComponent <AudioSource>().clip = Hit;
            GetComponent <AudioSource>().Play();
            enemyHUD.HP.text = EnemyUnit.currentHP.ToString();
            State            = BattleState.ENEMYTURN;
            //CombatLog.text += atk1.ToString() + "dmg dealt to enemy." + "\n";
            //CombatLog.color = Color.blue;
            UpdateCombatLog(atk1.ToString() + "dmg dealt to enemy.", Color.blue);
            EHalo.SetActive(false);
            PHalo.SetActive(true);
            yield return(new WaitForSeconds(2));

            if (isDead)
            {
                State = BattleState.WON;
                EHalo.SetActive(false);
                PHalo.SetActive(false);
                EndBattle();
            }

            else
            {
                StartCoroutine(EnemyTurn());
            }
        }
    }
예제 #15
0
    void Start()
    {
        //TODO: restart turn function that cleans this up a lot
        //Debug.Log("Started");
        if (firstMove)
        {
            GetAllPlayers();
            turnManager = GameObject.Find("Manager");
            dying       = false;
            attacksLeft = 1;
            //BuildZombieTree();
            myTf         = GetComponent <Transform> ();
            desiredCoord = myTf.position;
            myStats      = GetComponent <EnemyUnit> ();
            myMovement   = myStats.speed;
            speed        = ((float)myStats.speed) * SPEED_COEF;
            movesLeft    = myMovement;
            firstMove    = false;

            //Debug.Log (speed + " " + myStats.speed + " " + SPEED_COEF);

            movementCooldown = false;
        }
        MakeMove();
    }
예제 #16
0
    // Use this for initialization
    public void Start()
    {
        List <EnemyUnit> exploded = new List <EnemyUnit>();
        List <Unit>      list     = SlimePool.GetActiveSlimeList();

        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].element == Element.Fire)
            {
                Collider[] col = Physics.OverlapBox(list[i].transform.position, new Vector3(range / 2, 1, 1));
                for (int enemyIndex = 0; enemyIndex < col.Length; enemyIndex++)
                {
                    EnemyUnit e = col[enemyIndex].GetComponent <EnemyUnit>();
                    if (e != null)
                    {
                        if (allowMultihit)
                        {
                            exploded.Add(e);
                        }
                        else
                        {
                            if (!exploded.Contains(e))
                            {
                                exploded.Add(e);
                            }
                        }
                    }
                }
            }
        }
    }
예제 #17
0
        private void SetNewIntriguePt(EnemyUnit e)
        {
            GuardCommunication com = GuardCommunication.GetInstance();

            intriguePt    = com.getNewInvestigationPoint(e);
            lastSawPlayer = 2;
        }
예제 #18
0
    public void MoveUnit(Type type, Point curPoint, Point newPoint)
    {
        switch (type)
        {
        case Type.Envrionment:

            if (!EnvironmentCollection.ContainsKey(curPoint) || EnvironmentCollection.ContainsKey(newPoint))
            {
                Debug.LogError("[EnvironmentManager] Failed to set unit to new position");
                return;
            }

            EnviromentalUnit temp = EnvironmentCollection[curPoint];
            EnvironmentCollection.Remove(curPoint);
            EnvironmentCollection.Add(newPoint, temp);
            break;

        case Type.Enemy:

            if (!EnemyCollection.ContainsKey(curPoint) || EnemyCollection.ContainsKey(newPoint))
            {
                Debug.LogError("[EnvironmentManager] Failed to set unit to new position");
                return;
            }

            EnemyUnit enemyTemp = EnemyCollection[curPoint];
            EnemyCollection.Remove(curPoint);
            EnemyCollection.Add(newPoint, enemyTemp);
            break;

        default:
            break;
        }
    }
예제 #19
0
    /// <summary>
    /// Creates random units for the wave
    /// </summary>
    /// <param name="wave"></param>
    /// <param name="totalEnemies"></param>
    void CreateRandomWave(int level, int totalEnemies)
    {
        // Keeps track of stats built for a specific unit type so that
        // all units of that types share the same stats
        Dictionary <string, LevelUpMetada> levelData = new Dictionary <string, LevelUpMetada>();

        for (int i = 0; i < totalEnemies; i++)
        {
            // Select a random unit to create
            int       index = UnityEngine.Random.Range(0, m_baseUnits.Count);
            EnemyUnit unit  = BuildUnit(m_baseUnits[index].GetType().Name);

            if (unit != null)
            {
                // Because stats are initialized on unit creation with random base values
                // we want to zero them out so that each unit of the same type has the same values
                unit.Stats.SetStatsToZero();

                if (!levelData.ContainsKey(unit.name))
                {
                    levelData[unit.name] = unit.CreateLevelUp(level);
                }

                LevelUpMetada data = levelData[unit.name];
                unit.LevelUp(data);

                m_waveQueue.Enqueue(unit);
            }
        }
    }
예제 #20
0
 public Point getNewInvestigationPoint(EnemyUnit e)
 {
     // Dictionary<Point, double> dict = GetRandomPoints();
     // RankDictionary(dict, TacticsGrid.GetInstance().GetEntityPosition(e));
     // return SelectBest(dict);
     return(GetCompletelyRandomPoint());
 }
예제 #21
0
    // 查找目标敌人
    void FindEnemy()
    {
        if (targetEnemy != null)
        {
            return;
        }
        targetEnemy = null;
        int minlife = 0;                                                // 最低的生命值

        foreach (EnemyUnit enemy in NavalController.Instance.enemyList) // 遍历敌人
        {
            if (enemy.m_life == 0)
            {
                continue;
            }
            Vector3 pos1 = this.transform.position;
            pos1.y = 0;
            Vector3 pos2 = enemy.transform.position;
            pos2.y = 0;
            // 计算与敌人的距离
            float dist = Vector3.Distance(pos1, pos2);
            // 如果距离超过攻击范
            if (dist > attackArea)
            {
                continue;
            }
            // 查找生命值最低的敌人
            if (minlife == 0 || minlife > enemy.m_life)
            {
                targetEnemy = enemy;
                minlife     = enemy.m_life;
            }
        }
    }
예제 #22
0
    IEnumerator PlayerAtk2()
    {
        if (State == BattleState.PLAYERTURN)
        {
            int  hitChance = 45;
            bool isDead    = false;
            if (Random.Range(0, 100) <= hitChance)
            {
                int atk2 = Random.Range(5, 9);
                isDead = EnemyUnit.TakeDamage(atk2);
                //CombatLog.text = currentHP + "-" + dmg; idk tryna figure out the log
                enemyHUD.HP.text = EnemyUnit.currentHP.ToString();
                CombatLog.text  += atk2.ToString() + "dmg dealt to enemy." + "\n";
            }
            else
            {
                CombatLog.text += ("Attack missed!" + "\n");
            }

            State = BattleState.ENEMYTURN;
            yield return(new WaitForSeconds(2));

            if (isDead)
            {
                State = BattleState.WON;
                EndBattle();
            }

            else
            {
                StartCoroutine(EnemyTurn());
            }
        }
    }
 public void SetUp(Health parentHealth)
 {
     bodyUnit = GetComponent <EnemyUnit>();
     this.bodyUnit.Health.SetMaxHealth(parentHealth.GetTotalHealth());
     this.bodyUnit.Health.SetCurrentHealth(parentHealth.GetCurrentHealth());
     this.bodyUnit.Health = parentHealth;
 }
예제 #24
0
    private void Update()
    {
        EnemyUnit target = _targetFinder.EnemyTarget;

        if (target != null)
        {
            _lineRenderer.positionCount = 2;

            _lineRenderer.SetPositions(new Vector3[]
            {
                _spawnPoint.position,
                target.transform.position
            });
        }
        else
        {
            _lineRenderer.positionCount = 0;
        }

        _timer -= Time.deltaTime;

        if (_timer > 0f)
        {
            return;
        }

        _timer = _fireRate;

        if (target != null)
        {
            target.TakeDamage(Mathf.CeilToInt(_turretData.FireRate * _fireRate));
        }
    }
예제 #25
0
        private IEnumerator SetOrder()
        {
            yield return(new WaitForSeconds(enemyTurnInitialDelay));

            List <Unit> sorteredUnits = this.Units.OrderBy(u => ((EnemyUnit)u).Speed).ToList();

            foreach (var enemyUnit in sorteredUnits)
            {
                if (enemyUnit == null || enemyUnit.Health == null || enemyUnit.Health.IsDead() || enemyUnit.StructureType == StructureType.BODY_PART || enemyUnit.Health.GetTotalHealth() > 100 || !enemyUnit.gameObject.activeSelf)
                {
                    continue;
                }

                UnitSelected?.Invoke(this.SelectedUnit);
                this.UpdatePreviousUnit();
                this.SelectedUnit = enemyUnit;
                this.SelectedUnit.ChangeState(StateType.Selected);

                EnemyUnit enemy = (EnemyUnit)SelectedUnit;
                enemy.IdleFx?.Play(this.transform.position);
                yield return(new WaitForSeconds(idleDeltaTime));

                yield return(enemy.Execute(LevelManager.BoardController, LevelManager.GetBoard(TerrainSystem.TerrainNavigationType.BOTH)));

                yield return(new WaitForSeconds(this.deltaTime));
            }

            UnitSelected?.Invoke(null);
            this.EndTurn();
        }
예제 #26
0
    private void SpawnEnemies()
    {
        int difficulty = GameInformation.instance.GetLevelDifficulty();

        int currentDifficulty = 0;
        int numOfEnemies      = 0;

        while (currentDifficulty < difficulty && numOfEnemies < 6)
        {
            GameObject enemy = Instantiate(owner.enemyPrefab);

            int   index = Random.Range(0, enemyTiles.Count);
            Point p     = enemyTiles[index];
            enemyTiles.RemoveAt(index);

            EnemyUnit enemyUnit = enemy.GetComponent <EnemyUnit>();
            enemyUnit.Place(board.GetTile(p));

            EnemyUnitInfo enemyInfo = GameInformation.instance.GetRandomEnemy();
            enemyUnit.GetComponent <UnitStats>().SetEnemyInfo(enemyInfo);

            owner.enemyUnits.Add(enemyUnit);
            enemyUnit.Match();

            currentDifficulty += enemyInfo.difficulty;
            numOfEnemies++;
        }
    }
예제 #27
0
        private void AddToQueue(EEnemyType type, EnemyUnit unit, float prio = 0f)
        {
            var toAdd = new PrioritizableObject <EnemyUnit>(unit, prio);

            GetPrioritiyQueueByEnemyType(type).Add(toAdd);
            mAllUnits.Add(toAdd);
        }
예제 #28
0
 /// <summary>
 /// updates the enemy on display
 /// // currently unused
 /// </summary>
 public void UpdateEnemy()
 {
     if (updateUI.CheckForNewEnemy())
     {
         enemyUnit = GameObject.FindGameObjectWithTag("Enemy").GetComponent <EnemyUnit>();
     }
 }
예제 #29
0
    private void InitializeMegaBoss()
    {
        List <EnemyUnit> availableBosses = new List <EnemyUnit>();

        foreach (var bossObject in megaBosses)
        {
            var boss = bossObject.GetComponent <EnemyUnit>();

            if (boss.unitLevel <= playerUnit.unitLevel + 10)
            {
                availableBosses.Add(boss);
            }
        }

        int nextBossPos = Random.Range(0, availableBosses.Count);

        if (availableBosses[nextBossPos] == null)
        {
            InitializeMegaBoss();
            return;
        }
        else
        {
            enemyUnit = Instantiate(availableBosses[nextBossPos], enemyBattleStation.position, enemyBattleStation.rotation).GetComponent <EnemyUnit>();

            enemyUnit.InitializeBossSettings();

            enemyHUD.SetHP(enemyUnit.currentHP);
            enemyHUD.SetMP(enemyUnit.CurrentMP);
        }
    }
예제 #30
0
    //script name is enemyUnitFactory
    //Should buy more strong units on average but won't ignore worse deals entirely
    EnemyUnit testOfTimePick(ArrayList options)
    {
        int numberOfTrails = 5;         // FUDGE

        float[] sumOfValues = new float [options.Count];
        //Initialize the value table
        for (int i = 0; i < options.Count; i++)
        {
            sumOfValues [i] = 0f;
        }
        for (int i = 0; i < numberOfTrails; i++)
        {
            for (int j = 0; j < options.Count; j++)
            {
                int roll = Random.Range(0, unitPool.Count);
                sumOfValues[roll] += getUnitCreditEfficiency((EnemyUnit)options[roll]);                //Randomly pick a unit that can be purchased
            }
        }
        EnemyUnit winner       = new EnemyUnit();
        float     highestScore = 0f;

        for (int i = 0; i < options.Count; i++)
        {
            if (sumOfValues [i] > highestScore)
            {
                highestScore = sumOfValues [i];
                winner       = (EnemyUnit)options [i];
            }
        }
        Debug.Log(sumOfValues.ToString());

        Debug.Log("Winner is " + winner.name + " with a score of " + highestScore);
        return(winner);
    }
예제 #31
0
        //Revision: 3636
        //Author: zproxy
        //Date: 22. aprill 2012. a. 11:16:53
        //Message:

        //----
        //Added : /examples/java/OutRun4KTemplate
        //Added : /examples/java/OutRun4KTemplate/OutRun4KTemplate




        // http://www.digitalinsane.com/archives/2007/01/21/space_invaders/
        public SpaceInvaders()
        {

            ImageResources gfx = "http://server/";

            var overlay = new Overlay();

            overlay.BackgroundColor = Color.Black;
            overlay.MaximumOpacity = 1;
            overlay.ControlInBack.style.zIndex = 100000;
            overlay.ControlInFront.style.zIndex = 100001;


            var view = overlay.ControlInFront;

            view.style.textAlign = IStyle.TextAlignEnum.center;
            view.style.SetSize(480, 480);
            view.style.backgroundColor = Color.Green;
            view.style.color = Color.White;
            view.style.fontFamily = IStyle.FontFamilyEnum.Fixedsys;




            //Native.Document.body.appendChild(
            //    new IHTMLElement(IHTMLElement.HTMLElementEnum.center,
            //    view)
            //    );



            //Native.Document.body.style.backgroundColor = Color.Black;
            // Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;

            System.Func<IHTMLDiv> CreateCanvas =
                delegate
                {
                    var c = new IHTMLDiv();

                    c.style.overflow = IStyle.OverflowEnum.hidden;
                    c.style.SetLocation(1, 1, 478, 478);

                    return c;
                };

            view.style.position = IStyle.PositionEnum.relative;

            var canvas = CreateCanvas();
            var menu = CreateCanvas();

            canvas.style.backgroundColor = Color.Black;


            view.appendChild(canvas, menu);

            var msg_loading = new IHTMLDiv("loading...");

            msg_loading.style.color = Color.Green;

            menu.appendChild(msg_loading);

            // at this point we want our images

            overlay.Visible = true;

            ScriptCoreLib.JavaScript.Runtime.Timer.DoAsync(overlay.UpdateLocation);

            // now wait while all images are loaded/complete

            ((fbool)(() => !gfx.IsComplete)).Trigger(
            delegate
            {
                // loading images is done now.



                // build the scoreboard
                var MyEnemyDirectory = new EnemyDirectory(gfx);

                var board = new ScoreBoard(gfx);

                board.Control.style.SetLocation(8, 8, 464, 64);

                canvas.appendChild(board.Control);

                board.Lives = 2;
                board.Score = 450;

                // now we can see lives and score.
                // ie does not issue keypress for control keys.
                // scriptcorelib should filter firefox events...

                // lets show main menu

                var mmenu = new MainMenu(MyEnemyDirectory, gfx);
                var gameovermenu = new GameOverMenu();

                menu.appendChild(mmenu.Control, gameovermenu.Control);

                gameovermenu.Visible = false;
                gameovermenu.Control.style.SetLocation(0, 100, 468, 468 - 100);

                mmenu.Control.style.SetLocation(0, 64, 468, 468 - 64);
                mmenu.Visible = true;

                var Enemy_Ammo = new AmmoInfo
                                 {
                                     Color = Color.White,
                                     Speed = 8
                                 };

                var Player = (IHTMLImage)gfx.biggun.Clone();
                var Player_Ammo = new AmmoInfo
                                  {
                                      Color = Color.Green,
                                      Speed = -8
                                  };

                var Map_Top = 64;
                var Map_Left = 20;
                var Map_Right = 450;
                var Map_Bottom = 470;

                var Map_Rect = new Rectangle();

                Map_Rect.Top = Map_Top;
                Map_Rect.Left = Map_Left;
                Map_Rect.Right = Map_Right;
                Map_Rect.Bottom = Map_Bottom;

                var Player_Y = 460;
                var Player_X = 200;

                var Player_X_step = 8;

                Action<int> UpdatePlayer =
                    delegate(int v)
                    {
                        Player_X += v;

                        if (Player_X < Map_Left)
                            Player_X = Map_Left;

                        if (Player_X > Map_Right)
                            Player_X = Map_Right;


                        Player.SetCenteredLocation(Player_X, Player_Y);
                        Player.style.position = IStyle.PositionEnum.absolute;
                    };

                Player.Hide();

                canvas.appendChild(Player, Player_Ammo.Control, Enemy_Ammo.Control);

                AmmoInfo[] KnownAmmo = new[] { Player_Ammo, Enemy_Ammo };

                var KnownConcrete = new List<Concrete>();
                var ConcreteTop = 432;

                KnownConcrete.AddRange(Concrete.BuildAt(new Point(62 + 120 * 0, ConcreteTop)));
                KnownConcrete.AddRange(Concrete.BuildAt(new Point(62 + 120 * 1, ConcreteTop)));
                KnownConcrete.AddRange(Concrete.BuildAt(new Point(62 + 120 * 2, ConcreteTop)));
                KnownConcrete.AddRange(Concrete.BuildAt(new Point(62 + 120 * 3, ConcreteTop)));

                foreach (Concrete v in KnownConcrete.ToArray())
                {
                    canvas.appendChild(v.Control);
                }


                var UFO = new EnemyUnit(MyEnemyDirectory.UFO);
                var UFO_Direction = 1;

                UFO.Visible = false;

                canvas.appendChild(UFO.Control);


                var EnemyTop = 128;
                var EnemySpacing = 32;
                var EnemyCount = 9;

                var KnownEnemies = new List<EnemyUnit>();

                KnownEnemies.AddRange(EnemyUnit.Build(MyEnemyDirectory.A, 20, EnemyTop + 0 * EnemySpacing, EnemyCount, EnemySpacing));
                KnownEnemies.AddRange(EnemyUnit.Build(MyEnemyDirectory.B, 20, EnemyTop + 1 * EnemySpacing, EnemyCount, EnemySpacing));
                KnownEnemies.AddRange(EnemyUnit.Build(MyEnemyDirectory.B, 20, EnemyTop + 2 * EnemySpacing, EnemyCount, EnemySpacing));
                KnownEnemies.AddRange(EnemyUnit.Build(MyEnemyDirectory.C, 20, EnemyTop + 3 * EnemySpacing, EnemyCount, EnemySpacing));
                KnownEnemies.AddRange(EnemyUnit.Build(MyEnemyDirectory.C, 20, EnemyTop + 4 * EnemySpacing, EnemyCount, EnemySpacing));

                foreach (EnemyUnit v in KnownEnemies.ToArray())
                {
                    canvas.appendChild(v.Control);
                }

                var HitDamage = 40;

                var GameTimer = new ScriptCoreLib.JavaScript.Runtime.Timer();

                int GangDirection = 1;

                Action<string> EndGame =
                    delegate
                    {
                        gameovermenu.Visible = true;

                        GameTimer.Stop();
                    };

                #region DoAmmoDamage
                Func<AmmoInfo, bool> DoAmmoDamage =
                    delegate(AmmoInfo a)
                    {
                        bool hit = false;

                        #region did we hit ufo?
                        if (UFO.Visible)
                        {
                            if (UFO.Bounds.Contains(a.Location))
                            {
                                board.Score += UFO.Info.Points;

                                UFO.Visible = false;

                                hit = true;
                            }
                        }
                        #endregion

                        #region did we hit player
                        if (Player.Bounds.Contains(a.Location))
                        {
                            board.Lives--;

                            hit = true;

                            if (board.Lives < 1)
                            {
                                EndGame("Ship destroied");

                            }
                        }
                        #endregion


                        foreach (Concrete v in KnownConcrete.ToArray())
                        {
                            if (v.Visible)
                            {
                                if (v.Bounds.Contains(a.Location))
                                {
                                    v.Health -= HitDamage;

                                    if (v.Health > 0)
                                    {
                                        hit = true;
                                    }
                                    else
                                    {
                                        v.Visible = false;
                                    }
                                }
                            }
                        }

                        foreach (EnemyUnit v in KnownEnemies.ToArray())
                        {
                            if (v.Visible)
                            {
                                if (v.Bounds.Contains(a.Location))
                                {
                                    v.Visible = false;

                                    hit = true;
                                    new SpaceInvadersTemplate.HTML.Audio.FromAssets.invaderexplode().play();

                                    board.Score += v.Info.Points;
                                }
                            }
                        }



                        return hit;
                    };
                #endregion


                var MyRandom = new System.Random();

                var mothershiploop = new SpaceInvadersTemplate.HTML.Audio.FromAssets.mothershiploopx
                {

                    loop = true
                };


                var duh = new IHTMLAudio[] { 
                    new SpaceInvadersTemplate.HTML.Audio.FromAssets.duh0(),
                    new SpaceInvadersTemplate.HTML.Audio.FromAssets.duh1(),
                    new SpaceInvadersTemplate.HTML.Audio.FromAssets.duh2(),
                    new SpaceInvadersTemplate.HTML.Audio.FromAssets.duh3(),
                };

                var duh_cycle = duh.ToCyclicAction(a => a.play());


                #region EnemyAction
                Action EnemyAction =
                    delegate
                    {
                        #region create ufo

                        if (!UFO.Visible)
                        {
                            if (MyRandom.NextDouble() < 0.1)
                            {
                                Console.WriteLine("UFO!");
                                mothershiploop.play();

                                if (MyRandom.NextDouble() > 0.5)
                                {
                                    UFO_Direction = 1;
                                    UFO.MoveTo(0, EnemyTop - UFO.Control.height * 2);
                                }
                                else
                                {
                                    UFO_Direction = -1;
                                    UFO.MoveTo(478, EnemyTop - UFO.Control.height * 2);
                                }

                                UFO.Visible = true;
                            }
                        }
                        #endregion

                        var ev = Enumerable.Where(KnownEnemies.ToArray(), i => i.Visible);

                        if (!Enemy_Ammo.Visible)
                        {
                            var ei = (int)System.Math.Round(MyRandom.NextDouble() * Enumerable.Count(ev));

                            EnemyUnit et = Enumerable.ElementAt(ev, ei);

                            if (et == null)
                                System.Console.WriteLine("element at " + ei + " not found");
                            else
                            {
                                int ey = Enumerable.Max(
                                    from i in ev where i.X == et.X select i.Y
                                    //    Enumerable.Select(Enumerable.Where(ev, i => i.X == et.X), i => i.Y)
                                );

                                Enemy_Ammo.MoveTo(et.X, ey + 20);
                                Enemy_Ammo.Visible = true;
                            }
                        }


                        #region MoveAll
                        Action<Point> MoveAll =
                            delegate(Point to)
                            {
                                var ConcreteReached = false;

                                foreach (EnemyUnit v in ev)
                                {
                                    var vy = v.Y + to.Y;

                                    if (vy > ConcreteTop)
                                    {
                                        ConcreteReached = true;
                                    }

                                    v.MoveTo(v.X + to.X, vy);
                                }

                                if (ConcreteReached)
                                {
                                    EndGame("The walls have been breached.");
                                }
                            };
                        #endregion

                        Action MoveAllDown =
                            delegate
                            {
                                MoveAll(new Point(0, 8));
                            };

                        duh_cycle();

                        #region move the gang
                        if (GangDirection > 0)
                        {
                            int ex_max = Enumerable.Max(Enumerable.Select(ev, i => i.X));

                            // gang goes right

                            if (ex_max >= Map_Rect.Right)
                            {
                                GangDirection = -1;
                                MoveAllDown();
                            }
                            else
                            {
                                MoveAll(new Point(4, 0));
                            }
                        }
                        else
                        {
                            int ex_min = Enumerable.Min(Enumerable.Select(ev, i => i.X));

                            // gang goes left

                            if (ex_min <= Map_Rect.Left)
                            {
                                GangDirection = 1;
                                MoveAllDown();
                            }
                            else
                            {
                                MoveAll(new Point(-4, 0));
                            }
                        }
                        #endregion

                    };
                #endregion

                bool GamePaused = false;




                GameTimer.Tick +=
                    delegate
                    {

                        #region only blink while paused
                        if (GamePaused)
                        {
                            if (GameTimer.Counter % 15 == 0)
                            {
                                Player.ToggleVisible();
                            }

                            return;
                        }
                        #endregion



                        Player.Show();

                        #region move ufo

                        if (UFO.Visible)
                        {
                            if (UFO_Direction > 0)
                            {
                                UFO.MoveTo(UFO.X + 4, UFO.Y);

                                if (UFO.X > 478 + UFO.Control.width)
                                {
                                    UFO.Visible = false;
                                    mothershiploop.pause();
                                }
                            }
                            else
                            {
                                UFO.MoveTo(UFO.X - 4, UFO.Y);

                                if (UFO.X < -UFO.Control.width)
                                {
                                    UFO.Visible = false;
                                    mothershiploop.pause();
                                }
                            }
                        }
                        #endregion


                        #region do ammo stuff
                        foreach (AmmoInfo v in KnownAmmo)
                        {
                            if (v.Visible)
                            {
                                var y = v.Y + v.Speed;

                                if (Map_Rect.Contains(new Point(v.X, y)))
                                {
                                    // did we hit?
                                    if (DoAmmoDamage(v))
                                    {

                                        v.Visible = false;
                                    }
                                    else
                                    {
                                        v.MoveTo(v.X, y);
                                    }
                                }
                                else
                                {
                                    v.Visible = false;
                                }
                            }
                        }
                        #endregion



                        var AliveEnemies = Enumerable.Where(KnownEnemies.ToArray(), i => i.Visible);
                        var AliveCount = Enumerable.Count(AliveEnemies);

                        if (AliveCount == 0)
                        {
                            EndGame("Aliens destoried");

                            return;
                        }

                        if (GameTimer.Counter % (AliveCount / 2) == 0)
                        {
                            EnemyAction();
                        }

                    };


                #region ResetGame
                Action ResetGame =
                    delegate
                    {
                        mmenu.Visible = false;

                        Player_X = 220;
                        board.Score = 0;
                        board.Lives = 3;

                        Player.Show();

                        foreach (Concrete v in KnownConcrete.ToArray())
                        {
                            v.Health = 255;
                            v.Visible = true;
                        }


                        foreach (EnemyUnit v in KnownEnemies.ToArray())
                        {
                            v.ResetPosition();
                            v.Visible = true;
                        }

                        EnemyAction();

                        GameTimer.StartInterval(50);

                        UpdatePlayer(0);
                    };
                #endregion

                Action EgoShoot =
                    delegate
                    {
                        if (!Player_Ammo.Visible)
                        {
                            Player_Ammo.MoveTo(Player_X, Player_Y - 20);

                            new SpaceInvadersTemplate.HTML.Audio.FromAssets.firemissile().play();

                            Player_Ammo.Visible = true;

                        }
                    };

                overlay.ControlInBack.onclick +=
                    delegate
                    {
                        if (mmenu.Visible)
                            ResetGame();
                        else
                            EgoShoot();
                    };


                double gamma = 0;

                //Native.window.ondeviceorientation +=
                //    eventData =>
                //    {
                //        if (eventData.gamma < -50)
                //            gamma = eventData.beta;
                //        else
                //            gamma = eventData.gamma;


                //    };

                new ScriptCoreLib.JavaScript.Runtime.Timer(
                    t =>
                    {
                        // gamma is the left-to-right tilt in degrees, where right is positive
                        if (gamma < -15)
                        {
                            if (mmenu.Visible)
                                ResetGame();
                            else
                                UpdatePlayer(-Player_X_step);
                        }

                        if (gamma > 15)
                        {
                            if (mmenu.Visible)
                                ResetGame();
                            else
                                UpdatePlayer(Player_X_step);
                        }
                    }
                ).StartInterval(100);

                Native.Document.onkeydown += delegate(IEvent ev)
                {
                    Console.WriteLine(new { ev.KeyCode }.ToString());

                    if (mmenu.Visible)
                    {
                        if (ev.IsReturn)
                        {

                            ResetGame();

                        }

                        return;
                    }
                    else
                    {
                        if (ev.IsEscape)
                        {
                            GameTimer.Stop();

                            Player.Hide();

                            mmenu.Visible = true;

                            foreach (AmmoInfo v in KnownAmmo)
                            {
                                v.Visible = false;
                            }

                            foreach (Concrete v in KnownConcrete.ToArray())
                            {
                                v.Visible = false;
                            }

                            foreach (EnemyUnit v in KnownEnemies.ToArray())
                            {
                                v.Visible = false;
                            }

                            UFO.Visible = false;

                            gameovermenu.Visible = false;

                            // the animated gifs would stop after escape key
                            ev.preventDefault();

                            GamePaused = false;
                        }
                    }

                    int key_p = 80;


                    if (ev.KeyCode == key_p)
                    {
                        GamePaused = !GamePaused;
                    }

                    // player shouldn't really move while game is paused
                    // its cheating:)
                    if (GamePaused)
                        return;

                    int key_right = 39;
                    int key_left = 37;

                    if (ev.KeyCode == key_left)
                    {
                        UpdatePlayer(-Player_X_step);
                    }
                    else if (ev.KeyCode == key_right)
                    {
                        UpdatePlayer(Player_X_step);
                    }
                    else if (ev.IsSpaceOrEnterKey())
                    {
                        // the animated gifs would stop after escape key
                        ev.preventDefault();

                        EgoShoot();
                    }
                    else
                    {
                        Console.WriteLine(new { UnknownKeyCode = ev.KeyCode }.ToString());
                    }
                };

                msg_loading.Orphanize();
            }
            , 50);


        }
예제 #32
0
    // Use this for initialization
    void Start()
    {
        anim = GetComponent<EnemyAnimation>();
        status = GetComponent<EnemyUnit>();

        if (status == null) {
            Debug.LogError(gameObject.name + ".MeleeAI : No EnemyUnit script found");
            Application.Quit();
        }

        target = GameObject.Find ("Player");
        if (target == null) {
            Debug.LogError(gameObject.name + ".MeleeAI : No Player object found");
            Application.Quit();
        }
        pathfinder = GetComponent<NavMeshAgent> ();
        if (pathfinder == null) {
            Debug.LogError(gameObject.name + ".MeleeAI : No NavMeshAgent script found");
            Application.Quit();
        }

        pathfinder.enabled = true;

        // create aura
        aura = (GameObject)Instantiate(Resources.Load("Prefabs/EnemyAura"), transform.position, new Quaternion());
        aura.transform.parent = transform;

        var aura_script = aura.GetComponent<EnemyAttackAura>();
        aura_script.damage = GetComponent<Character>().damage;
        aura_script.SetAuraSize(aura_size);

        pathfinder.updateRotation = false;
    }
예제 #33
0
 public void setRightEnemy(EnemyUnit enemy)
 {
     currentRightEnemy = enemy;
     if (currentRightEnemy != null) {
         currentRightEnemy.setDirection ("left");
         currentRightEnemy.setTempEnemyStatus ("left");
     }
 }
예제 #34
0
            public static EnemyUnit[] Build(EnemyInfo info, int x, int y, int c, int s)
            {
                var a = new EnemyUnit[c];

                for (int i = 0; i < c; i++)
                {
                    var ke = new EnemyUnit(info);

                    var kx = x + s * i;
                    var ky = y;

                    ke.ResetPosition =
                        delegate
                        {
                            ke.MoveTo(kx, ky);
                        };

                    a[i] = ke;

                }

                return a;
            }
예제 #35
0
 public void setHeroDirection(string dir)
 {
     //currentEnemy = getCurrentEnemy(dir);
     currentHead.setDirection (dir);
     currentEnemy = getCurrentEnemy (dir);
 }
예제 #36
0
 public void setUpEnemy(EnemyUnit enemy)
 {
     currentUpEnemy = enemy;
     if (currentUpEnemy != null) {
         currentUpEnemy.setDirection ("down");
         currentUpEnemy.setTempEnemyStatus ("down");
     }
 }