public void PopulateWaterBlocks(params int[][] points)
        {
            GameContext.Map = new Map(10, 10);
            GameContext.Rules = new GameRules();

            var exploration = new MapExplorationManager();
            var turnResults = new TurnState();

            turnResults.Water.AddRange(points.Select(x => new TurnState.Point(x[0], x[1])));
            exploration.Process(turnResults);

            var water = (from row in Enumerable.Range(0, GameContext.Map.Rows)
                         from col in Enumerable.Range(0, GameContext.Map.Columns)
                         let tile = GameContext.Map.At(row, col)
                         where tile.State == TileState.Water
                         select tile
                        ).ToArray();

            Assert.AreEqual(points.Length, water.Length);

            var rawTiles = (from pt in points
                            select GameContext.Map.At(pt[0], pt[1])
                           ).ToArray();

            foreach (MapTile pt in water.Except(rawTiles))
                Assert.Fail("Point [{1},{0}] was not found in the result", pt.Column, pt.Row);

            foreach (MapTile source in water.Except(rawTiles))
                Assert.Fail("Point [{1},{0}] was not an expected result", source.Column, source.Row);
        }
        private IEnumerable<MapTile> FetchTilesWithFood(TurnState turnState)
        {
            Map map = GameContext.Map;

            return from r in turnState.Food
                   select map.At(r.Row, r.Column);
        }
        public void Process(TurnState turnState)
        {
            var foodQueue = new Queue<MapTile>();
            int radius = GameContext.ViewRadius*2;
            Func<MapTile, bool> isSuitable = tile => tile.CurrentAnt != null;

            foreach (MapTile foodTile in this.FetchTilesWithFood(turnState))
                foodQueue.Enqueue(foodTile);

            while (foodQueue.Count > 0)
            {
                MapTile foodTile = foodQueue.Dequeue();
                IEnumerable<MapRoute> routes = foodTile.DiscoverNearestRoutesTo(radius, isSuitable);

                foreach (MapRoute route in routes)
                {
                    Ant ant = route.Source.CurrentAnt;
                    var ev = new FoodItemSpottedEvent(route);

                    if (!ant.MovementStrategy.AcceptOverride(ev))
                        continue;

                    if (ev.OverridenTile != null)
                        foodQueue.Enqueue(ev.OverridenTile);

                    break;
                }
            }
        }
	void Start () {
		BSM = FindObjectOfType<BattleStateMachine>();
		isSelected = false;
		currentState = TurnState.INITIALIZING;
		startPosition = gameObject.transform.position;
		UpdateWeaponSprite();
	}
	void Update () {

		switch (currentState) 
		{
			case (TurnState.WAITING):
				//idle
				UpdateStaminaBar();
			break;
			case (TurnState.SELECTING):
				
			break;
			case (TurnState.INITIALIZING):
				BSM.survivorTurnList.Add (this.gameObject);
				currentState = TurnState.WAITING;
			break;
			case (TurnState.DONE):
				mySelectedIcon.SetActive(false);
				isSelected = false;
				BSM.playerGUI = BattleStateMachine.PlayerInput.ACTIVATE;
			break;
			case (TurnState.ACTION):
				StartCoroutine(TakeAction());
			break;
			case (TurnState.DEAD):

			break;

		}

	}
Esempio n. 6
0
        public CombatScreen()
        {
            ClearColor = Color.Black;
            _combatService = Rock.Instance.GetService<CombatOverwatchService>() as CombatOverwatchService;

            comState = CombatState.PreCombat;
            turState = TurnState.Waiting;

            delaySpan = new TimeSpan();

            //Menus:
            // 0 - main
            // 1 - skill
            // 2 - item
            // 3 - targeting
            // 4 - choose skill.attack
            menuPositions = new int[5];

            menuItems = new List<string[]>();
            menuItems.Add(new string[4] { "Std Melee", "Skills", "Items", "Flee" });
            menuItems.Add(new string[1] { "Cancel" });
            menuItems.Add(new string[1] { "Cancel" });
            menuItems.Add(new string[8] { "Enemy: Front", "Enemy: Left", "Enemy: Right", "Enemy: Back", "Team: Front", "Team: Left", "Team: Right", "Team: Back" });
            menuItems.Add(new string[1] { "IMessedUp" });
        }
        private static void PopulateWaterBlocks(TurnState turnState)
        {
            Map map = GameContext.Map;

            foreach (TurnState.Point point in turnState.Water)
                map.At(point.Row, point.Column).State = TileState.Water;
        }
	// Update is called once per frame
	void Update () {
		switch (currentState) 
		{
			case (TurnState.WAITING):
				//idle
			break;
			case (TurnState.CHOOSEACTION):
				ChooseAction();
				currentState = TurnState.WAITING;
			break;
			case (TurnState.TAKEACTION):
				StartCoroutine (TakeAction());
			break;
			case (TurnState.DEAD):
				if (GameManager.instance.zombiesToFight >= 6) {
					//kill me and refresh me.
					StartCoroutine(DeathAction(true));
				} else {
					//Kill me and do not refresh.
					StartCoroutine(DeathAction(false));
				}
			break;

		}
	}
	// Use this for initialization
	void Start () {
		myTargetGraphic.SetActive(false);
		startPosition = gameObject.transform.position;
		startRotation = gameObject.transform.rotation;
		spawnPoint = new Vector3 (startPosition.x + 2.5f, startPosition.y, startPosition.z);
		currentState = TurnState.WAITING;
		BSM = FindObjectOfType<BattleStateMachine>();
		myTypeText.text = zombie.zombieType.ToString();
	}
Esempio n. 10
0
 // setup variables
 public BattleEntity(Character character, BattleEntityDelegate listener)
 {
     mStatusEffectManager = new StatusEffectClient(this);
     mCombatNodeFactory = new CombatNodeFactory (this);
     mListener = listener;
     turnState = new TurnState(this);
     this.character = character;
     this.maxHP = character.maxHP;
     this.currentHP = character.curHP;
 }
Esempio n. 11
0
    private static void TurnStart()
    {
        for (int i = 0; i < factions[currentFactionTurn].Units.Count; ++i)
        {
            factions[currentFactionTurn].Units[i].BeginTurn();
        }
        currentState = TurnState.Actions;
        Debug.Log("Selecting a character");
        uiMan.SelectCharacter(factions[currentFactionTurn].Units[0]);

        TurnAction(); // We actually call turn action here because there's no reason to waste an update.
    }
Esempio n. 12
0
	// Update is called once per frame
	void Update () {
		if (turn == TurnState.TOMMYEND && NinjasDoneMoving())
		{
			EnemysTurn();
		}
		else if (turn == TurnState.ENEMY && NinjasDoneMoving())
		{
			TommysTurn();
		}
		else if (turn == TurnState.ENEMYSTART) 
		{
			turn = TurnState.ENEMY;
		}
	}
Esempio n. 13
0
    private static void TurnEnd()
    {
        for (int i = 0; i < factions[currentFactionTurn].Units.Count; ++i)
        {
            factions[currentFactionTurn].Units[i].EndTurn();
        }
        currentFactionTurn++;
        if (currentFactionTurn >= factions.Count)
        {
            currentFactionTurn = 0;
        }

        currentState = TurnState.TurnStart;
    }
    public void TakeDamage(int damageAmount)
    {
        BSM.ShowDamage(damageAmount);

        Player.currentHP -= damageAmount;

        if (Player.currentHP <= 0)
        {
            Player.currentHP = 0;
            currentTurnState = TurnState.DEAD;
        }

        UpdateHeroPanel();
    }
Esempio n. 15
0
 void OnTriggerStay(Collider other)
 {
     if(other.tag == "Player" && turnState == TurnState.readyToTurn)
     {
         turnState = TurnState.isTurning;
         Debug.Log("Turning...");
         if (direction == Direction.right)
             other.transform.Rotate(Vector3.up, 90, Space.Self);
         else if (direction == Direction.left)
             other.transform.Rotate(Vector3.up, -90, Space.Self);
         turnState = TurnState.hasTurned;
         Debug.Log("Turned.");
     }
 }
        private static void InferLandUsage(TurnState turnState)
        {
            Map map = GameContext.Map;
            int[] viewRadius = Enumerable.Range(1, GameContext.ViewRadius).ToArray();
            IEnumerable<MapTile> tiles = from pt in turnState.Ants
                                         where pt.Owner == 0
                                         let antTile = map.At(pt.Row, pt.Column)
                                         from vr in viewRadius
                                         from rangedTiles in antTile.CircleFromCenter(vr).Union(new[] {antTile})
                                         where rangedTiles.State == TileState.NotExplored
                                         select rangedTiles;

            foreach (MapTile mapTile in tiles)
                mapTile.State = TileState.Land;
        }
        public void Process(TurnState turnState)
        {
            this.EnsureIsInitialized();
            this.TurnDownHeatForEveryTileEverSeen();
            this.TurnHeatUpOnAllTilesWhichAntsAreOn(turnState);
            this.TurnHeatDownOnUnexploredEdges();

            //            var enemyAnts = from r in turnState.Ants
            //                            where r.Owner != 0
            //                            select GameContext.Map.At(r.Row, r.Column);
            //            ApplyGaussian(_enemyAntSpotted, enemyAnts);

            List<MapTile> tiles = FindColdestTiles();
            this.MoveAntsToColdestRegions(tiles);
        }
        public void EnsureMovesAreIssued()
        {
            var mock = new MockFactory();
            Mock<IGameOutputAdapter> outputAdapterMock = mock.CreateMock<IGameOutputAdapter>();

            outputAdapterMock.Expects.One.MethodWith(x => x.NotifyReady());
            outputAdapterMock.Expects.One.MethodWith(x => x.NotifyEndOfTurn());

            var gameManager = new GameManager(outputAdapterMock.MockObject);
            var turnResults = new TurnState();

            turnResults.Ants.Add(new TurnState.Point(3, 3));

            gameManager.RulesNotification(new GameRules {MapColumns = 10, MapRows = 10});
            gameManager.DoMoves(turnResults);

            mock.VerifyAllExpectationsHaveBeenMet();
        }
Esempio n. 19
0
    private void applyRules()
    {
        // Calculate and execute victorie or captures
        if ( victorie() )
        {
            pieces[18].die ();
            turnState = TurnState.ANIMATION; // ANIMATION
            return;
        }

        // Calculate captures and execute piece coroutine die()
        turnState = TurnState.END;
        int r = (int)currentPlayer.selectedPiece.coord.y;
        int c = (int)currentPlayer.selectedPiece.coord.x;
        if( c < 9 )		checkCapture ( board [r,c+1], board [r,c+2] );
        if( c > 1 )		checkCapture ( board [r,c-1], board [r,c-2] );
        if( r < 9 )		checkCapture ( board [r+1,c], board [r+2,c] );
        if( r > 1 )		checkCapture ( board [r-1,c], board [r-2,c] );

        currentPlayer.selectedPiece = null;
    }
        public void EnsureLandBeingMarked()
        {
            GameContext.Map = new Map(100, 100);
            GameContext.Rules = new GameRules
                                    {
                                        ViewRadiusSquared = 55
                                    };

            var exploration = new MapExplorationManager();
            var turnResults = new TurnState();

            turnResults.Ants.Add(new TurnState.Point(5, 5));
            exploration.Process(turnResults);

            var land = (from row in Enumerable.Range(0, GameContext.Map.Rows)
                         from col in Enumerable.Range(0, GameContext.Map.Columns)
                         let tile = GameContext.Map.At(row, col)
                         where tile.State == TileState.Land
                         select tile
                        ).ToArray();

            Assert.IsTrue(land.Length > 0);
        }
Esempio n. 21
0
    void InitializeScene()
    {
        // Remove any created items from last game and reset variables
        if (players != null)
        {
            foreach (var p in players)
            {
                Destroy(p.baseObject);
            }

            players = null;
        }

        playerTurnIndex = 0;
        turnState = TurnState.Starting;

        // Initialize references
        guiController = GetComponent<GUIController>();
        editorController = GetComponent<EditorController>();
        fileController = GetComponent<FileController>();

        // Add back editorController if it is not there (it was destoryed for performance )
        if (editorController == null)
        {
            editorController = gameObject.AddComponent<EditorController>();
        }

        blockPrefabs = new List<GameObject>();
        blockPrefabs.Add(GameObject.Find("PB_Square"));
        blockPrefabs.Add(GameObject.Find("PB_Hexagon"));
        blockPrefabs.Add(GameObject.Find("PB_Trapezoid"));
        blockPrefabs.Add(GameObject.Find("PB_Rhombus"));
        blockPrefabs.Add(GameObject.Find("PB_Triangle"));
        blockPrefabs.Add(GameObject.Find("PB_ThinRhombus"));

        blockImages = new List<Texture2D>();
        blockImages.Add((Texture2D)Resources.Load("Texture/FlatSquare"));
        blockImages.Add((Texture2D)Resources.Load("Texture/FlatHexagon"));
        blockImages.Add((Texture2D)Resources.Load("Texture/FlatTrapezoid"));
        blockImages.Add((Texture2D)Resources.Load("Texture/FlatRhombus"));
        blockImages.Add((Texture2D)Resources.Load("Texture/FlatTriangle"));
        blockImages.Add((Texture2D)Resources.Load("Texture/FlatThinRhombus"));

        mouseHelper = GetComponent<MouseHelper>();

        baseHolder = GameObject.Find("BaseHolder");
        factory = GameObject.Find("Factory");
        prefabBase = GameObject.Find("PB_Base");

        activeBaseMarker = GameObject.Find("ActiveBaseMarker");

        cameraObj = GameObject.Find("GameCamera");
        gameCamera = cameraObj.camera;
        radarCameraObj = GameObject.Find("RadarCamera");
        radarCamera = radarCameraObj.camera;
        SetRadarCameraVisible(false);

        shooter = GameObject.Find("Shooter");

        // Hide Factory
        if (hideFactory)
        {
            factory.transform.position = new Vector3(0, 100, 0);
        }
    }
Esempio n. 22
0
 public void SetState(TurnState state) => _text.text = state.ToString();
Esempio n. 23
0
    // Update is called once per frame
    void Update()
    {
        if (battleStarted)
        {
            if (!savePos)
            {
                startPos = transform.position;
                savePos  = true;
            }
            battle = GameObject.Find("BattleManager(Clone)").GetComponent <BattleStateMachine>();
        }
        switch (currentState)
        {
        case (TurnState.PROCESSING):
            updateProgressBar();
            break;

        case (TurnState.ADDTOLIST):
            battle.heroesToManage.Add(this.gameObject);
            currentState = TurnState.WAITING;
            break;

        case (TurnState.WAITING):

            break;

        case (TurnState.ACTION):
            StartCoroutine(timeForAction());
            break;

        case (TurnState.DEAD):
            if (!alive)
            {
                return;
            }
            else
            {
                Debug.Log("Hero is dead");
                //change tag
                this.gameObject.tag = "Dead Hero";
                //not attackable
                battle.heroes.Remove(this.gameObject);
                //not manageable
                battle.heroesToManage.Remove(this.gameObject);
                //reset gui
                //battle.ActionList.SetActive(false);
                gameManager.GetComponent <GameStates>().List.SetActive(false);
                //remove item from performList
                if (battle.heroes.Count > 0)
                {
                    for (int i = 0; i < battle.list.Count; i++)
                    {
                        if (battle.list[i].attacksGameObject == this.gameObject)
                        {
                            battle.list.Remove(battle.list[i]);
                        }

                        if (battle.list[i].attackersTarget == this.gameObject)
                        {
                            battle.list[i].attackersTarget = battle.heroes[Random.Range(0, battle.heroes.Count)];
                        }
                    }
                }

                //change color.play animation
                //this.gameObject.GetComponent<MeshRenderer>().material.color = new Color32(0,0,0,0);
                //reset hero input
                battle.battleState = BattleStateMachine.performAction.CHECKALIVE;
                alive         = false;
                battleStarted = false;
                savePos       = false;
            }
            break;
        }
    }
Esempio n. 24
0
 private void TurnEnd()
 {
     Debug.Log("[[Team Turn End]] Team: " +  this.CurrentTeam.Name);
     this.teamIndex = (this.teamIndex + 1) % this.teams.Count;
     this.turnState = TurnState.TurnBegin;
 }
 public void EndTurn(TurnState turnState)
 {
 }
Esempio n. 26
0
 void Start()
 {
     ReadMap();
     phase = TurnState.PLAYER;
 }
Esempio n. 27
0
    //creo un enumerator privato e lo chiamo TimeForAction
    private IEnumerator TimeForAction()
    {
        //controlle se l'azione è iniziata
        if (actionIsStarted)
        {
            //se lo è fermo tutto
            yield break;
        }
        //imposto actionIsStarted a true
        actionIsStarted = true;
        // imposto l'obbiettivo del Player sul Nemico da attaccare
        Vector3 EnemyPosition = new Vector3(enemyToAttack.transform.position.x + 10.5f, enemyToAttack.transform.position.y, enemyToAttack.transform.position.z + 5f);

        //imposto la boleana IsWalking a true
        anim.SetBool("IsWalking", true);
        //mi muovo verso il nemico
        while (MoveTowardEnemy(EnemyPosition))
        {
            yield return(null);
        }
        //imposto la boleana IsWalking a false
        anim.SetBool("IsWalking", false);
        // attivo il trigger IsAttacking
        anim.SetTrigger("IsAttacking");
        //aspetto un poco
        yield return(new WaitForSeconds(timeOfAnimation));

        // faccio danno
        DoDamage();
        // setto la posizioned del player alla posizione originale
        Vector3 firtPosition = startPosition;

        //imposto la boleana IsWalkingBack a true
        anim.SetBool("IsWakkingBack", true);
        // mi muovo verso la posizione originale
        while (MoveTowardStart(firtPosition))
        {
            yield return(null);
        }
        //imposto la boleana IsWalkingBack a false
        anim.SetBool("IsWakkingBack", false);
        // rimuovo questo performer dalla lista BSM
        Bsm.performList.RemoveAt(0);
        // controllo quando il bsm è diverso sia dalla perform action win che dalla perform action lose
        if (Bsm.BattleState != BatleStateMachine.PerformAction.Win && Bsm.BattleState != BatleStateMachine.PerformAction.Lose)
        {
            //resetto BSM in wait
            Bsm.BattleState = BatleStateMachine.PerformAction.Wait;
            //resetto lo stato del nemico
            curCoolDown = 0f;
            //cambio il currentState a Processing
            CurrentState = TurnState.Processing;
        }
        else
        {
            // cambio il current state a waiting
            CurrentState = TurnState.Waiting;
        }

        //finisco la coroutine
        actionIsStarted = false;
    }
Esempio n. 28
0
        public void Move(char[,] grid)
        {
            switch (grid[y, x])
            {
            case '-':
            case '|':
                MoveStraight();
                break;

            case '\\':
                switch (direction)
                {
                case Direction.Right:
                    TurnRight();
                    break;

                case Direction.Up:
                    TurnLeft();
                    break;

                case Direction.Down:
                    TurnLeft();
                    break;

                case Direction.Left:
                    TurnRight();
                    break;
                }
                break;

            case '/':
                switch (direction)
                {
                case Direction.Right:
                    TurnLeft();
                    break;

                case Direction.Up:
                    TurnRight();
                    break;

                case Direction.Down:
                    TurnRight();
                    break;

                case Direction.Left:
                    TurnLeft();
                    break;
                }
                break;

            case '+':
                switch (turnState)
                {
                case TurnState.Left:
                    TurnLeft();
                    turnState = TurnState.Straight;
                    break;

                case TurnState.Straight:
                    MoveStraight();
                    turnState = TurnState.Right;
                    break;

                case TurnState.Right:
                    TurnRight();
                    turnState = TurnState.Left;
                    break;
                }
                break;

            default:
                throw new Exception();
            }
        }
Esempio n. 29
0
    public int SpawnPlatforms()
    {
        int length = 0;

        for (int i = 0; i < 10; i++)
        {
            float  random = UnityEngine.Random.Range(0f, 100f);
            string name   = "";
            if (random <= 5f)
            {
                length = 4;
                if (nextZPosToSpawn > minZPosToFinish)
                {
                    Instantiate(endPlatform, transform.position + Vector3.forward * (nextZPosToSpawn + length / 2), Quaternion.identity);
                    return(-1);
                }
                else
                {
                    name = Constants.SHORT;
                }
            }
            else if (random <= 15f)
            {
                name   = Constants.LONG;
                length = 10;
            }
            else if (random <= 32f)
            {
                name   = Constants.MOVING;
                length = 4;
            }
            else if (random <= 49f)
            {
                name   = Constants.ROTATING;
                length = 10;
            }
            else if (random <= 66f)
            {
                name   = Constants.UPDOWN;
                length = 10;
            }
            else if (random <= 83f)
            {
                name   = Constants.SQUEEZING;
                length = 10;
            }
            else if (random <= 100f)     // TurnLeft/Right
            {
                name   = Constants.SHORT;
                length = 4;
                if (turnState == TurnState.None)
                {
                    if (random <= 91.5f)
                    {
                        turnState = TurnState.Left;
                    }
                    else
                    {
                        turnState = TurnState.Right;
                    }
                }
            }
            GameObject go = objectPooler.SpawnFromPool(name, transform.position + Vector3.forward * (nextZPosToSpawn + length / 2) + Vector3.right * nextXPosToSpawn, Quaternion.identity);
            if (turnState == TurnState.Left)
            {
                go.tag           = Tags.TURN_LEFT;
                nextXPosToSpawn -= 7;
                GameObject goLong = objectPooler.SpawnFromPool(Constants.LONG, new Vector3(nextXPosToSpawn, go.transform.position.y, go.transform.position.z), Quaternion.identity);
                goLong.transform.rotation = Quaternion.Euler(0f, -90f, 0f);
                nextXPosToSpawn          -= 7;
                GameObject goRight = objectPooler.SpawnFromPool(name, new Vector3(nextXPosToSpawn, go.transform.position.y, go.transform.position.z), Quaternion.identity);
                goRight.tag = Tags.TURN_RIGHT;
                turnState   = TurnState.None;
            }
            else if (turnState == TurnState.Right)
            {
                go.tag           = Tags.TURN_RIGHT;
                nextXPosToSpawn += 7;
                GameObject goLong = objectPooler.SpawnFromPool(Constants.LONG, new Vector3(nextXPosToSpawn, go.transform.position.y, go.transform.position.z), Quaternion.identity);
                goLong.transform.rotation = Quaternion.Euler(0f, 90f, 0f);
                nextXPosToSpawn          += 7;
                GameObject goLeft = objectPooler.SpawnFromPool(name, new Vector3(nextXPosToSpawn, go.transform.position.y, go.transform.position.z), Quaternion.identity);
                goLeft.tag = Tags.TURN_LEFT;
                turnState  = TurnState.None;
            }
            if (go.CompareTag(Tags.CHECKPOINT))
            {
                nextZPosToSpawn += 10;
            }
            else
            {
                nextZPosToSpawn += 4;
            }
        }
        return(nextZPosToSpawn - spawnDiff);
    }
Esempio n. 30
0
 void Start()
 {
     t_state = TurnState.IN_TURN;
 }
    // Update is called once per frame
    void Update()
    {
        switch (currentState)
        {
        case (TurnState.PROCESSING):
        {
            UpgradeProgressBar();

            break;
        }

        case (TurnState.CHOOSEACTION):
        {
            ChooseAction();
            currentState = TurnState.WAITING;

            break;
        }

        case (TurnState.WAITING):
        {
            //idle

            break;
        }

        case (TurnState.ACTION):
        {
            StartCoroutine(TimeForAction());

            break;
        }

        case (TurnState.DEAD):
        {
            if (!alive)
            {
                return;
            }
            else
            {
                //change tag
                this.gameObject.tag = "DeadEnemy";
                //not attackable
                BSM.EnemysInBattle.Remove(this.gameObject);
                //disable selector
                Selector.SetActive(false);
                //remove all inputs heroattks
                if (BSM.EnemysInBattle.Count > 0)
                {
                    for (int i = 0; i < BSM.PerformList.Count; i++)
                    {
                        if (BSM.PerformList[i].AttackersGameObject == this.gameObject)
                        {
                            BSM.PerformList.Remove(BSM.PerformList[i]);
                        }

                        if (BSM.PerformList[i].AttackersTarget == this.gameObject)
                        {
                            BSM.PerformList[i].AttackersTarget = BSM.EnemysInBattle[Random.Range(0, BSM.EnemysInBattle.Count)];
                        }
                    }
                }

                //chagnge color/play dead animations i guess
                this.gameObject.GetComponent <SpriteRenderer>().color = new Color32(105, 105, 105, 255);
                //set alive
                alive = false;
                //reset enemybuttons
                BSM.EnemyButtons();
                //check if battle is won/lost already
                BSM.battleStates = BattleStateMachine.PerformAction.CHECKALIVE;
            }

            break;
        }
        }
    }
Esempio n. 32
0
 /// <summary>
 ///     Register a player and his respective turn state.
 /// </summary>
 /// <param name="player"></param>
 /// <param name="state"></param>
 public void RegisterPlayerState(IPlayer player, TurnState state)
 {
     actorsRegister.Add(player, state);
 }
Esempio n. 33
0
    // Update is called once per frame
    void Update()
    {
        player.playing = playing;
        if (Input.GetKeyUp(KeyCode.P) || Input.GetKeyUp(KeyCode.Escape))
        {
            TogglePause();
        }

        //checking if level is complete
        int numEnemiesAlive = 0;

        foreach (EnemyScript enemy in enemies)
        {
            if (enemy.IsAlive)
            {
                numEnemiesAlive++;
            }
        }
        if (numEnemiesAlive <= 0)
        {
            if (SceneManager.GetActiveScene().name == "Dungeon_Level1")
            {
                SceneManager.LoadScene("Dungeon_Level2");
            }
            else
            {
                SceneManager.LoadScene("MainMenu");
            }
        }

        //swapping players and handling camera
        cam.player = player.gameObject;

        if (Input.GetButtonDown("Swap Characters"))
        {
            SelectNextPC();
        }
        selectedPlayer = playerCharacters.IndexOf(player);

        // -- ROUND STATES
        switch (State)
        {
        case RoundState.Player:

            // -- TURN STATES
            switch (turnState)
            {
            case TurnState.Character:

                if (player.Health <= 0)
                {
                    SceneManager.LoadScene("MainMenu");
                }
                turnState = TurnState.Action;
                break;

            case TurnState.Action:

                if (isDisplayingAttack)
                {
                    break;
                }

                if (playerPassTurn)
                {
                    turnState = TurnState.Result;
                }
                break;

            case TurnState.Result:

                turnState = TurnState.Character;
                State     = RoundState.Enemy;
                break;
            }
            break;

        case RoundState.Enemy:

            if (!isDisplayingAttack)
            {
                if (!enemiesMoved)
                {
                    foreach (EnemyScript enemy in enemies)
                    {
                        if (enemy.IsAlive)
                        {
                            enemy.AIMove();
                        }
                    }
                    enemiesMoved  = true;
                    enemiesMoving = true;
                }
                else if (enemiesMoving)
                {
                    int numMoving = 0;
                    foreach (EnemyScript enemy in enemies)
                    {
                        if (enemy.IsLerping)
                        {
                            numMoving++;
                        }
                    }
                    if (numMoving <= 0)
                    {
                        enemiesMoving    = false;
                        enemiesAttacking = true;

                        foreach (EnemyScript enemy in enemies)
                        {
                            if (enemy.IsAlive)
                            {
                                enemy.AIAttack();
                            }
                        }
                        State = RoundState.Reset;
                    }
                }
            }
            break;

        case RoundState.Reset:

            playerPassTurn = false;
            foreach (PlayerScript p in playerCharacters)
            {
                p.Moving      = false;
                p.usedAttack  = false;
                p.currentMove = 0;
                p.dodge       = p.startDodge;
            }

            enemiesMoved     = false;
            enemiesMoving    = false;
            enemiesAttacking = true;

            State = RoundState.Player;
            break;
        }

        // Disabling/Enabling Action Buttons
        // Move
        if (player.moveTotal - player.currentMove - 1 == 0)
        {
            buttons[0].interactable = false;
        }
        else
        {
            buttons[0].interactable = true;
        }
        // Attack
        if (player.usedAttack)
        {
            buttons[1].interactable = false;
            buttons[3].interactable = false;
        }
        else
        {
            buttons[1].interactable = true;
            buttons[3].interactable = true;
        }
        // Pass
        if (turnState == TurnState.Character)
        {
            buttons[2].interactable = false;
        }
        else
        {
            buttons[2].interactable = true;
        }
    }
Esempio n. 34
0
    // Update is called once per frame
    void Update()
    {
        //Handle 'esc' button for quit
        if (Input.GetKey("escape"))
        {
            gameState = GameState.Closing;
        }

        // Ensure sound keeps looping - Sometimes it stops randomly
        if (!audio.isPlaying)
        {
            audio.Play();
            Debug.Log("Sound was restarted!!");
        }

        if (gameState == GameState.Starting)
        {
            // Show Title
            if (!showTitleScreen ||
              guiController.ShowTitleScreen(3.0f) == GUIResult.Finished)
            {
                gameState = GameState.MainMenu;
            }
        }

        if (gameState == GameState.MainMenu)
        {
            var result = guiController.ShowMainMenu();

            if (result.isFinished)
            {
                switch (result.mainMenuAction)
                {
                    case MainMenuAction.NewGame:
                        gameState = GameState.LoadingNewGame;
                        newGameOptions = result.newGameOptions;
                        break;
                    case MainMenuAction.Close:
                    default:
                        gameState = GameState.Closing;
                        break;
                }
            }
        }

        if (gameState == GameState.LoadingNewGame)
        {
            // TEMP: Refactor this
            guiController.ShowNone();

            var options = newGameOptions;

            var humans = new List<int>();

            for (int i = 0; i < options.humanPlayerCount; i++)
            {
                humans.Add(i);
            }

            PerformanceController.PausePerformance();
            NewGame(options.humanPlayerCount + options.computerPlayerCount, humans);
            PerformanceController.ResetPerformance(0.5f);

            gameState = GameState.Editor;
        }

        if (gameState == GameState.Editor)
        {
            HandleCameraInputs();

            // Handle when editor is finished
            if (editorController.editorState == EditorState.Finished || !newGameOptions.shouldShowEditor)
            {
                editorController.FinishedIsHandled();

                PerformanceController.PausePerformance();

                // Disable editor for performance
                Destroy(editorController);

                CreateBasesIfEmpty();

                RemoveAllAligners();
                EnableBases();

                PerformanceController.ResetPerformance(1.0f);

                // Start Game Mode
                gameState = GameState.Playing;
            }
        }

        if (gameState == GameState.Playing)
        {
            SetRadarCameraVisible(true);

            var hasMoved = HandleCameraInputs();

            if (hasMoved)
            {
                hasCameraMovedForTurnState = true;
            }

            if (turnState == TurnState.Starting)
            {
                // Move camera
                var pos = players[playerTurnIndex].baseObject.transform.position;
                mouseHelper.MoveCameraToLookAtGroundPoint(pos.x, pos.z);

                // Move the ActiveBaseMarker
                activeBaseMarker.transform.position = pos;

                // TODO: Display Player Info
                Debug.Log("Turn = PlayerIndex " + playerTurnIndex);

                turnState = TurnState.Aiming;

                hitBaseIndex = -1;
            }

            if (turnState == TurnState.Aiming)
            {
                GameAction gameAction;

                if (players[playerTurnIndex].isHuman)
                {
                    // TODO: Allow player to shoot blocks only near base
                    gameAction = HandleGameInputs();
                }
                else
                {
                    // Computer Aiming
                    gameAction = ComputerAim();
                }

                if (gameAction == GameAction.PlayerShotBlock)
                {
                    turnState = TurnState.Shooting;
                }
                else if (gameAction == GameAction.None)
                {
                    // Do Nothing
                }
                else
                {
                    throw new System.Exception("Unknown GameAction: " + gameAction);
                }

            }

            if (turnState == TurnState.Shooting)
            {
                // Detect shooting block stop movement + Timeout
                var sController = shootingBlock.GetComponent<ShootingBlockController>();
                var isTurnFinished = sController.shootingBlockState == ShootingBlockState.Finished &&
                  Time.time - sController.finishedTime > endOfTurnTimeSpan;

                // Detect if has hit enemy base
                var pos = shootingBlock.transform.position;

                for (var iPlayer = 0; iPlayer < players.Count; iPlayer++)
                {
                    if (iPlayer == playerTurnIndex)
                    {
                        continue;
                    }

                    var player = players[iPlayer];
                    var pBase = player.baseObject;

                    if (!player.isAlive)
                    {
                        continue;
                    }

                    var bPos = pBase.transform.position;
                    var distance = Vector3.Distance(bPos, pos);
                    if (distance < blockHitBaseDistance)
                    {
                        hitBaseIndex = iPlayer;
                    }
                }

                if (sController.shootingBlockState != ShootingBlockState.Finished &&
                  !hasCameraMovedForTurnState)
                {
                    if (hitBaseIndex < 0)
                    {
                        // Follow the shooting block with the camera (while it is still moving)
                        mouseHelper.MoveCameraToLookAtGroundPoint(pos.x, pos.z);
                    }
                    else
                    {
                        // Move camera to base
                        var pBasePos = players[hitBaseIndex].baseObject.transform.position;
                        mouseHelper.MoveCameraToLookAtGroundPoint(pBasePos.x, pBasePos.z);
                    }
                }

                if (isTurnFinished)
                {
                    sController.FinishedIsHandled();
                    turnState = TurnState.Ended;
                }
            }

            if (turnState == TurnState.Ended)
            {
                // Detect End of Game (if only one human player is still active or all human players are inactive)
                // Or if no human players - then only one computer left
                var humanPlayerCount = 0;
                var humansAliveCount = 0;
                var computersAliveCount = 0;

                foreach (var p in players)
                {
                    if (p.isHuman)
                    {
                        humanPlayerCount++;

                        if (p.isAlive)
                        {
                            humansAliveCount++;
                        }
                    }
                    else
                    {
                        if (p.isAlive)
                        {
                            computersAliveCount++;
                        }
                    }
                }

                var playersAliveCount = humansAliveCount + computersAliveCount;

                if ((humansAliveCount == 0 && humanPlayerCount > 0) || playersAliveCount <= 1)
                {
                    Debug.Log("Players -> GameOver");
                    gameState = GameState.EndOfGameReport;
                }

                // Go to next alive player
                var origPlayer = playerTurnIndex;

                do
                {
                    playerTurnIndex++;

                    if (playerTurnIndex >= players.Count)
                    {
                        playerTurnIndex = 0;
                    }

                    if (playerTurnIndex == origPlayer)
                    {
                        // Game Over (only one player alive (or maybe none alive)) - This should be handled by above check
                        break;
                    }

                } while (!players[playerTurnIndex].isAlive);

                turnState = TurnState.Starting;
            }
        }

        if (gameState == GameState.EndOfGameReport)
        {
            SetRadarCameraVisible(false);

            var winnerName = "Nobody";
            var isWinnerHuman = false;
            var loserHumans = new List<string>();

            foreach (var p in players)
            {
                if (p.isAlive)
                {
                    winnerName = p.name;
                    isWinnerHuman = p.isHuman;
                }
                else
                {
                    if (p.isHuman)
                    {
                        loserHumans.Add(p.name);
                    }
                }

            }

            var reportInfo = new EndOfGameInfo(winnerName, isWinnerHuman, loserHumans.ToArray());

            if (guiController.ShowEndOfGameReport(reportInfo, 5.0f) == GUIResult.Finished)
            {
                gameState = GameState.MainMenu;
            }
        }

        if (gameState == GameState.Closing)
        {
            Application.Quit();
        }
    }
 public DuelState(string id, DuelistState firstDuelist, DuelistState secondDuelist, TurnState turn)
 {
     Id            = id;
     FirstDuelist  = firstDuelist;
     SecondDuelist = secondDuelist;
     Turn          = turn;
 }
Esempio n. 36
0
    // Update is called once per frame
    void Update()
    {
        // creo uno switch che mi permette di cambiare fra i vari turnState
        switch (CurrentState)
        {
        //creo il primo caso
        case (TurnState.Processing):
            //dentro processing chiamo la funzione UpgradeProgressBar
            UpgradeProgressBar();
            //creo un break per fermare il caso 1
            break;

        //creo il secondo caso
        case (TurnState.AddToList):
            //aggiungo il gameObject a cui è assegnato lo script a heroToManage della classe BatleStateMachine
            Bsm.HeroToManage.Add(this.gameObject);
            //inposto lo stato a waiting
            CurrentState = TurnState.Waiting;
            break;

        case (TurnState.Waiting):
            //idle
            break;

        case (TurnState.Action):
            //faccio iniziare la couroutine e inserisco l'enumerator TimeForAction
            StartCoroutine(TimeForAction());
            break;

        case (TurnState.Dead):
            //controllo se non è isAlive
            if (!IsAlive)
            {
                return;
            }
            // se il personaggio è morto
            else
            {
                //cambia tag
                this.gameObject.tag = "DeadHero";
                //elimino il gameObject dalla lista herosInGame cosi da non farlo attaccare dai nemici
                Bsm.HerosInGame.Remove(this.gameObject);
                //elimino il gameObject dalla lista HeroToManage cosi da non poterlo più utilizzare
                Bsm.HeroToManage.Remove(this.gameObject);
                // disativazione del selector
                Selector.SetActive(false);
                //resetto hud inpostando l'attacPanel a false e il selector a false
                Bsm.AttackPanel.SetActive(false);
                Bsm.EnemySelectPanel.SetActive(false);
                //creo un if che controlla se gli HerosInGame sono maggiori di 0
                if (Bsm.HerosInGame.Count > 0)
                {
                    //se lo sono rimuovioamo gli ogetti dalla performList
                    for (int i = 0; i < Bsm.performList.Count; i++)
                    {
                        //controllo se i è diverso da 0
                        if (i != 0)
                        {
                            //controlliamo se in questo momento stiamo attaccando con quel personaggio
                            if (Bsm.performList[i].AttacksGameObject == this.gameObject)
                            {
                                //rimuovo il personaggio dalla Perform list così attaccheremo con l'altro
                                Bsm.performList.Remove(Bsm.performList[i]);
                            }
                            // controlle se il nostro personaggio appena morto era stato selezionato come target di un attacco
                            if (Bsm.performList[i].AttacksTarget == this.gameObject)
                            {
                                //reindirizzo il nemico ad un altro giocatore a caso
                                Bsm.performList[i].AttacksTarget = Bsm.HerosInGame[Random.Range(0, Bsm.HerosInGame.Count)];
                            }
                        }
                    }
                }

                //attiva animazione di morte
                this.gameObject.GetComponent <MeshRenderer>().material.color = new Color32(105, 105, 105, 255);
                //reste heroInput
                Bsm.BattleState = BatleStateMachine.PerformAction.CheckAlive;
                //inposto isAlive a false
                IsAlive = false;
            }
            //finisco il caso con un break
            break;
        }
    }
	IEnumerator TakeAction () {
		if (actionStarted) {
			yield break;
		} else {
			actionStarted = true;
			//match the sprite layer to that of the target
			int startRenderLayer = gameObject.GetComponent<SpriteRenderer>().sortingOrder;


			if (survivor.weaponEquipped != null){
				//attack with a weapon
				BaseWeapon myWeapon = survivor.weaponEquipped.GetComponent<BaseWeapon>();


				//animate the hero to the target, unless you have a gun equipped and at least 1 bullet
				if (myWeapon.weaponType == BaseWeapon.WeaponType.KNIFE || myWeapon.weaponType == BaseWeapon.WeaponType.CLUB || GameManager.instance.ammo < 1) {
					Vector3 targetPosition = new Vector3 (plyrTarget.transform.position.x - 0.3f, plyrTarget.transform.position.y, plyrTarget.transform.position.z);
					gameObject.GetComponent<SpriteRenderer>().sortingOrder = plyrTarget.GetComponent<SpriteRenderer>().sortingOrder;
					while (MoveTowardsTarget(targetPosition)) {yield return null;}
				}
				//animate weapon fx
				yield return new WaitForSeconds(0.2f);

				//do damage
				ZombieStateMachine targetZombie = plyrTarget.GetComponent<ZombieStateMachine>();
				int myDmg = CalculateMyDamage();
				Debug.Log ("Survivor hit the zombie for " +myDmg+ " damage");
				targetZombie.zombie.curHP = targetZombie.zombie.curHP - myDmg;
				targetZombie.CheckForDeath();
				StartCoroutine(SendAttackToServer(survivor.survivor_id, myWeapon.weapon_id));
				UpdateStaminaBar();
				if (survivor.weaponEquipped != null) {
					survivor.curStamina -= myWeapon.stam_cost;	
				}
				//Record the durability loss
				myWeapon.durability = myWeapon.durability - 1;
				if (myWeapon.durability < 1) {
					Destroy(survivor.weaponEquipped.gameObject);
					UpdateWeaponSprite();
					Debug.Log("oh noes! weapon is broken beyond repair!");
				}
			} else {
				//unequipped weapon attack.
				Vector3 targetPosition = new Vector3 (plyrTarget.transform.position.x - 0.3f, plyrTarget.transform.position.y, plyrTarget.transform.position.z);
				gameObject.GetComponent<SpriteRenderer>().sortingOrder = plyrTarget.GetComponent<SpriteRenderer>().sortingOrder;
				while (MoveTowardsTarget(targetPosition)) {yield return null;}

				//animate weapon fx
				yield return new WaitForSeconds(0.2f);

				//do damage
				ZombieStateMachine targetZombie = plyrTarget.GetComponent<ZombieStateMachine>();
				int myDmg = CalculateMyDamage();
				Debug.Log ("Survivor hit the zombie for " +myDmg+ " damage");
				targetZombie.zombie.curHP = targetZombie.zombie.curHP - myDmg;
				targetZombie.CheckForDeath();
				StartCoroutine(SendAttackToServer(survivor.survivor_id, 0));
				UpdateStaminaBar();

			}
			//return to start position, gun shots should already be there.
			while (MoveTowardsTarget(startPosition)) {yield return null;}
			//remove from list
			BSM.TurnList.RemoveAt(0);


			//reset BSM ->
			BSM.battleState = BattleStateMachine.PerformAction.WAIT;

			gameObject.GetComponent<SpriteRenderer>().sortingOrder = startRenderLayer;
			actionStarted = false;
			currentState = TurnState.DONE;
		}
		
	}
Esempio n. 38
0
 public void EndPlayerRage()
 {
     currentTurnState = TurnState.ProgressionTurn;
     StartCoroutine("BetweenTurnsCoroutine");
 }
 public void StartTurn(TurnState turnState)
 {
     canFire    = !cooldown;
     cooldown   = false;
     fireTarget = null;
 }
Esempio n. 40
0
 public Pool()
 {
     _currentPlayer = PlayerIndex.One;
     _turnState = TurnState.SHOOTING;
     _gameState = GameState.MENU;
     _menuState = MenuState.HOME;
     graphics = new GraphicsDeviceManager(this);
     graphics.PreferredBackBufferWidth = 1280;
     graphics.PreferredBackBufferHeight = 720;
     IsFixedTimeStep = true;
     TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 10);
     IsMouseVisible = true;
     Content.RootDirectory = "Content";
 }
Esempio n. 41
0
    private void TurnBegin()
    {
        var curTeam = this.CurrentTeam;
        Debug.Log("[[Team Turn Begin]] Team: " + curTeam.Name);

        if (this.turnLabel == null)
        {
            this.turnLabel = new FLabel("courier", "Current Team: " + curTeam.Name);
            this.turnLabel.x = 250;
            this.turnLabel.y = 50;
            this.turnLabel.color = Color.black;
            this.hud.AddChild(this.turnLabel);
        }
        else
        {
            this.turnLabel.text = "Current Team: " + curTeam.Name;
        }

        this.teamActorCount = curTeam.Members.Count;
        this.actorsProcessedThisTurn = 0;
        foreach (var actor in this.Map.Actors.Where(a => a.Team == curTeam))
        {
            actor.TurnState = ActorState.CommandsAvailable;
            foreach (var ability in actor.Properties.AllAbilities)
            {
                ability.DecrementCooldown();
            }
        }

        this.turnState = TurnState.TurnMiddle;
    }
    void OnStateStart(TurnState newState)
    {
        switch (newState)
        {
        case TurnState.choosePlayer:
            CurrentTurnState = TurnState.placing;
            break;

        case TurnState.placing:
            CurrentPlayerTurn = PlayerTurn.Curve_Turn;
            FindObjectOfType <Camera> ().transform.localPosition = CameraPosition;
            NewUIManager.Instance.ChangeText("Preparation phase: Place two robots!");
            NewUIManager.Instance.TutorialBoxSummon();
            RobotManager.Instance.RobotsQuadratiInHand = RobotManager.Instance.Draw(RobotManager.Instance.RobotQuadratiInHand, RobotManager.Instance.RobotQuadrati, RobotManager.Instance.RobotsQuadratiInHand, Player.Player_Quad);
            break;

        case TurnState.rotation:
            NewUIManager.Instance.Slots.SetActive(false);
            NewUIManager.Instance.DoubleRotation.SetActive(true);
            NewUIManager.Instance.DoubleUpgrade.SetActive(false);
            NewUIManager.Instance.Rotation_Buttons.SetActive(true);
            NewUIManager.Instance.ChangeText("Rotation phase: Rotate your grids!");
            NewUIManager.Instance.TutorialBoxSummon();
            RobotManager.Instance.SetGraphicAsParent();
            ArrowManager.Instance.Frecce.SetActive(false);
            NewUIManager.Instance.GridButtons.SetActive(false);
            ButtonManager.Instance.CurveGridClockwiseButton.gameObject.SetActive(true);
            ButtonManager.Instance.CurveGridCounterclockwiseButton.gameObject.SetActive(true);
            ButtonManager.Instance.QuadGridClockwiseButton.gameObject.SetActive(true);
            ButtonManager.Instance.QuadGridCounterclockwiseButton.gameObject.SetActive(true);
            if (isCurveRotationTurn)
            {
                ButtonManager.Instance.CurveGridClockwiseButton.transform.Rotate(0f, 180f, 180f);
                ButtonManager.Instance.CurveGridCounterclockwiseButton.transform.Rotate(0f, 180f, 180f);
                ButtonManager.Instance.QuadGridClockwiseButton.transform.Rotate(0f, 180f, 0f);
                ButtonManager.Instance.QuadGridCounterclockwiseButton.transform.Rotate(0f, 180f, 0f);
                NewUIManager.Instance.RB_Button_Curve_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.LT_Button_Curve_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.RT_Button_Curve_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.LB_Button_Curve_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.RB_Button_Quad_Turn.gameObject.SetActive(false);
                NewUIManager.Instance.LT_Button_Quad_Turn.gameObject.SetActive(false);
                NewUIManager.Instance.RT_Button_Quad_Turn.gameObject.SetActive(false);
                NewUIManager.Instance.LB_Button_Quad_Turn.gameObject.SetActive(false);
                JoystickManager.Instance.IsDoubleRotationActive = false;
                isCurveRotationTurn = false;
            }
            else if (!isCurveRotationTurn)
            {
                ButtonManager.Instance.CurveGridClockwiseButton.transform.Rotate(0f, 180f, 180f);
                ButtonManager.Instance.CurveGridCounterclockwiseButton.transform.Rotate(0f, 180f, 180f);
                ButtonManager.Instance.QuadGridClockwiseButton.transform.Rotate(0f, 180f, 0f);
                ButtonManager.Instance.QuadGridCounterclockwiseButton.transform.Rotate(0f, 180f, 0f);
                NewUIManager.Instance.RB_Button_Quad_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.LT_Button_Quad_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.RT_Button_Quad_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.LB_Button_Quad_Turn.gameObject.SetActive(true);
                NewUIManager.Instance.RB_Button_Curve_Turn.gameObject.SetActive(false);
                NewUIManager.Instance.LT_Button_Curve_Turn.gameObject.SetActive(false);
                NewUIManager.Instance.RT_Button_Curve_Turn.gameObject.SetActive(false);
                NewUIManager.Instance.LB_Button_Curve_Turn.gameObject.SetActive(false);
                JoystickManager.Instance.IsDoubleRotationActive = false;
                isCurveRotationTurn = true;
            }
            break;

        case TurnState.battle:
            NewUIManager.Instance.Rotation_Buttons.SetActive(false);
            NewUIManager.Instance.DoubleRotation.SetActive(false);
            ButtonManager.Instance.Skip_Turn.gameObject.SetActive(false);
            JoystickManager.Instance.DoubleRotationAlreadyActivated = false;
            if (_currentPlayerTurn == PlayerTurn.Curve_Turn)
            {
                FindObjectOfType <Camera> ().GetComponentInParent <Animator> ().Play("BattleCameraFirstPlayer");
                NewUIManager.Instance.Segnapunti.GetComponent <Animator>().Play("Punteggio_Curve_Start_Curve_Turn");
                NewUIManager.Instance.Segnapunti.GetComponent <Animator>().Play("Punteggio_Quad_Start_Curve_Turn");
                GameManager.isSomeAnimationGoing = true;
                ChangeTurn();
            }
            else
            {
                if (RobotManager.Instance.RobotsCurviInHand == 2 && RobotManager.Instance.RobotsQuadratiInHand == 2 && RobotManager.Instance.RobotCurvi.Count == 0 && RobotManager.Instance.RobotQuadrati.Count == 0)
                {
                    RobotManager.Instance.LastBattle = true;
                }
                FindObjectOfType <Camera> ().GetComponentInParent <Animator> ().Play("BattleCameraSecondPlayer");
                NewUIManager.Instance.Segnapunti.GetComponent <Animator>().Play("Punteggio_Curve_Start_Quad_Turn");
                NewUIManager.Instance.Segnapunti.GetComponent <Animator>().Play("Punteggio_Quad_Start_Quad_Turn");
                GameManager.isSomeAnimationGoing = true;
                ChangeTurn();
            }
            break;

        case TurnState.upgrade:
            if (isFirstUpgradeTurn)
            {
                ArrowManager.Instance.ActiveAllArrows();
                isFirstUpgradeTurn = false;
            }
            switch (RemainingTurns)
            {
            case 3:
                RemainingTurnsText = "Remaining turns: 3";
                break;

            case 2:
                RemainingTurnsText = "Remaining turns: 2";
                break;

            case 1:
                RemainingTurnsText = "Last turn!";
                break;

            default:
                break;
            }
            ArrowManager.Instance.Frecce.SetActive(true);
            NewUIManager.Instance.GridButtons.SetActive(true);
            NewUIManager.Instance.DoubleUpgrade.SetActive(true);
            NewUIManager.Instance.Slots.SetActive(true);
            NewUIManager.Instance.Rotation_Buttons.SetActive(false);
            NewUIManager.Instance.ChangeText("Upgrade phase: Upgrade your robots! " + RemainingTurnsText);
            NewUIManager.Instance.TutorialBoxSummon();
            RemainingTurns--;
            if (_currentPlayerTurn == PlayerTurn.Curve_Turn)
            {
                JoystickManager.Instance.IsDoubleUpgradeActive         = false;
                JoystickManager.Instance.DoubleUpgradeAlreadyActivated = false;
                NewUIManager.Instance.A_Button_Quad.gameObject.SetActive(false);
                ArrowManager.Instance.Frecce_Quad.SetActive(false);
                NewUIManager.Instance.DoubleUpgrade.SetActive(true);
                RobotManager.Instance.RobotsCurviInHand = RobotManager.Instance.Draw(RobotManager.Instance.RobotCurviInHand, RobotManager.Instance.RobotCurvi, RobotManager.Instance.RobotsCurviInHand, Player.Player_Curve);
            }
            else
            {
                JoystickManager.Instance.IsDoubleUpgradeActive = false;
                RobotManager.Instance.RobotsQuadratiInHand     = RobotManager.Instance.Draw(RobotManager.Instance.RobotQuadratiInHand, RobotManager.Instance.RobotQuadrati, RobotManager.Instance.RobotsQuadratiInHand, Player.Player_Quad);
            }
            break;

        case TurnState.useEnergy:
            break;

        default:
            break;
        }
    }
Esempio n. 43
0
    private void TurnMiddle()
    {
        var mousePosition2d = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        var globalCoords = MouseManager.ScreenToGlobal(mousePosition2d);
        var gridVector = this.Map.GlobalToGrid(globalCoords);
        this.scrollMap(mousePosition2d);

        if (this.SelectedActor != null)
        {
            var actorState = this.SelectedActor.TurnState;

            if (Input.GetKeyUp(KeyCode.Escape))
            {
                if (actorState == ActorState.AwaitingCommand)
                {
                    this.SelectedActor.TurnState = ActorState.CommandsAvailable;
                    this.clearSelection();
                }
            }
        }

        if (this.TurnOver())
        {
            this.turnState = TurnState.TurnEnd;
        }
    }
Esempio n. 44
0
 public void EndSwarmZonesTurn()
 {
     currentTurnState = TurnState.PlayerTurn;
     StartCoroutine("BetweenTurnsCoroutine");
 }
 // Start is called before the first frame update
 void Start()
 {
     currentState = TurnState.PROCESSING;
 }
Esempio n. 46
0
 public void WonGame()
 {
     currentTurnState = TurnState.Won;
 }
Esempio n. 47
0
    void Update()
    {
        // Debug.Log(currentState);
        switch (currentState)
        {
        case (TurnState.PROCESSING):
            UpgradeProgressBar();
            break;

        case (TurnState.ADDTOLIST):
            BSM.HerosToManage.Add(this.gameObject);
            ChooseAction();
            currentState = TurnState.WAITING;
            break;

        case (TurnState.WAITING):

            break;


        case (TurnState.ACTION):
            StartCoroutine(TimeForAction());
            break;

        case (TurnState.DEAD):
            if (!alive)
            {
                return;
            }
            else
            {
                //change tag
                this.gameObject.tag = "DeadHero";
                //not attackable by enemies
                BSM.HerosInBattle.Remove(this.gameObject);
                //not manageable
                BSM.HerosToManage.Remove(this.gameObject);

                //remove item from performlist

                // if (BSM.HerosInBattle.Count > 0)
                //{
                for (int i = 0; i < BSM.PerformList.Count; i++)
                {
                    if (BSM.PerformList[i].AttackingGameObject == this.gameObject)
                    {
                        BSM.PerformList.Remove(BSM.PerformList[i]);
                    }

                    // if (BSM.PerformList[i].AttackersTarget == this.gameObject)
                    //   {
                    //        BSM.PerformList[i].AttackersTarget = BSM.EnemiesInBattle[0];
                    //    }
                }
                //  }
                //change colour/play animation
                this.gameObject.GetComponent <MeshRenderer>().material.color = new Color32(105, 105, 105, 255);
                //reset hero input
                BSM.battleStates = BattleStateMachine.PerformAction.CHECKALIVE;
                alive            = false;
            }
            break;
        }
    }
Esempio n. 48
0
 public void LostGame()
 {
     currentTurnState = TurnState.Won;
 }
Esempio n. 49
0
    void NewGame(int playerCount, List<int> humanPlayers)
    {
        // TODO: Separate Root Scene with the actual level
        //Application.LoadLevel( "MainScene" );

        Debug.Log("NEW GAME!!!");

        InitializeScene();

        // Create Players & Bases
        playerTurnIndex = 0;
        turnState = TurnState.Starting;

        players = new List<PlayerInfo>();

        var iHuman = 0;
        var iComputer = 0;

        var radiansBetweenBases = 2 * Mathf.PI / playerCount;

        // n = spaces = players
        // baseDistance = 1/n * C == 1/n D PI = 1/n 2PI r = r 2PI / n
        // r = baseDistance / (2PI/n)
        // r = baseDistance * n / 2PI
        var stageRadius = baseDistance * playerCount / (2 * Mathf.PI);

        // For small number players, this can happen (less than 4)
        if (stageRadius < baseDistance / 2)
        {
            stageRadius = baseDistance / 2;
        }

        // Increase power for large radiuses
        shooterStageSizeModifier = Mathf.Sqrt(stageRadius * 2 / baseDistance);

        Debug.Log("StageRadius=" + stageRadius);

        for (int i = 0; i < playerCount; i++)
        {
            var player1Point = 1.0f * Mathf.PI;
            var radians = player1Point - (radiansBetweenBases * i);
            radians = (radians + 2 * Mathf.PI) % (2 * Mathf.PI);

            var x = stageRadius * Mathf.Cos(radians);
            var z = stageRadius * Mathf.Sin(radians);

            //if (radians > Mathf.PI)
            //{
            //  x = -x;
            //}

            //if ((radians > Mathf.PI * 0.5f)
            //  && (radians < Mathf.PI * 1.5f))
            //{
            //  z = -z;
            //}

            Debug.Log((radians / Mathf.PI) + " * PI @ " + x + " , " + z);

            var position = new Vector3(x, 0, z);
            var baseObj = (GameObject)Instantiate(prefabBase, position, Quaternion.identity);
            baseObj.tag = "Base";
            baseObj.transform.parent = baseHolder.transform;
            var isHuman = humanPlayers.Contains(i);
            var name = "";

            if (isHuman)
            {
                if (humanPlayers.Count > 1)
                {
                    name = "Player " + (iHuman + 1);
                }
                else
                {
                    name = "Player";
                }
            }
            else
            {
                if (playerCount - humanPlayers.Count > 1)
                {
                    name = "Computer " + (iComputer + 1);
                }
                else
                {
                    name = "Computer";
                }
            }

            var player = new PlayerInfo(baseObj, isHuman, name);
            players.Add(player);

            if (isHuman)
            {
                iHuman++;
            }
            else
            {
                iComputer++;
            }
        }

        // Go to editor
        // TODO: Give each human a chance to create base
        editorController.ShowEditor(players[0].baseObject, blockMaxDistanceFromBase, blockPrefabs.ToArray(), blockImages.ToArray());
    }
Esempio n. 50
0
    // Update is called once per frame
    void Update()
    {
        //Debug.Log(currentState);
        switch (currentState)
        {
        case (TurnState.PROCESSING):
            UpdateProgressBar();
            break;

        case (TurnState.ADDTOLIST):
            BSM.heroesToManage.Add(this.gameObject);
            currentState = TurnState.WAITING;
            break;

        case (TurnState.WAITING):
            //wait for input
            break;

        case (TurnState.ACTION):
            StartCoroutine(TimeForAction());
            break;

        case (TurnState.DEAD):
            if (!isAlive)
            {
            }
            else
            {
                //change tag
                this.gameObject.tag = "Dead Hero";

                //disable oncoming attack
                BSM.heroesInBattle.Remove(this.gameObject);

                //not managable
                BSM.heroesToManage.Remove(this.gameObject);

                //disactivate the slector
                selector.SetActive(false);

                //reset GUI
                BSM.attackPanel.SetActive(false);
                BSM.enemySelectPanel.SetActive(false);

                if (BSM.heroesInBattle.Count > 0)
                {
                    //remove from the list
                    for (int i = 0; i < BSM.performList.Count; i++)
                    {
                        if (i != 0)    //prevent to false delete
                        {
                            if (BSM.performList[i].attacksGameObject == this.gameObject)
                            {
                                BSM.performList.Remove(BSM.performList[i]);    //remover
                            }

                            if (BSM.performList[i].attackersTarget == this.gameObject)
                            {
                                BSM.performList[i].attackersTarget =
                                    BSM.heroesInBattle[Random.Range(0, BSM.heroesInBattle.Count)];
                            }
                        }
                    }
                }

                //Channge this color gameobject or play adead aanimation
                this.gameObject.GetComponentInChildren <MeshRenderer>().material.color =
                    new Color32(105, 105, 105, 255);

                BSM.battleStates = BattleStateMachine.PerformAction.CHECKLIFE;
                //reset hero input
                isAlive = false;
            }
            break;
        }
    }
Esempio n. 51
0
 public void Restart()
 {
     turnState = TurnState.Player;
     OnTurnChange.newTurnState = turnState;
     OnTurnChange.FireEvent();
 }
Esempio n. 52
0
    /// <summary>
    /// Initialize resources.  Right now, for testing purposes, a simple random map is
    /// generated here with a few actors in it.
    /// </summary>
    public override void Start()
    {
        var width   = 50;
        var height  = 35;
        var mapSeed = "blah blah";
        var tiles   = new TileProperties[width, height];

        this.mapContainer = new FContainer();
        this.hud          = new FContainer();

        // This handles GUI and stuff
        //this.interfaceManager = new InterfaceManager();
        //this.interfaceManager = ScriptableObject.CreateInstance("InterfaceManager");;

        // Generate a very simple random map tiles
        this.mapGenerator = new MapGenerator();
        tiles             = mapGenerator.GenerateMap(width, height, 10);

        /*
         * this is the old code for generating a random map
         * var rand = new System.Random();
         * for (int ii = 0; ii < width; ii++)
         * {
         *  for (int jj = 0; jj < height; jj++)
         *  {
         *      tiles[ii, jj] = (rand.NextDouble() < 0.7) ? StaticTiles.GrassTile : StaticTiles.ForestTile;
         *  }
         * }
         */
        this.Map = new Map(tiles);


        int i = 5;
        int j = 5;

        foreach (var team in this.teams)
        {
            var actorList = new List <Actor>();
            foreach (var member in team.Members)
            {
                var actor = new Actor(member, team);
                actorList.Add(actor);
                this.Map.AddActor(actor, new Vector2i(i++, j++));
            }
        }


        this.Map.Start();
        this.mapContainer.AddChild(this.Map);

        // Initialize overlay
        this.visibleOverlayIndices = new HashSet <Vector2i>();
        this.overlay = new FSprite[Map.Columns, Map.Rows];
        for (int ii = 0; ii < Map.Columns; ii++)
        {
            for (int jj = 0; jj < Map.Rows; jj++)
            {
                var overlaySprite = new FSprite("bluehighlight");
                overlaySprite.x         = ii * AwayTeam.TileSize + AwayTeam.TileSize / 2;
                overlaySprite.y         = jj * AwayTeam.TileSize + AwayTeam.TileSize / 2;
                overlaySprite.isVisible = false;
                overlaySprite.width     = overlaySprite.height = AwayTeam.TileSize;
                this.overlay[ii, jj]    = overlaySprite;
                this.mapContainer.AddChild(overlaySprite);
            }
        }

        this.AddChild(this.mapContainer);
        this.AddChild(this.hud);
        this.teamIndex = 0;
        this.turnState = TurnState.TurnBegin;
        this.started   = true;
    }
Esempio n. 53
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            graphics.IsFullScreen = false;
            OriginScreenSize = new Vector2(1024, 768);
            ScreenSize = new Vector2(768, 576);

            ScreenScaleFactor = new Vector2();
            ScreenScaleFactor.X = ScreenSize.X / OriginScreenSize.X;
            ScreenScaleFactor.Y = ScreenSize.Y / OriginScreenSize.Y;

            graphics.PreferredBackBufferWidth = 768;
            graphics.PreferredBackBufferHeight = 576;

            Content.RootDirectory = "Content";

            Global.thisGame = this;
            HexagonServer = IO.Socket(GameSettings.HexagonServer);

            HexagonServer.On(Socket.EVENT_CONNECT, () =>
            {
                ServerReady = true;
            });

            HexagonServer.On("sendMove", (data) =>
            {
                if (hexMap != null)
                {
                    int i,j;
                    string[] d = ((string)data).Split(',');
                    i = Convert.ToInt32(d[0]);
                    j = Convert.ToInt32(d[1]);
                    hexMap.SelectCell(i, j, true);
                }
            });

            HexagonServer.On("registerResult", (data) =>
            {
                var result = Convert.ToInt32(data);
                switch (result)
                {
                    case -1:
                        connectionState = ConnectionState.DuplicateID;
                        break;
                    case 0:
                        connectionState = ConnectionState.RoomFull;
                        break;
                    case 1:
                        connectionState = ConnectionState.Connected;
                        playerState = PlayerState.Blue;
                        turnState = TurnState.Waiting;
                        break;
                    case 2:
                        connectionState = ConnectionState.Waiting;
                        playerState = PlayerState.Red;
                        turnState = TurnState.Ready;
                        break;
                }
            });

            HexagonServer.On("otherQuit", (data) =>
            {
                var username = (string)data;
                connectionState = ConnectionState.OtherDisconnected;
            });

            HexagonServer.On("otherJoin", (data) =>
            {
                var username = (string)data;
                connectionState = ConnectionState.Connected;
            });
        }
Esempio n. 54
0
 private void TurnEnd()
 {
     Debug.Log("[[Team Turn End]] Team: " + this.CurrentTeam.Name);
     this.teamIndex = (this.teamIndex + 1) % this.teams.Count;
     this.turnState = TurnState.TurnBegin;
 }
Esempio n. 55
0
 // Start is called before the first frame update
 void Start()
 {
     currentState  = TurnState.Processing;
     bsm           = GameObject.Find("BattleManager").GetComponent <BattleStateMachine>();
     startPosition = transform.position;
 }
Esempio n. 56
0
        //выполняет действия с выбранной точкой.
        private void ActionPoint(Point where)
        {
            if (where.X < 0 || where.X > 7 || where.Y < 0 || where.Y > 7)
            {
                //clicked out of field. Drop all selected things, set state to nothing selected
                selectedPoints.Clear();
                state = TurnState.nothingSelected;
                return;
            }
            else
            {
                Figure selectedFigure = currentField.WhoIsOn(where);

                //IF NONE SELECTED
                if (state == TurnState.nothingSelected || state == TurnState.emptyGridSelected || state == TurnState.enemyFigureSelected)
                {
                    if (selectedFigure == null)
                    {
                        state = TurnState.emptyGridSelected;  //selected an empty
                    }
                    else
                    {
                        if (selectedFigure.Team == CurrentPlayerTeam)
                        {
                            selectedPoints.Clear();
                            selectedPoints = WhereToGo(selectedFigure);
                            selectedPoints.Add(selectedFigure.Position);
                            state = TurnState.friendlyFigureSelected;
                            //Мы имеем список всех клеток, куда она может пойти и ее саму в конце
                            //select your figure
                        }
                        else
                        {
                            state = TurnState.enemyFigureSelected;       //select enemy
                            selectedPoints.Clear();
                            selectedPoints.Add(selectedFigure.Position); //add this figure to a selectedPoints
                        }
                    }
                    return;
                }

                //IF FRIEND SELECTED and pressed other point
                if (state == TurnState.friendlyFigureSelected && selectedPoints.Count > 0)
                {
                    Figure previousSelected = currentField.WhoIsOn(selectedPoints[selectedPoints.Count - 1]);
                    //garanted a friendly figure
                    if (selectedFigure == null && WhereToGo(previousSelected).IndexOf(where) >= 0 /*можем пойти в этиу клетку*/)
                    {
                        /*MAKE A TURN GREAT AGAIN*/
                        selectedPoints = WhereToGo(previousSelected);
                        state          = TurnState.makeATurn;
                        DoATurn(previousSelected, where);
                        return;
                    }
                    if (selectedFigure != null)
                    {
                        //not null selected
                        if (selectedFigure.Position == previousSelected.Position)
                        {
                            //еще один клик на выбраннуб пешку
                            selectedPoints.Clear();
                            state = TurnState.nothingSelected;
                            return;
                        }
                        if (selectedFigure.Team == previousSelected.Team)
                        {
                            //выбираем другую пешку своей же команды. При этом список переделывается
                            selectedPoints.Clear();
                            selectedPoints = WhereToGo(selectedFigure);
                            selectedPoints.Add(selectedFigure.Position);
                            state = TurnState.friendlyFigureSelected;
                            return;
                        }
                    }
                }
            }
        }
Esempio n. 57
0
 public void EndEnemiesTurn()
 {
     currentTurnState = TurnState.ProgressionTurn;
     StartCoroutine("BetweenTurnsCoroutine");
 }
 // Use this for initialization
 void Start()
 {
     startPosition = transform.position;
     CurrentState  = TurnState.PROCESSING;
     bsm           = GameObject.Find("BattleManager").GetComponent <BattleStateMachine>();
 }
Esempio n. 59
0
        protected void UpdateGame(GameTime gameTime)
        {
            #region TEST
            //if (Mouse.GetState().LeftButton == ButtonState.Pressed && Mouse.GetState().LeftButton != _mouseStatePrevious.LeftButton)
            //{
            //    testRectangle.X = Mouse.GetState().X;
            //    testRectangle.Y = Mouse.GetState().Y;
            //}
            //else if (Mouse.GetState().LeftButton == ButtonState.Pressed)
            //{
            //    testRectangle.Width = Mouse.GetState().X - testRectangle.X;
            //    testRectangle.Height = Mouse.GetState().Y - testRectangle.Y;
            //}
            //if (Keyboard.GetState().IsKeyDown(Keys.Left) && Keyboard.GetState().IsKeyDown(Keys.Left) != _keyboardStatePrevious.IsKeyDown(Keys.Left))
            //{
            //    spherePosition.X--;
            //}
            //if (Keyboard.GetState().IsKeyDown(Keys.Right) && Keyboard.GetState().IsKeyDown(Keys.Right) != _keyboardStatePrevious.IsKeyDown(Keys.Right))
            //{
            //    spherePosition.X++;
            //}
            //if (Keyboard.GetState().IsKeyDown(Keys.Down) && Keyboard.GetState().IsKeyDown(Keys.Down) != _keyboardStatePrevious.IsKeyDown(Keys.Down))
            //{
            //    spherePosition.Y++;
            //}
            //if (Keyboard.GetState().IsKeyDown(Keys.Up) && Keyboard.GetState().IsKeyDown(Keys.Up) != _keyboardStatePrevious.IsKeyDown(Keys.Up))
            //{
            //    spherePosition.Y--;
            //}
            #endregion

            if (_bigTextTimer > 0)
            {
                _bigTextTimer -= gameTime.ElapsedGameTime.Milliseconds;
            }

            if (_cueBallTimer > 0)
            {
                _cueBallTimer -= gameTime.ElapsedGameTime.Milliseconds;
                _freezeInput = true;
            }
            else
            {
                /// TODO LOL
                if (_cueBallTimer < 0)
                    _cueBallTimer = 0;
            }

            if (_gameMode == GameMode.ONLINE && _currentPlayer != _myPlayer)
            {
                _freezeInput = true;
                _cueVisible = false;
            }
            else
            {
                _cueVisible = true;
            }

            if (!_freezeInput)
            {
                _cuePosition = balls[0].Position;
                if (Mouse.GetState().LeftButton == ButtonState.Released)
                {
                    _lastMousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
                    if (_mouseStatePrevious.LeftButton == ButtonState.Pressed && _cueDistance > 0)
                    {
                        // do shot
                        MakeShot(_cueDistance, _cueRotation, false);
                        if (_gameMode == GameMode.ONLINE && _connection != null)
                        {
                            _connection.SendSync(balls);
                            _connection.SendVelocity(_cueDistance, _cueRotation);
                        }
                        _cueDistance = 0;
                    }
                    else
                    {
                        _cueRotation = Math.Atan2(Mouse.GetState().X - balls[0].X, Mouse.GetState().Y - balls[0].Y);
                    }
                }
                else if (Mouse.GetState().LeftButton == ButtonState.Pressed && _mouseStatePrevious.LeftButton == ButtonState.Released)
                {
                    _lastMousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
                }
                else
                {
                    double mouseDistanceFromCue = (_mousePosition - balls[0].Position).Length();

                    // let the user pull the cue back to decide power
                    // (let me overcomplicate everything for you!)
                    // Angles between the polar axes centred around the ball and various lines
                    double lastMousePosAngle = _cueRotation;
                    double currentMousePosAngle = Math.Atan2(Mouse.GetState().X - balls[0].X, Mouse.GetState().Y - balls[0].Y);
                    // A triangle constructed of:
                    // - The line between the ball and where the mouse currently is
                    // - The line between the ball and where the mouse was when lmb was first held
                    // - The third line connecting these two lines, creating a right angle between this line and the line to where lmb was first held
                    // The angle is gotten by subtracting the angles above
                    double theta = currentMousePosAngle - lastMousePosAngle;
                    // The length of the first line segment
                    double firstLineSegment = (_mousePosition - balls[0].Position).Length();
                    // Then use trigonometry to calculate the length of the third line
                    double trigThirdLine = firstLineSegment * Math.Cos(theta);
                    double fullLine = (balls[0].Position - _lastMousePosition).Length();
                    // And subtract this length from line segment 2 to get the distance of the mouse from that point
                    _cueDistance = (int)Math.Floor(fullLine - trigThirdLine);

                    if (_cueDistance < 0)
                        _cueDistance = 0;
                    if (_cueDistance > MAX_POWER)
                        _cueDistance = MAX_POWER;
                }

                if (_cueDistance > 0 && Mouse.GetState().LeftButton == ButtonState.Released)
                    _cueDistance = 0;

                _cuePosition.X = balls[0].Position.X - (float)(Math.Sin(_cueRotation) * _cueDistance);
                _cuePosition.Y = balls[0].Position.Y - (float)(Math.Cos(_cueRotation) * _cueDistance);
            }

            _ballPredictor.Update(gameTime, balls, _cueRotation);

            foreach (Ball ball in balls)
            {
                foreach (Ball other in balls)
                {
                    if (ball != other)
                    {
                        if (ball.Velocity.LengthSquared() > 0)
                        {
                            if (ball.BoundingSphere.Intersects(other.BoundingSphere))
                            {
                                Vector2 impact = other.Velocity - ball.Velocity;
                                Vector2 impulse = Vector2.Normalize(other.Position - ball.Position);
                                float impactSpeed = Vector2.Dot(impact, impulse);
                                if (impactSpeed < -2000)
                                    impactSpeed = -2000;
                                if (impactSpeed < 0)
                                {
                                    _ballStrike.Play(impactSpeed / -2000.0f, 0.0f, 0.0f);
                                    if (ball.Colour != Color.White && other.Colour != Color.White)
                                    {
                                        Color tempColour = ball.Colour;
                                        ball.Colour = other.Colour;
                                        other.Colour = tempColour;
                                    }
                                    else if (ball.Colour == Color.White)
                                    {
                                        if (_firstColourHit == Color.Transparent)
                                        {
                                            _firstColourHit = other.Colour;
                                            //string colourHit;
                                            //if (other.Colour == Color.Black)
                                            //    colourHit = "black";
                                            //else if (other.Colour == Color.Orange)
                                            //    colourHit = "orange";
                                            //else if (other.Colour == Color.Red)
                                            //    colourHit = "red";
                                            //else
                                            //    colourHit = "BAD";
                                            //ShowBigText(Color.White, "Hit " + colourHit, 1500);
                                        }

                                    }
                                    else if (other.Colour == Color.White)
                                    {
                                        if (_firstColourHit == Color.Transparent)
                                        {
                                            _firstColourHit = ball.Colour;
                                            //string colourHit;
                                            //if (ball.Colour == Color.Black)
                                            //    colourHit = "black";
                                            //else if (ball.Colour == Color.Orange)
                                            //    colourHit = "orange";
                                            //else if (ball.Colour == Color.Red)
                                            //    colourHit = "red";
                                            //else
                                            //    colourHit = "BAD";
                                        }
                                    }

                                    impulse *= impactSpeed * 0.95f;
                                    other.Velocity -= impulse;
                                    ball.Velocity += impulse;
                                }
                            }
                        }
                    }
                }

                ball.Update(gameTime);
            }

            for (int i = 0; i < pottedBalls.Count; i++)
            {
                if (pottedBalls[i].X > refugeX + (i * 30))
                {
                    pottedBalls[i].X -= (float)(0.5 * gameTime.ElapsedGameTime.Milliseconds);
                }
                if (pottedBalls[i].X < refugeX + (i * 30))
                {
                    pottedBalls[i].X = refugeX + (i * 30);
                }
            }

            _freezeInput = false;
            for (int i = 0; i < balls.Count; i++)
            {
                if (balls[i]._potted)
                {
                    // If it aint the cue ball.. damnit
                    if (balls[i].Colour != Color.White)
                    {
                        _pocketBounce.Play(1.0f, 0.0f, 0.0f);
                        // If it aint the black.. double damnit
                        if (balls[i].Colour != Color.Black)
                        {
                            // If players are not yet assigned colours
                            if (_playerOneColour == Color.Transparent)
                            {
                                // Assign 'em I guess
                                Color otherColour;
                                if (balls[i].Colour == Color.Red)
                                    otherColour = Color.Orange;
                                else
                                    otherColour = Color.Red;

                                switch (_currentPlayer)
                                {
                                    case PlayerIndex.One:
                                        _playerOneColour = balls[i].Colour;
                                        _playerTwoColour = otherColour;
                                        break;
                                    case PlayerIndex.Two:
                                        _playerOneColour = otherColour;
                                        _playerTwoColour = balls[i].Colour;
                                        break;
                                }

                                ShowBigText(Color.White, "SCORE", 1500);
                                _turnState = TurnState.SCORED;
                            }
                            else
                            {
                                // Otherwise check if they potted their own ball
                                Color currentPlayersColour;
                                if (_currentPlayer == PlayerIndex.One)
                                {
                                    currentPlayersColour = _playerOneColour;
                                }
                                else
                                {
                                    currentPlayersColour = _playerTwoColour;
                                }
                                if (balls[i].Colour == currentPlayersColour)
                                {
                                    // BAM
                                    _turnState = TurnState.SCORED;
                                    ShowBigText(Color.White, "SCORE", 1500);
                                }
                            }
                        }
                        else
                        {
                            // If they pot the black
                            Color currentPlayerColour;
                            if (_currentPlayer == PlayerIndex.One)
                                currentPlayerColour = _playerOneColour;
                            else
                                currentPlayerColour = _playerTwoColour;

                            int currentPlayerBallsLeft = 0;
                            foreach (Ball ball in balls)
                            {
                                if (ball.Colour == currentPlayerColour)
                                    currentPlayerBallsLeft++;
                            }

                            // If they have more than one ball of their colour left, f**k
                            if (currentPlayerBallsLeft > 0 || currentPlayerColour == Color.Transparent || (_firstColourHit != currentPlayerColour && _firstColourHit != Color.Black))
                            {
                                PlayerIndex otherPlayer;
                                if (_currentPlayer == PlayerIndex.One)
                                    otherPlayer = PlayerIndex.Two;
                                else
                                    otherPlayer = PlayerIndex.One;

                                _winningPlayer = otherPlayer;
                                _winningTimer = 14000;
                                _freezeInput = true;
                            }
                            else
                            {
                                _winningPlayer = _currentPlayer;
                                _winningTimer = 14000;
                                _freezeInput = true;
                            }
                        }
                        pottedBalls.Add(balls[i]);
                        balls[i].X = 2000;
                        balls[i].Y = 676;
                        balls.Remove(balls[i]);
                        i--;
                    }
                    else
                    {
                        // If white,
                        _portal.Play(1.0f, 1.0f, 1.0f);
                        balls[i]._potted = false;
                        _freezeInput = true;
                        _cueBallTimer = 1000;
                        balls[i].Position = Ball._reversedPocketSpheres[balls[i]._pocketCollided];
                    }
                }
                else if (balls[i].Velocity.LengthSquared() > 0)
                {
                    _freezeInput = true;
                }
            }

            if (_winningTimer > 0)
            {
                _freezeInput = true;
                _winningTimer -= gameTime.ElapsedGameTime.Milliseconds;
            }
            else if (_winningPlayer != PlayerIndex.Three)
            {
                // Restart game when timer gets to 0
                _winningTimer = 0;
                GenerateBalls();
                _playerOneColour = Color.Transparent;
                _playerTwoColour = Color.Transparent;
                _startTime = gameTime.TotalGameTime.Seconds;
                InitializeGame(false);
            }

            if (_freezeInput == false && _freezeInputPrevious == true && _gameMode != GameMode.PRACTICE)
            {
                // Play just resumed, then
                Color currentPlayerColour;
                if (_currentPlayer == PlayerIndex.One)
                    currentPlayerColour = _playerOneColour;
                else
                    currentPlayerColour = _playerTwoColour;

                // Check how many balls the current player has
                int currentPlayerBallsLeft = 0;
                foreach (Ball ball in balls)
                {
                    if (ball.Colour == currentPlayerColour)
                        currentPlayerBallsLeft++;
                }

                if ((currentPlayerColour == Color.Transparent && (_firstColourHit == Color.Red || _firstColourHit == Color.Orange))
                    || (currentPlayerColour != Color.Transparent && _firstColourHit == currentPlayerColour)
                    || ((currentPlayerBallsLeft == 0 && currentPlayerColour != Color.Transparent) && _firstColourHit == Color.Black))
                {

                }
                else if (_winningTimer == 0)
                {
                    ShowBigText(Color.White, "Foul", 1500);
                }
                else if (_winningTimer != 0)
                {
                    _firstColourHit = Color.Transparent;
                }

                _firstColourHit = Color.Transparent;

                // Switch players
                if (_turnState != TurnState.SCORED)
                {
                    if (_currentPlayer == PlayerIndex.One)
                        _currentPlayer = PlayerIndex.Two;
                    else
                        _currentPlayer = PlayerIndex.One;
                }
                _turnState = TurnState.SHOOTING;
            }

            _freezeInputPrevious = _freezeInput;
        }
Esempio n. 60
0
 public void EndSpawnPointsTurn()
 {
     currentTurnState = TurnState.SwarmZonesTurn;
     StartCoroutine("BetweenTurnsCoroutine");
 }