Example #1
0
        public void AddRandom_ShouldReturnRightNumBoms()
        {
            //Arrange
            int numberOfBombs = 10;
            int gridRows      = 8;
            int gridColumns   = 8;

            int[,] finalBombArray;
            Bombs myBombs  = new Bombs();
            int   expected = 10;
            int   response = 0;

            //Act
            finalBombArray = myBombs.AddRandom(gridRows, gridColumns, numberOfBombs);

            foreach (int position in finalBombArray)
            {
                if (position == 100)
                {
                    response++;
                }
            }

            //Assert
            Assert.Equal(expected, response);
        }
Example #2
0
        public void Render(GameTime gameTime)
        {
            Arena.DisplayArena(this);
            PlayerOne.DisplayCharacter(this);
            int?IndexToRemove = null;

            for (int i = 0; i < Bombs.Count; i++)
            {
                if (Bombs[i].BombExploded)
                {
                    IndexToRemove = i;
                }
            }
            if (IndexToRemove != null)
            {
                Bombs.RemoveAt((int)IndexToRemove);
            }

            foreach (Bomb bomb in Bombs)
            {
                bomb.DisplayBomb(this);
            }
            if (DisplayDebug)
            {
                DebugUtility.DisplayDebugInfo(this, PlayerOne, Arena.Blocks.FirstOrDefault(), Color.White);
            }
        }
Example #3
0
    private int[,] GetScoreBoard(char[,] board, int range)
    {
        var scoreBoard = new int[HEIGHT, WIDTH];

        for (int y = 0; y < HEIGHT; y++)
        {
            for (int x = 0; x < WIDTH; x++)
            {
                char cell = board[y, x];
                if (!cell.Equals(FLOOR_CELL))
                {
                    scoreBoard[y, x] = 0;
                    continue;
                }

                if (Bombs.Any(b => b.X == x && b.Y == y))
                {
                    scoreBoard[y, x] = 0;
                    continue;
                }

                scoreBoard[y, x] = GetHitCount(board, new Bomb(x, y, 8, range));
            }
        }

        return(scoreBoard);
    }
Example #4
0
 public void Collisisons(GameTime gametime)
 {
     foreach (var item in Teachers)
     {
         item.DeleteTeacherEvent += e => Teachers.Remove(e);
         if (item.Collision(Player))
         {
             break;
         }
         this.Start(bomb_texture, gametime, spriteBatch);
     }
     foreach (var item in Coins)
     {
         item.DeleteCoinEvent += e => Coins.Remove(e);
         if (item.Collision(Player))
         {
             break;
         }
     }
     foreach (var item in Bombs)
     {
         item.DeleteBombEvent += e => Bombs.Remove(e);
         if (item.Collision(Player))
         {
             break;
         }
     }
 }
Example #5
0
 public int GetMaxCountSteps()
 {
     return
         (Math.Max(
              Troops.Any() ? Troops.Max(x => x.Remaining) : 0,
              Bombs.Any() ? Bombs.Max(x => x.Remaining) + Constants.BOMB_EXPLODE_DURATION : 0
              ));
 }
Example #6
0
 /// <summary>
 /// Plants new bomb on map
 /// </summary>
 /// <param name="bomb"></param>
 public void Plant(Bomb bomb)
 {
     if (Bombs.FirstOrDefault(x => x.Position.X == bomb.Position.X && x.Position.Y == bomb.Position.Y) == null)
     {
         Fields[bomb.Position.X, bomb.Position.Y].Bomb = bomb;
         Bombs.Add(bomb);
     }
 }
Example #7
0
 public void Reset()
 {
     Bots.Clear();
     Bombs.Clear();
     Missiles.Clear();
     Explosions.Clear();
     Board = new BoardTile[Board.GetLength(0), Board.GetLength(1)];
     OnArenaChanged();
 }
        public void FromMapData(MapData mapData)
        {
            Turn    = mapData.Turn;
            Walls   = mapData.Walls.Select(item => new Position(item[0], item[1])).ToList();
            Blocks  = mapData.Blocks.Select(item => new Position(item[0], item[1])).ToList();
            Players = mapData.Players;
            Me      = mapData.Players.Find(p => p.Name == Consts.MyName);
            Bombs   = mapData.Bombs;
            Items   = mapData.Items;
            Fires   = mapData.Fires.Select(item => new Position(item[0], item[1])).ToList();

            MinX = Walls.Select(item => item.x).Min();
            int MaxX = Walls.Select(item => item.x).Max();

            SizeX = MaxX - MinX + 1;

            MinY = Walls.Select(item => item.y).Min();
            int MaxY = Walls.Select(item => item.y).Max();

            SizeY = MaxY - MinY + 1;

            logger.Debug($"MinX: {MinX}, SizeX: {SizeX}, MinY {MinY}, SizeY {SizeY}");


            var ary2 = Enumerable.Range(MinY, SizeY).Select(y =>
            {
                return(Enumerable.Range(MinX, SizeX).Select(x =>
                {
                    var cell = new Cell()
                    {
                        X = x,
                        Y = y,
                        Wall = Walls.Any(w => w.x == x && w.y == y),
                        Block = Blocks.Any(b => b.x == x && b.y == y),
                        AnyPlayer = Players.Any(p => p.pos.x == x && p.pos.y == y && p.Name != Consts.MyName),
                        MyPosition = Players.Any(p => p.pos.x == x && p.pos.y == y && p.Name == Consts.MyName),
                        Bomb = Bombs.Find(b => b.pos.x == x && b.pos.y == y),
                        Item = Items.Any(i => i.pos.x == x && i.pos.y == y),
                        Fire = Fires.Any(f => f.x == x && f.y == y)
                    };
                    var pos = new Position(x, y);
                    return new KeyValuePair <Position, Cell>(pos, cell);
                }));
            }).SelectMany(e => e);

            CellDict = new CellDict(ary2, MinX, SizeX, MinY, SizeY);

            SetAboutToFire();

            SetFallingWall();

            CellDict.SetDistance(Me.pos);

            CellDict.Log();
        }
Example #9
0
 private void Awake()
 {
     if (instance != null)
     {
         Destroy(gameObject);
         return;
     }
     DontDestroyOnLoad(gameObject);
     instance  = this;
     bombInput = GetComponentInChildren <Bombs>();
 }
Example #10
0
 private void DropBomb()
 {
     if (bombs != 0)
     {
         Bombs--;
         GameObject newBomb        = Instantiate(bombPrefab, this.transform.position, Quaternion.identity);
         Bombs      bombsBehaviour = newBomb.GetComponent <Bombs>();
         bombsBehaviour.detonating = true;
         bombsBehaviour.StartCoroutine(bombsBehaviour.Explode());
     }
 }
Example #11
0
        public void CreateBombs()
        {
            float bombPos = 200 + (float)this.random.NextDouble() * 500;

            while (!IsDisposed && bombPos < 9400 && (SceneManager.Form == null || !SceneManager.Form.IsDisposed))
            {
                Bombs.Instantiate(new Vector2(0, bombPos));
                bombPos += 80 + (float)this.random.NextDouble() * 800;
                Thread.Sleep((int)Math.Round(random.NextDouble() * 650));
            }
        }
Example #12
0
 private void WindowKeyPressed(object sender, KeyEventArgs e)
 {
     if (e.Code == Keyboard.Key.F3)
     {
         DisplayDebug = !DisplayDebug;
     }
     if (e.Code == Keyboard.Key.Space && PlayerOne.CanDropBomb)
     {
         Bombs.Add(PlayerOne.DropBomb(GameTime.TotalTimeElapsed));
     }
     PlayerOne.KeyUpControls(e);
 }
        private void SetAboutToFire()
        {
            var aboutToExplode = Bombs.Where(b => b.timer == 1);

            foreach (var bomb in aboutToExplode)
            {
                var area = PosAffectedIncludingCausingExplosion(bomb);
                foreach (var pos in area)
                {
                    CellDict[pos].ToBeFire = true;
                }
            }
        }
Example #14
0
 private void BombShoot()
 {
     lock (Lasers)
     {
         BombSound.Play();
         BombCounter++;
         var bomb = new Bomb {
             Shape = { Position = Center }
         };
         bomb.CurrentVelocity = AimDirectionNormal * bomb.MaxVelocity;
         Bombs.Add(bomb);
     }
 }
Example #15
0
 public void AddBomb(Side side, int src, int dst, int remaining)
 {
     if (side == Side.MyOwn)
     {
         Bombs.Add(new Bomb
         {
             Side      = side,
             Dst       = dst,
             Remaining = remaining,
             Src       = src
         });
     }
 }
Example #16
0
 /// <summary>
 /// Placing bombs on the map
 /// </summary>
 public void PlaceBomb(Map Map)
 {
     if (NumberOfBombs > Bombs.Count)
     {
         if (!Map.Tiles[Key].ContainsBomb)
         {
             Map.Tiles[Key].ContainsBomb = true;
             Map.Tiles[Key].WhoPlaced    = this;
             Bomb nova = new Bomb(Map.Tiles[Key].Rectangle.Location, ExplosionRadius);
             Bombs.Add(Key, nova);
             Map.placedBombs.Add(Key, nova);
         }
     }
 }
Example #17
0
 private void OnStateChange(KMGameInfo.State state)
 {
     currentState = state;
     setPins();
     if (currentState != KMGameInfo.State.PostGame)
     {
         arduinoConnection.Stop();
     }
     else
     {
         if (bombState == 0)
         {
             StopCoroutines(); arduinoConnection.sendMSG(String.Format("{0} {1} {2} 0 0 255", RP, GP, BP));
         }                                                                                                                      //For multiple bombs
     }
     if (currentState == KMGameInfo.State.Gameplay)
     {
         //if(arduinoConnection._connected) StartCoroutine(Test());
         bombState   = 0;
         lastStrikes = 0;
         lastSolves  = 0;
         strikeCounts.Clear();
         solveCounts.Clear();
         StartCoroutine(getField());
         StartCoroutine(Warning());
         StartCoroutine(OnStrike());
         StartCoroutine(OnSolve());
         StartCoroutine(CheckForBomb(true));
         StartCoroutine(FactoryCheck());
         StartCoroutine(getBomb());
         StartCoroutine(HandleReflectors());
     }
     else
     {
         currentModuleName = "";
         Modules.Clear();
         StopCoroutine(CheckForBomb(false));
         StopCoroutine(FactoryCheck());
         StopCoroutine(WaitUntilEndFactory());
         StopCoroutine(HandleReflectors());
         BombActive = false;
         Bombs.Clear();
         BombCommanders.Clear();
     }
     if (currentState == KMGameInfo.State.Quitting)
     {
         arduinoConnection.Disconnect();
     }
 }
Example #18
0
        public Battlefield ExportState()
        {
            var arena = new Battlefield(Board.GetLength(0), Board.GetLength(1));

            Board.ForEveryElement((x, y, val) =>
            {
                arena.Board[x, y] = val;
            });

            arena.Bots     = Bots.Select(bot => new TankBlasterBot(bot)).ToList();
            arena.Bombs    = Bombs.Select(bomb => new Bomb(bomb)).ToList();
            arena.Missiles = Missiles.Select(missile => new Missile(missile)).ToList();

            return(arena);
        }
        private void CreateBoard()
        {
            var rnd = new Random();

            for (var i = 0; i < 20; i++)
            {
                for (var j = 0; j < 20; j++)
                {
                    var    rand = rnd.Next(25) + 1;
                    string text;
                    switch (rand)
                    {
                    case 1:
                        text = "1";
                        break;

                    case 2:
                        text = "2";
                        break;

                    case 3:
                        text = "3";
                        break;

                    case 4:
                        text = "4";
                        break;

                    case 5:
                        text = "5";
                        break;

                    default:
                        text = "";
                        break;
                    }
                    var x = rnd.Next(Width - 80);
                    var y = rnd.Next(Height - 50);
                    Bombs.Add(new Bomb
                    {
                        BombId         = text,
                        BombCanvasLeft = x,
                        BombCanvasTop  = y,
                    });
                }
            }
        }
        public int SetBombs()
        {
            int checker = 0;

            for (int i = 0; i < MyWindow.mapa.Grid.Count; i++)
            {
                for (int j = 0; j < MyWindow.mapa.Grid[i].Count; j++)
                {
                    if (MyWindow.mapa.Grid[i][j].WybranaBomba == true)
                    {
                        Bombs.Add(MyWindow.mapa.Grid[i][j]);//agregacja
                        MyWindow.mapa.Grid[i][j].WybranaBomba = false;
                        checker += 1;
                    }
                }
            }
            return(checker);
        }
Example #21
0
 public void Start(Texture2D bomb_texture, GameTime gametime, SpriteBatch spritebatch)
 {
     if (Teachers.Count != 0)
     {
         int randx = random.Next(832, 4928);
         spawn += (float)gametime.ElapsedGameTime.TotalSeconds;
         if (spawn >= 1)
         {
             spawn = 0;
             if (Bombs.Count() < 30)
             {
                 Bombs.Add(new BombQuestion(bomb_texture, new Vector2(randx, 0), spritebatch));
             }
         }
     }
     else
     {
         Bombs.Clear();
     }
 }
        bool IsSafeToPutBomb(Position pos, int power)
        {
            logger.Debug("---------- IsSafeToPutBomb -----------");
            logger.Debug($"pos {pos.ToString()} power {power} ");

            // 置こうとしている場所が、既存の爆弾の誘爆圏内ならfalse
            var isInExplosion = Bombs.Any(bomb =>
            {
                var affects = PosAffectedIncludingCausingExplosion(bomb);
                return(affects.Contains(pos));
            });

            if (isInExplosion)
            {
                logger.Debug($"pos {pos.ToString()} is inExplosion ");
                logger.Debug($"false ");
                logger.Debug("---------- IsSafeToPutBomb -----------");
                return(false);
            }

            // 置いた場合5歩以内に誘爆圏内から逃れられるか?
            var b        = new Bomb(pos, power);
            var affected = PosAffectedIncludingCausingExplosion(b);

            var minEscapeStep = affected.Select(p =>
            {
                return(CellDict[p].Distance);
            }).Min();

            logger.Debug($"minEscapeStep {minEscapeStep} ");
            if (minEscapeStep > 5)
            {
                logger.Debug($"false ");
                logger.Debug("---------- IsSafeToPutBomb -----------");
                return(false);
            }

            logger.Debug($"true ");
            logger.Debug("---------- IsSafeToPutBomb -----------");
            return(true);
        }
Example #23
0
        internal override void Setup(FactoryRoom room)
        {
            base.Setup(room);

            InvoiceData.Enabled = false;

            FactoryBomb[] bombs = Bombs.ToArray();

            Vector3 vanillaBombSpawnPosition = Room.VanillaBombSpawn.position;

            float bombSpacing = Mathf.Min(SPAWN_LENGTH / (bombs.Length - 1.0f), MAXIMUM_BOMB_SPACING);

            vanillaBombSpawnPosition.x -= (bombs.Length - 1) * bombSpacing * 0.5f;

            for (int bombIndex = 0; bombIndex < bombs.Length; ++bombIndex)
            {
                bombs[bombIndex].transform.position = vanillaBombSpawnPosition;
                bombs[bombIndex].SetupHoldableOrigin(vanillaBombSpawnPosition);
                bombs[bombIndex].EnableBomb();

                vanillaBombSpawnPosition.x += bombSpacing;
            }
        }
        public GamePage()
        {
            InitializeComponent();

            // Get the application's ContentManager
            content = (Application.Current as App).Content;
            
            input = new GameInput();
            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            TouchPanel.EnabledGestures = GestureType.DoubleTap | GestureType.Hold | GestureType.Tap;
            bombs = new Bombs();

            CrunchCore.yourWords.Clear();
            CrunchCore.opponentsWords.Clear();

            if(stopwatch == null)
                stopwatch = new StopWatch();

            if (!Initialized)
            {
                stopwatch.Start();
                WordGame.scoreOpponent = 0;
                WordGame.scoreYou = 0;
            }

            quad = new Quad(Vector3.Zero, Vector3.Up, Vector3.Backward, 10, 9);

            if (bombedEvent == null)
                bombedEvent = new EventHandler<BombedArgs>(CrunchCore_OnBombed);

            if (goodGuessEvent == null)
                goodGuessEvent = new EventHandler<GoodGuessArgs>(CrunchCore_OnGoodGuess);
        }
        public int ComputeThreatScore(Position pos)
        {
            var threats = Bombs.Select((b) =>
            {
                if (pos.x - b.pos.x == 0 && Math.Abs(pos.y - b.pos.y) <= b.power)
                {
                    return(new Threat {
                        ThreatLevel = ThreatLevel.Danger, Direction = Direction.North
                    });
                }
                else if (pos.x - b.pos.x == 0 && Math.Abs(b.pos.y - pos.y) <= b.power)
                {
                    return(new Threat {
                        ThreatLevel = ThreatLevel.Danger, Direction = Direction.South
                    });
                }
                else if (pos.y - b.pos.y == 0 && Math.Abs(pos.x - b.pos.x) <= b.power)
                {
                    return(new Threat {
                        ThreatLevel = ThreatLevel.Danger, Direction = Direction.West
                    });
                }
                else if (pos.y - b.pos.y == 0 && Math.Abs(b.pos.x - pos.x) <= b.power)
                {
                    return(new Threat {
                        ThreatLevel = ThreatLevel.Danger, Direction = Direction.East
                    });
                }

                return(new Threat {
                    ThreatLevel = ThreatLevel.None, Direction = Direction.None
                });
            }).Where((threat) => threat.ThreatLevel != ThreatLevel.None);

            return(threats.Count());
        }
Example #26
0
 private void ChageBombType(GameTime gameTime)
 {
     switch (selectedBombType)
     {
         case Bombs.COMMON:
             selectedBombType = Bombs.WATER;
             break;
         case Bombs.WATER:
             selectedBombType = Bombs.ELECTRIC;
             break;
         case Bombs.ELECTRIC:
             selectedBombType = Bombs.MUD;
             break;
         case Bombs.MUD:
             selectedBombType = Bombs.COMMON;
             break;
     }
 }
Example #27
0
        public override void Initialize()
        {
            base.modelName = "Models/Player";
            base.modelScale = 0.1f;

            modelRotation = new Vector3();

            life = 100;
            speed = 1f;

            selectedBombType = Bombs.COMMON;
            possibleBombsCount = 3;
            bombsCount = 0;
            bombRange = 3;

            prevModelPosition = modelPosition;

            min = new Vector3();
            max = new Vector3();
            boundingSphere = new BoundingSphere();
            boundingBox = new BoundingBox();
            UpdateBoundingBox();

            base.Initialize();
        }
Example #28
0
    /// <summary>
    /// Lo utilizamos para procesar el JSON que nos llega desde el servidor.
    /// </summary>
    /// <param name="json">JSON que nos envía el servidor.</param>
    IEnumerator ProcessJSON(JSONNode json)
    {
        if (json["type"].Value == INITIAL_REQUEST)
        {
            MapWidth   = json["width"].AsInt;
            MapHeight  = json["height"].AsInt;
            MapVersion = json["map_version"].AsInt;
            var playerSpawnPosition = json["spawn"].ReadVector3();
            _playerId = json["playerId"].AsInt;

            var obstacleParent = new GameObject("Obstacles").transform;

            var mapNode   = json["map"];
            var obstacles = new int[mapNode.AsArray.Count, mapNode.AsArray[0].AsArray.Count];

            for (int i = 0; i < mapNode.AsArray.Count; i++)
            {
                for (int j = 0; j < mapNode.AsArray[i].AsArray.Count; j++)
                {
                    obstacles[i, j] = mapNode.AsArray[i].AsArray[j].AsInt;
                }
            }

            BuildMap(obstacles);
            var go = Instantiate(PlayerPrefab, playerSpawnPosition, Quaternion.identity);
            _player      = go.GetComponent <Player>();
            _player.Name = PlayerPrefs.GetString("playerName");
            _characters.Add(_player);
            GenerateBorders();
            StartCoroutine(NetworkUpdateLoop());
        }
        else if (json["type"].Value == UPDATE_REQUEST)
        {
            var gameState = json["state"];
            RemainingTime = gameState["timer"].AsInt;
            // Lista de cambios que tenemos que hacer en el mapa
            foreach (var version in gameState["map_changes"].AsArray)
            {
                MapVersion++;
                foreach (var change in version.Value.AsArray)
                {
                    var k = change.Value.AsInt;
                    if (Obstacles.ContainsKey(k))
                    {
                        iTween.ScaleTo(Obstacles[k], iTween.Hash("scale", Vector3.zero, "time", .5f));
                        Destroy(Obstacles[k], 0.5f);
                        Obstacles.Remove(k);
                    }
                }
            }

            foreach (var bomb in gameState["bombs"].AsArray)
            {
                var timer  = bomb.Value["timer"].AsFloat;
                var bombId = bomb.Value["id"].AsInt;

                if (!Bombs.ContainsKey(bombId))
                {
                    Bombs[bombId] = Instantiate(BombPrefab, bomb.Value.ReadVector3(), Quaternion.identity);
                    Bombs[bombId].GetComponent <Bomb>().TimeToExplode = timer;
                    Bombs[bombId].GetComponent <Bomb>().Id            = bombId;
                    SetSortingOrder(Bombs[bombId]);
                }
            }

            foreach (var chest in gameState["chests"].AsArray)
            {
                var chestId = chest.Value["id"].AsInt;

                if (!Chests.ContainsKey(chestId))
                {
                    Chests[chestId] = Instantiate(ChestPrefab, chest.Value.ReadVector3(), Quaternion.identity);
                    Chests[chestId].GetComponent <SpawnedObject>().Id = chestId;
                    SetSortingOrder(Chests[chestId].gameObject);
                }
            }

            // Hacemos una copia de los players que tenemos controlados
            otherPlayersControl = new Dictionary <int, OtherPlayer>(_otherPlayers);

            foreach (var pair in gameState["players"])
            {
                var key   = int.Parse(pair.Key);
                var value = pair.Value;
                // Si estamos actualizando los otros personajes
                if (key != _playerId)
                {
                    if (!_otherPlayers.ContainsKey(key))
                    {
                        // Jugador que no tenemos instanciado. lo instanciamos
                        var otherPlayer = Instantiate(OtherPlayerPrefab).GetComponent <OtherPlayer>();
                        otherPlayer.Name   = value["playerName"];
                        _otherPlayers[key] = otherPlayer;
                    }

                    // Elimino personaje si existe en la partida actual y me quedo con los que ya no esten
                    // para mantener un control de que ha cambiado
                    if (otherPlayersControl.ContainsKey(key))
                    {
                        otherPlayersControl.Remove(key);
                    }
                    // Actualizamos su posicion, velocidad y puntuacion
                    _otherPlayers[key].GetComponent <Character>().SetPosition(new Vector2(pair.Value["position"]["x"], pair.Value["position"]["y"]));
                    _otherPlayers[key].GetComponent <OtherPlayer>().Velocity = pair.Value["velocity"];
                    _otherPlayers[key].GetComponent <OtherPlayer>().Score    = pair.Value["score"];

                    // Si el servidor dice que siguen vivos, actualizar su vida
                    if (_otherPlayers[key].GetComponent <Health>().CurrentHealth > 0)
                    {
                        _otherPlayers[key].GetComponent <Health>().CurrentHealth = pair.Value["health"];
                    }
                    else  // Si dice que estan muertos, destruirlos
                    {
                        _otherPlayers[key].GetComponent <Health>().CurrentHealth = 0;
                    }
                }
                // Si estamos actualizando nuestro personaje
                else
                {
                    // Actualizamos su vida y puntuacion
                    _player.GetComponent <Health>().CurrentHealth = pair.Value["health"];
                    _player.GetComponent <Character>().Score      = pair.Value["score"];
                }

                // Actualizamos la puntuacion, de forma que siempre mantenga la
                // Mas alta
                if (pair.Value["score"].AsInt >= highscore)
                {
                    highscore          = pair.Value["score"].AsInt;
                    highscoreText.text = "Top: " + pair.Value["playerName"] + " " + pair.Value["score"];
                }
            }

            // Los que quedan en el control son los que se han desconectado
            // Han muerto o han sufrido algun problema en red
            // Los eliminamos de otherPlayers
            if (otherPlayersControl.Count > 0)
            {
                foreach (var pair in otherPlayersControl)
                {
                    _otherPlayers[pair.Key].GetComponent <Health>().CurrentHealth = 0;
                    Destroy(_otherPlayers[pair.Key].gameObject);
                    _otherPlayers.Remove(pair.Key);
                }
                // Si hemos usado el diccionario de control, lo reestablecemos
                otherPlayersControl.Clear();
            }
        }
        yield return(null);
    }
 public void RemoveBomb(Bomb bomb)
 {
     Bombs.Remove(bomb);
     CellDict[bomb.pos].Bomb = null;
 }
 public void AddBomb(Bomb bomb)
 {
     Bombs.Add(bomb);
     CellDict[bomb.pos].Bomb = bomb;
 }
Example #31
0
 /// <summary>
 /// Game Turn
 ///     One game turn is computed as follows:
 ///          Move existing troops and bombs
 ///          Execute user orders
 ///          Produce new cyborgs in all factories
 ///          Solve battles
 ///          Make the bombs explode
 ///          Check end conditions
 /// </summary>
 public void DoNextMove()
 {
     foreach (var factory in Factories.Where(x => x.Side != Side.Neutral))
     {
         if (factory.InactivityDaysLeft <= 0)
         {
             factory.TroopsCount += factory.Income;
         }
         else
         {
             factory.InactivityDaysLeft--;
         }
     }
     foreach (var troop in Troops)
     {
         troop.Remaining--;
     }
     foreach (var bomb in Bombs)
     {
         bomb.Remaining--;
     }
     //Solve battles
     foreach (var troopGroup in Troops.Where(x => x.Remaining == 0).GroupBy(x => x.Dst))
     {
         var factory        = Factories[troopGroup.First().Dst];
         int troopToFactory =
             troopGroup.Where(x => x.Side == Side.MyOwn).Sum(x => x.Size) -
             troopGroup.Where(x => x.Side == Side.Enemy).Sum(x => x.Size);
         if (troopToFactory == 0)
         {
             continue;
         }
         Side troopRestSide = troopToFactory > 0 ? Side.MyOwn : Side.Enemy;
         troopToFactory = Math.Abs(troopToFactory);
         var sign = 1;
         //            if (factory.Side == Side.Neutral  ? troopRestSide == Side.Enemy : (factory.Side != troopRestSide))
         if (factory.Side != troopRestSide)
         {
             sign = -1;
         }
         factory.TroopsCount += troopToFactory * sign;
         if (factory.TroopsCount < 0)
         {
             factory.Side        = troopRestSide;
             factory.TroopsCount = Math.Abs(factory.TroopsCount);
         }
     }
     //Bomb explode
     foreach (var bomb in Bombs.Where(x => x.Remaining == 0))
     {
         var factory = Factories[bomb.Dst];
         factory.TroopsCount -= Math.Max(10, factory.TroopsCount / 2);
     }
     Bombs.RemoveAll(bomb => {
         if (bomb.Remaining > 0)
         {
             return(false);
         }
         var factory                = Factories[bomb.Dst];
         factory.TroopsCount       -= Math.Min(factory.TroopsCount, Math.Max(10, factory.TroopsCount / 2));
         factory.InactivityDaysLeft = Constants.BOMB_EXPLODE_DURATION;
         return(true);
     });
     //
     Troops = Troops.Where(x => x.Remaining > 0).ToList();
     CurrentGameTick++;
     //        foreach (var factory in Factories) {
     //            if (factory.Side == Side.Neutral) {
     //                if (factory.TroopsCount != 0)
     //                    factory.Side = factory.TroopsCount > 0 ? Side.MyOwn : Side.Enemy;
     //            }
     //            else if (factory.TroopsCount < 0)
     //                factory.Side = factory.Side == Side.Enemy ? Side.MyOwn : Side.Enemy;
     //        }
 }
Example #32
0
 public void ClearMovedEntities()
 {
     Troops.Clear();
     Bombs.Clear();
 }
Example #33
0
    public override void AddBomb()
    {
        Bombs newBomb = new Bombs();

        base.AddBomb(newBomb);
    }
 private void PutBomb(GameTime gameTime, Bombs bType)
 {
     if (BombsCount < PlayerProfile.PossibleBombsCount)
     {
         var pos = GetBombPosition();
         switch(bType)
         {
             case Bombs.Common:
                 models.AddBomb(new FireBomb(game, pos, this, gameTime));
                 break;
             case Bombs.Water:
                 models.AddBomb(new WaterBomb(game, pos, this, gameTime));
                 break;
             case Bombs.Electric:
                 models.AddBomb(new ElectricBomb(game, pos, this, gameTime));
                 break;
             case Bombs.Mud:
                 models.AddBomb(new MudBomb(game, pos, this, gameTime));
                 break;
         }
         BombsCount++;
     }
 }