public LevelSimulationSnapshot MakeMove(AIMove move)
    {
        var newMap = new int[_map.GetLength(0), _map.GetLength(1)];

        Buffer.BlockCopy(_map, 0, newMap, 0, _map.Length * sizeof(int));
        var piece            = GetPiece(move.FromX, move.FromY);
        var hasCollectedCube = _hasCollectedCube;

        if (newMap[move.ToX, move.ToY] > 4)
        {
            newMap[move.ToX, move.ToY] -= 4;
            hasCollectedCube            = true;
        }
        newMap[move.ToX, move.ToY]    += piece;
        newMap[move.FromX, move.FromY] = IsFloor(move.FromX, move.FromY) ? 1 : 0;
        if (piece < 128)
        {
            var damagedPiece = GetPiece(IntBetween(move.FromX, move.ToX), IntBetween(move.FromY, move.ToY));
            if (damagedPiece == 64)
            {
                newMap[IntBetween(move.FromX, move.ToX), IntBetween(move.FromY, move.ToY)] -= 32;
            }
            else
            {
                newMap[IntBetween(move.FromX, move.ToX), IntBetween(move.FromY, move.ToY)] -= damagedPiece;
            }
        }
        return(new LevelSimulationSnapshot(newMap, _goalX, _goalY, hasCollectedCube));
    }
Exemplo n.º 2
0
        public void DoMove()
        {
            AIMove move = calc.Calculate(WaterTaken(), opponent.WaterTaken(), NumHoles());

            switch (move)
            {
            case AIMove.FIRE:
                FireShot(opponent);
                vicky.setUnderAttack(watch);
                Game1.recentMoves.Add("AI fired a shot");
                fireEffect.Play();
                break;

            case AIMove.BOARD:
                Repair(1);
                Game1.recentMoves.Add("AI fixed a hole");
                repairEffect.Play();
                break;

            case AIMove.BUCKET:
                BailWater(Ship.WATER_PER_BAIL);
                Game1.recentMoves.Add("AI bailed water");
                bailEffect.Play();
                break;
            }
            Game1.TrimRecentsList();
        }
 private void Start()
 {
     ai          = GetComponent <AIMove>();
     m_AIManager = GetComponent <AISpawner>();
     // Initiates new fish in with SwimState active
     SetState(new SwimState(this));
 }
Exemplo n.º 4
0
    public static List <AIMove> GetPieceDestinations(ChessPiece piece)
    {
        List <AIMove> pieceMoves = new List <AIMove>();

        bool[,] allowedMoves = piece.IsMovePossible();

        for (int i = 0; i < allowedMoves.GetLength(0); i++)
        {
            for (int j = 0; j < allowedMoves.GetLength(1); j++)
            {
                if (!allowedMoves[i, j])
                {
                    continue;
                }

                if (piece.type != "King")
                {
                    bool moveThreatensGeneral = CheckGeneralThreatened(piece, i, j);
                    if (moveThreatensGeneral)
                    {
                        continue;
                    }
                }

                AIMove newMove = new AIMove(piece, i, j);
                if (piece.type == "King" && newMove.VulnerableAfterMove)
                {
                    continue;
                }

                pieceMoves.Add(newMove);
            }
        }
        return(pieceMoves);
    }
Exemplo n.º 5
0
    public void go(ChessSquare[,] b)
    {
        selectedMove = null;
        board        = b;
        state        = 1;

        side         s = side.White;
        AttacksTable t = chess.attacksBlack;

        if (!chess.isWhiteTurn())
        {
            s = side.Black;
            t = chess.attacksWhite;
        }

        if (chess.checkCheck(b, s, t))
        {
            selectedMove = selectCheckBreaker(s);
        }
        else
        {
            selectedMove = selectAttack(s, t);
            if (selectedMove == null)
            {
                selectedMove = selectRandom(s);
            }
        }
        if (selectedMove == null)
        {
            chess.theEnd();
            state = 0;
        }

        cooldown = Time.time;
    }
Exemplo n.º 6
0
    AIMove selectAttack(side s, AttacksTable t)
    {
        if (initial)
        {
            ArrayList moves = gimmeMoves(s);
            attackMoves = new ArrayList();
            foreach (AIMove m in moves)
            {
                if (m.eatenValue != 0)
                {
                    attackMoves.Add(m);
                }
            }
        }

        AIMove move = selectMoveAttack(selectMovesOfRisk(attackMoves, 5));

        if (move == null)
        {
            move = selectMoveAttack(selectAttacksDefensive(selectMovesOfRisk(attackMoves, 4)));
        }
        if (move == null)
        {
            move = selectMoveAttack(selectAttacksDefensive(selectMovesOfRisk(attackMoves, 3)));
        }

        return(move);
    }
Exemplo n.º 7
0
 public void CheckAIMove()
 {
     listofAImove = new List <AIMove>();
     for (int i = 0; i < board.width; i++)
     {
         for (int j = 0; j < board.height; j++)
         {
             if (board.allDots[i, j] != null)
             {
                 if (i < board.width - 1)
                 {
                     AIMove AICheck = gameObject.AddComponent <AIMove>();
                     AICheck.NewAIMove(i, j, i + 1, j, 0);
                     SwithAndCheckAI(i, j, Vector2.right, AICheck);
                     listofAImove.Add(AICheck);
                 }
                 if (j < board.height - 1)
                 {
                     AIMove AICheck = gameObject.AddComponent <AIMove>();
                     AICheck.NewAIMove(i, j, i, j + 1, 0);
                     SwithAndCheckAI(i, j, Vector2.up, AICheck);
                     listofAImove.Add(AICheck);
                 }
             }
         }
     }
 }
Exemplo n.º 8
0
 public void CalculateAngleAI(AIMove finalmove)
 {
     board.currentState = GameState.wait;
     swipeAngle         = Mathf.Atan2(finalmove.targetY - finalmove.currentY, finalmove.targetX - finalmove.currentX) * 180 / Mathf.PI;
     MovePiecesAI();
     board.currentDot = board.allDots[finalmove.currentX, finalmove.currentY].GetComponent <Dot>();
 }
Exemplo n.º 9
0
        public bool MakeAIMove(ref bool extra_movement)
        {
            bool rtn = false;

            if (!(GetPlayerPlaying() is VirtualPlayer))
            {
                return(rtn);
            }
            Move currentMove = (GetPlayerPlaying() as VirtualPlayer).GetMove(Board, GetTurnColor().Substring(0, 1));

            if (currentMove != null)
            {
                if (IsPlayPossible(currentMove.origin.Position, currentMove.destination.Position, GetTurnColor().Substring(0, 1)))
                {
                    AIMove?.Invoke(currentMove.origin.Position, currentMove.destination.Position);
                    UpdatePieces(currentMove.origin.Position, currentMove.destination.Position);
                    rtn = true;
                }
            }
            if (HasEaten)
            {
                if (ExtraMov(currentMove.destination.Position, GetTurnColor().Substring(0, 1)))
                {
                    extra_movement = true;
                }
            }
            CheckWinner();
            if (Winner != null)
            {
                IsGameOver = true;
            }
            CheckQueen(GetTurnColor().Substring(0, 1), currentMove.destination.Position);

            return(rtn);
        }
Exemplo n.º 10
0
        public override Move getMove()
        {
            //Create the resulting move
            Move result = new Move();

            //Get first player identity and board
            identity first = Program.getFirstPlayer();
            Board    board = Program.getBoard();

            //Decide if this is whites turn or not
            bool isWhitesTurn = (first == this.getIdentity());


            //Get the move from the AI DLL
            AIMove nextMove = AIGetMove(board.blackCount, board.whiteCount, board.blackRows, board.whiteRows, isWhitesTurn);

            //Convert the AIMove to a Move class
            result.Begin.X = nextMove.row;
            result.Begin.Y = nextMove.col;
            if (isWhitesTurn)
            {
                result.End.X = nextMove.row + 1;
            }
            else
            {
                result.End.X = nextMove.row - 1;
            }
            result.End.Y = nextMove.col + nextMove.target - 1;

            //Return the result
            return(result);
        }
Exemplo n.º 11
0
        public static Move getAMove(bool isWhitesTurn)
        {
            //Create the resulting move
            Move result = new Move();

            //Get first player identity and board
            identity first = Program.getFirstPlayer();
            Board    board = Program.getBoard();

            //Convert to AISpace
            ulong[,] AISQUARES = { {                 1,                  2,                  4,                  8,               16,               32,                64,               128 },
                                   {               256,                512,               1024,               2048,             4096,             8192,             16384,             32768 },
                                   {             65536,             131072,             262144,             524288,          1048576,          2097152,           4194304,           8388608 },
                                   {          16777216,           33554432,           67108864,          134217728,        268435456,        536870912,        1073741824,        2147483648 },
                                   {        4294967296,         8589934592,        17179869184,        34359738368,      68719476736,     137438953472,      274877906944,      549755813888 },
                                   {     1099511627776,      2199023255552,      4398046511104,      8796093022208,   17592186044416,   35184372088832,    70368744177664,   140737488355328 },
                                   {   281474976710656,    562949953421312,   1125899906842624,   2251799813685248, 4503599627370496, 9007199254740992, 18014398509481984, 36028797018963968 },
                                   { 72057594037927936, 144115188075855872, 288230376151711744, 576460752303423488,
                                     1152921504606846976, 2305843009213693952, 4611686018427387904, 9223372036854775808 } };


            ulong black = 0;
            ulong white = 0;

            for (uint i = 0; i < 8; i++)
            {
                for (uint j = 0; j < 8; j++)
                {
                    if (board.blackRows[i] % board.COLUMNS[j] == 0)
                    {
                        black += AISQUARES[i, j];
                    }
                    if (board.whiteRows[i] % board.COLUMNS[j] == 0)
                    {
                        white += AISQUARES[i, j];
                    }
                }
            }


            //Get the move from the AI DLL
            AIMove nextMove = AIGetMove(board.blackCount, board.whiteCount, black, white, isWhitesTurn, 0);

            //Convert the AIMove to a Move class
            result.Begin.X = checked ((int)nextMove.row);
            result.Begin.Y = checked ((int)nextMove.col);
            if (isWhitesTurn)
            {
                result.End.X = checked ((int)nextMove.row + 1);
            }
            else
            {
                result.End.X = checked ((int)nextMove.row - 1);
            }
            result.End.Y = checked ((int)(nextMove.col + nextMove.target - 1));

            //Return the result
            return(result);
        }
Exemplo n.º 12
0
 void Start()
 {
     nextPosition = transform.position;
     move         = GetComponent <AIMove>();
     data         = GetComponent <PlayerData>();
     pathfinding  = GetComponent <Pathfinding2D>();
     //tiles = MapController.Instance.Tiles;
 }
Exemplo n.º 13
0
 public void AddMove(AIMove move)
 {
     if (possibleMoves == null)
     {
         possibleMoves = new List <AIMove>();
     }
     possibleMoves.Add(move);
 }
Exemplo n.º 14
0
 void Start()
 {
     S_Adire = GetComponent <AIDirector>(); // ディレクター取得
     S_Amove = GetComponent <AIMove>();     // 移動スクリプト取得
     S_Agun  = GetComponent <AIGun>();      // 射撃スクリプト取得
     S_Alife = GetComponent <AILife>();     // ライフスクリプト取得
     RegisterObj();                         // 変身するオブジェクトをリストに格納
     SetOdata(OdataList[mynum]);
 }
Exemplo n.º 15
0
        private void TestApplyMove(string input, AIMove move, string output)
        {
            var grid   = GridTests.CreateGrid(input, 0);
            var solver = new AISolver(grid, new AISettings());
            var grid2  = solver.GetGridWithMove(grid.ToIntArray(), move);

            Assert.AreEqual(output.ToLower().Trim(),
                            Grid.ToString(grid2, true));
        }
Exemplo n.º 16
0
        //For now this will use a simple approach using a visited set instead of a disjoint set approach
        //We can get away with this because there's only one "flow" source point (the unit).
        public List <Coord> getValidMoves(int myX, int myY, Battlefield battlefield)
        {
            if (hasMovedThisTurn)
            {
                return(new List <Coord>());
            }

            HashSet <Coord>        visited    = new HashSet <Coord>();
            PriorityQueue <AIMove> movePQueue = new PriorityQueue <AIMove>();

            movePQueue.Enqueue(new AIMove(myX, myY, 0));
            while (movePQueue.Count() > 0)
            {
                AIMove currentMove = movePQueue.Dequeue();
                //check all four directions
                int[,] moveDirs = new int[, ] {
                    { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 }
                };

                for (int x = 0; x < moveDirs.GetLength(0); x++)
                {
                    int targetX = currentMove.x + moveDirs[x, 0];
                    int targetY = currentMove.y + moveDirs[x, 1];
                    if (targetX < battlefield.map.GetLength(0) && targetY < battlefield.map.GetLength(1) && targetX >= 0 && targetY >= 0)
                    {
                        Stack <Tile> targetTile = battlefield.map[targetX, targetY];
                        if (targetTile.Count != 0)
                        {
                            float  movePointsExpended = currentMove.weight + targetTile.Peek().tileType.Cost(this.moveType);
                            Coord  targetMove         = new Coord(targetX, targetY);
                            AIMove targetMoveAI       = new AIMove(targetX, targetY, movePointsExpended);

                            if (movePointsExpended <= this.numMoveTiles && !visited.Contains(targetMove))
                            {
                                //If it's empty, we can move to it and on it
                                if (battlefield.units[targetX, targetY] == null)
                                {
                                    visited.Add(targetMove);
                                    movePQueue.Enqueue(targetMoveAI);
                                }
                                else if (battlefield.units[targetX, targetY].getCharacter(battlefield) == this.getCharacter(battlefield))
                                {
                                    //If it's our unit, we can move through it, but not on it
                                    movePQueue.Enqueue(targetMoveAI);
                                }
                                else
                                {
                                    //If it's a hostile unit, we can't move to or through it.
                                }
                            }
                        }
                    }
                }
            }

            return(visited.ToList());
        }
Exemplo n.º 17
0
        private void AIputX()
        {
            AIMove bestMove = getBestMove("X");

            DrawO(pen, g, (bestMove.currentcell) + 1);
            cell[bestMove.currentcell, 0] = "1";
            cell[bestMove.currentcell, 1] = "X";
            currentplayer = "0";
        }
Exemplo n.º 18
0
 void Start()
 {
     isColumnBomb   = false;
     isRowBomb      = false;
     isColorBomb    = false;
     isAdjacentBomb = false;
     board          = GameObject.FindWithTag("Board").GetComponent <Board>();
     AIMove         = gameObject.AddComponent <AIMove>();
     findMatches    = GameObject.FindWithTag("FindMatches").GetComponent <FindMatches>();
 }
Exemplo n.º 19
0
    private void OnMoveReset()
    {
        BoardManager.Instance.selectedPiece = null;
        chosenDestination = null;
        chosenMove        = null;
        chosenPiece       = null;

        moveThreatensGeneral = false;
        shouldCharge         = false;
    }
Exemplo n.º 20
0
Arquivo: Bot.cs Projeto: loneNerd/Bang
    public IEnumerator StartMove()
    {
        ImageOfDesk.color = new Color(0.8676471f, 0.7360041f, 0.0f);
        Hand.Add(PackAndDiscard.Instance.GetRandomCard());
        Hand.Add(PackAndDiscard.Instance.GetRandomCard());

        StartCoroutine(AIMove.StartMove());
        yield return(new WaitUntil(() => endMove));

        EndMove();
    }
Exemplo n.º 21
0
 /*
  *  This method sets up the golem in its frozen state. It makes the golem deal no damage
  *  and unable to move before being activated.
  */
 private void setupGolem()
 {
     animator             = GetComponent <Animator>();
     moveScript           = GetComponent <AIMove>();
     animator.speed       = 0;
     rb2D.bodyType        = RigidbodyType2D.Static;
     rb2D.freezeRotation  = true;
     moveScript.canMove   = false;
     moveScript.canSearch = false;
     rb2D.mass            = 5000;
 }
Exemplo n.º 22
0
 void Start()
 {
     scoreManager   = FindObjectOfType <ScoreManager>();
     basePieceValue = 20;
     streakValue    = 1;
     findMatches    = GameObject.FindWithTag("FindMatches").GetComponent <FindMatches>();
     allTiles       = new BackgroundTile[width, height];
     allDots        = new GameObject[width, height];
     currentState   = GameState.move;
     AIMove         = gameObject.AddComponent <AIMove>();
     SetUp();
 }
Exemplo n.º 23
0
 void Update()
 {
     foot.GetComponent <Animator>().SetFloat("Speed", GetComponent <Rigidbody2D>().velocity.magnitude);
     UpdatePosition();
     if (AIMove != null)
     {
         AIMove.Update();
     }
     if (AIWeapon != null)
     {
         AIWeapon.Update();
     }
 }
Exemplo n.º 24
0
    ChessSquare[,] simulateMove(AIMove m)
    {
        ChessSquare[,] newBoard = (ChessSquare[, ])board.Clone();

        newBoard [Mathf.RoundToInt(m.finalPos.x), Mathf.RoundToInt(m.finalPos.y)]             = new ChessSquare();
        newBoard [Mathf.RoundToInt(m.finalPos.x), Mathf.RoundToInt(m.finalPos.y)].pieceSquare = newBoard [Mathf.RoundToInt(m.initialPos.x), Mathf.RoundToInt(m.initialPos.y)].pieceSquare;
        newBoard [Mathf.RoundToInt(m.finalPos.x), Mathf.RoundToInt(m.finalPos.y)].sideSquare  = newBoard [Mathf.RoundToInt(m.initialPos.x), Mathf.RoundToInt(m.initialPos.y)].sideSquare;

        newBoard [Mathf.RoundToInt(m.initialPos.x), Mathf.RoundToInt(m.initialPos.y)]             = new ChessSquare();
        newBoard [Mathf.RoundToInt(m.initialPos.x), Mathf.RoundToInt(m.initialPos.y)].pieceSquare = piece.None;
        newBoard [Mathf.RoundToInt(m.initialPos.x), Mathf.RoundToInt(m.initialPos.y)].sideSquare  = side.None;

        return(newBoard);
    }
Exemplo n.º 25
0
    void Awake()
    {
        S_Amove   = GetComponent <AIMove>();
        S_Aflag   = GetComponent <AIFlag>();
        S_Agun    = GetComponent <AIGun>();
        S_Asearch = GetComponent <AIRouteSearch>();
        S_Alife   = GetComponent <AILife>();
        S_Atrans  = GetComponent <AITransChange>();
        S_Team    = GetComponent <TeamScript>();

        RegisterEvent_ChangeState(SetNowState);
        RegisterEvent_ChangeFindEnemyFlag(SetFindEnemyFlag);
        S_Aflag.RegisterEvent_ChangeHaveFlag(ChangeFlagState);
    }
Exemplo n.º 26
0
    public void FinalMove()
    {
        int bestmove = 0;

        finalAIMove = listofAImove[0];
        for (int i = 1; i < listofAImove.Count; i++)
        {
            if (listofAImove[i].value >= bestmove)
            {
                bestmove    = listofAImove[i].value;
                finalAIMove = listofAImove[i];
            }
        }
    }
Exemplo n.º 27
0
    private void ProtectGeneral()
    {
        chosenMove = Utils.ChooseBestMove(movesAI);

        if (chosenMove == null)
        {
            return;
        }

        BoardManager.Instance.SelectPiece(chosenMove.Attacker.CurrentX, chosenMove.Attacker.CurrentY);
        chosenDestination = new int[] {
            chosenMove.Defender != null ? chosenMove.Defender.CurrentX : chosenMove.AttackX,
            chosenMove.Defender != null ? chosenMove.Defender.CurrentY : chosenMove.AttackY
        };
    }
Exemplo n.º 28
0
    void CreateEnemy()
    {
        Vector3 pos = new Vector3();

        pos.x = UnityEngine.Random.value * 100;
        pos.y = UnityEngine.Random.value * -100;
        GameObject       enemy = vc.CreateEnemy(pos);
        PlayerController ep    = enemy.GetComponent <PlayerController>();

        ep.HP          = 100;
        ep.OnHitEvent += OnEnemyHit;
        ep.GetComponent <AgeCalculator>().DeadAge      = Mathf.FloorToInt(UnityEngine.Random.value * 1000) + 500;
        ep.GetComponent <AgeCalculator>().OnDeadEvent += OnEnemySpeakEvent;
        ep.gameObject.name = "enemy";

        AIMove moveAi = new AIMove();

        moveAi.PlayerController = ep;
        moveAi.ViewController   = vc;
        ep.AIMove = moveAi;

        WongWeaponController wwc = enemy.GetComponent <WongWeaponController>();

        wwc.AimViewController = vc.AimViewController;
        wwc.AddWeapon(new object[] { "步槍(半自動)", 10, .6f, false, 5, 30.0f, 0.5f, false, 0.0f, false, false, 5, false, true });

        /*
         * float wid = UnityEngine.Random.value;
         * if( wid < .6f)
         * {
         *  wwc.AddWeapon(GameConfig.WeaponConfig[1]);
         * }
         * else if( wid < .8f)
         * {
         *  wwc.AddWeapon(GameConfig.WeaponConfig[5]);
         * }
         * else
         * {
         *  wwc.AddWeapon(GameConfig.WeaponConfig[0]);
         * }
         */
        AIWeapon weaponAI = new AIWeapon();

        weaponAI.PlayerController     = ep;
        weaponAI.WongWeaponController = wwc;
        weaponAI.ViewController       = vc;
        ep.AIWeapon = weaponAI;
    }
Exemplo n.º 29
0
    public static AIMove ChooseBestMove(List <AIMove> moves)
    {
        List <AIMove> bestMoves;
        AIMove        chosenMove = null;

        moves = moves.OrderByDescending(move => move.Weight).ToList();

        bestMoves = moves.FindAll(move => move.Weight == moves[0].Weight);

        if (bestMoves.Count > 0)
        {
            chosenMove = bestMoves[Random.Range(0, bestMoves.Count)];
        }

        return(chosenMove);
    }
Exemplo n.º 30
0
        /// <summary>
        /// Test Heuristic.WeightMove
        /// </summary>
        private void TestComboDetection(string gridString, int combosCount)
        {
            var grid = GridTests.CreateGrid(gridString, 0);
            var move = new AIMove()
            {
                gridAfterMove = grid.ToIntArray()
            };
            var h = new AIHeuristic();
            var w = h.WeightMove(move, grid.width, grid.height, 0);

            Assert.AreEqual(combosCount, w.combosCount);
            if (combosCount > 0)
            {
                Assert.AreNotEqual(0, w.total);
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Turns Tank 90 degrees
        /// </summary>
        void AITurnRight()
        {
            Vector3 loc = tankLocation;
            float oldRotation = totalRotation;
            if (totalRotation <= targetRotation && targetRotation != 0)
            {
                loc = tankLocation;
                if (steerRotation != 0)
                {
                    TurnLeft();
                    if (Math.Abs(steerRotation) < 1f / 300f)
                        steerRotation = 0;
                }
                else
                {
                    totalRotation = targetRotation;
                    currentCommand = AIMove.Forward;
                    Vector2 tankLoc = new Vector2((int)(tankLocation.X / 1000),
                        (int)(tankLocation.Z / 1000));
                    tankLoc.X = tankLoc.X + Math.Sign(tankLocation.X);
                    tankLoc.Y = tankLoc.Y + Math.Sign(tankLocation.Z);

                    targetLocation = (tankLoc.X*1000 - 2500 * Math.Sign(tankLocation.X))* (float)Math.Sin(totalRotation) +
                                     (tankLoc.Y*1000 - 2500 * Math.Sign(tankLocation.Z))* (float)Math.Cos(totalRotation);
                }
                oldRotation = totalRotation;
            }
            else if (totalRotation > targetRotation)
            {
                TurnRight();
                MoveForward();
                if (loc == tankLocation)
                    TurnLeft();
            }

            if (oldRotation < totalRotation && targetRotation == 0)
                totalRotation = 0;
        }
Exemplo n.º 32
0
 /// <summary>
 /// Moves the tank 3 blocks
 /// </summary>
 void AIForward()
 {
     //1D tank location
     float tankLoc = tankLocation.X * (float)Math.Sin(totalRotation) +
                     tankLocation.Z * (float)Math.Cos(totalRotation);
     if (tankLoc < targetLocation)
         MoveForward();
     else
         currentCommand = AIMove.None;
 }
Exemplo n.º 33
0
        public Tank(Game game, Vector3 p_tankLocation)
            : base(game)
        {
            tankGame = game;
            isAI = true;
            camera = (GameServices.CameraState)Game.Services.GetService(
                                typeof(GameServices.CameraState));
            audio = (GameServices.AudioLibrary)Game.Services.GetService(
                                typeof(GameServices.AudioLibrary));

            //set the original tank propeties
            frontWheelRotation = 0;
            backWheelRotation = 0;
            steerRotation = 0;
            turretRotation = 0;
            cannonRotation = 0;
            hatchRotation = 0;
            totalRotation = 0;
            tankLocation = p_tankLocation;
            movementSpeed = 10;
            barrelLength = 300;
            health = 1;
            cannonFired = -1.5;
            cannonReloading = false;
            currentCommand = AIMove.None;
        }
Exemplo n.º 34
0
        void CalculateNextCommand()
        {
            //calculate angle to target based on world blocks (1000 unit blocks)
            Vector2 tankLoc = new Vector2((int)(tankLocation.X/1000) ,
                (int)(tankLocation.Z/ 1000 ));
            Vector2 enemyLoc = new Vector2((int)(enemyLocation.X/1000),
                (int)(enemyLocation.Z/ 1000 ));
            //Im exhausted and not thinking clearly so this is most likely unnecessary
            tankLoc.X = tankLoc.X + Math.Sign(tankLocation.X);
            tankLoc.Y = tankLoc.Y + Math.Sign(tankLocation.Z);
            enemyLoc.X = enemyLoc.X + Math.Sign(tankLocation.X);
            enemyLoc.Y = enemyLoc.Y + Math.Sign(tankLocation.Z);
            Vector2 loc = enemyLoc - tankLoc;
            float angle;
            if (loc.Length() != 0)
            {
                angle = (float)Math.Acos(Math.Abs(loc.Y) / (loc.Length()));
                if (loc.X < 0 && loc.Y < 0)
                    angle -= (float)MathHelper.Pi;
                else if (loc.Y < 0)
                    angle = (float)MathHelper.Pi - angle;
                else if (loc.X < 0)
                    angle = - angle;
            }
            else
                angle = 0;

            //calculate rotation relative to tank
            float relAngle = angle- totalRotation;

            if (relAngle > Math.PI)
                relAngle -= (float)Math.PI * 2;
            if (relAngle < -Math.PI)
                relAngle += (float)Math.PI*2;

            //if rotation is right
            if (Math.Abs(relAngle) < MathHelper.PiOver2 )
            {
                //if not too close
                if (loc.Length() > 6)
                {
                    //AI move forward
                    currentCommand = AIMove.Forward;

                    targetLocation = (tankLoc.X * 1000 - 2500 * Math.Sign(tankLocation.X)) * (float)Math.Sin(totalRotation) +
                                     (tankLoc.Y * 1000 - 2500 * Math.Sign(tankLocation.Z)) * (float)Math.Cos(totalRotation);
                }
                else if (loc.Length() < 4)
                {
                    //move back
                    currentCommand = AIMove.Backward;
                    targetLocation = (tankLoc.X * 1000 + 1500 * Math.Sign(tankLocation.X)) * (float)Math.Sin(totalRotation) +
                                     (tankLoc.Y * 1000 + 1500 * Math.Sign(tankLocation.Z)) * (float)Math.Cos(totalRotation);

                }
            }
            //else If tank is not in safe location ( 800 > tank location - i*1500*2 > -800)
            else if ((Math.Abs(tankLoc.X) - 2) % 3 == 0 || (Math.Abs(tankLoc.Y) - 2) % 3 == 0)
            {
                //Move forward
                currentCommand = AIMove.Forward;
            }
            else if (relAngle > 0)
                {
                    currentCommand = AIMove.TurnLeft;
                    targetRotation = totalRotation + MathHelper.PiOver2;
                    if (targetRotation > (float)Math.PI * 2)
                        targetRotation -= (float)Math.PI * 2;
                }
            else if (relAngle < 0)
            {
                //turn right
                currentCommand = AIMove.TurnRight;
                targetRotation = totalRotation - MathHelper.PiOver2;
                if (targetRotation < 0)
                    targetRotation += (float)Math.PI * 2;
            }
        }