コード例 #1
0
        protected override void ExecuteInsertUnitCommand(string[] commandWords)
        {
            Unit unit = null;
            switch (commandWords[1])
            {
                case "Tank":
                    unit = new Tank(commandWords[2]);
                    break;
                case "Marine":
                    unit = new Marine(commandWords[2]);
                    break;
                case "Parasite":
                    unit = new Parasite(commandWords[2]);
                    break;
                case "Queen":
                    unit = new Queen(commandWords[2]);
                    break;
                default:
                    break;
            }

            if (unit != null)
            {
                base.InsertUnit(unit);
            }

            base.ExecuteInsertUnitCommand(commandWords);
        }
コード例 #2
0
ファイル: Roulette.cs プロジェクト: nitzanbueno/TanksDropTwo
 public override void InstantAction( TimeSpan gameTime )
 {
     Random r = new Random();
     chosenTank = Tanks[ r.Next( Tanks.Count ) ];
     if ( chosenTank.IsAlive )
     {
         Explosion explod = new Explosion( gameTime );
         explod.Initialize( Game );
         explod.LoadContent( Game.Content, Game.ScreenWidth, Game.ScreenHeight );
         explod.Position = chosenTank.Position;
         Game.QueueEntity( explod );
         Game.explod.Play();
         chosenTank.Destroy( gameTime );
     }
     else
     {
         Explosion explod = new Explosion( gameTime, 2000, ( float )Game.Settings[ "BlastRadius" ].Item2, false );
         explod.Initialize( Game );
         explod.LoadContent( Game.Content, Game.ScreenWidth, Game.ScreenHeight );
         explod.Position = chosenTank.Position;
         Game.QueueEntity( explod );
         reverseExplod.Play();
         chosenTank.IsAlive = true;
     }
 }
コード例 #3
0
ファイル: Bullet.cs プロジェクト: sttema/Battle_City
 public Bullet(int X, int Y, int bullet_speed, int bullet_course, Tank Tank_owner)
     : base(X, Y)
 {
     tank_owner = Tank_owner;
     base.image = bullet_image;
     speed = bullet_speed;
     course = bullet_course;
     Rotate_to_course(course);
     switch (course)
     {
         case 0:
             y_speed = -speed;
             base.x += 13;
             base.y -= 8;
             break;
         case 1:
             x_speed = speed;
             base.x += 32;
             base.y += 13;
             break;
         case 2:
             y_speed = speed;
             base.x += 13;
             base.y += 32;
             break;
         case 3:
             x_speed = -speed;
             base.x -= 8;
             base.y += 13;
             break;
     }
 }
コード例 #4
0
ファイル: TestTank.cs プロジェクト: T3H40/Worldofwartanks
        public void testAwake()
        {
            Tank tank=new Tank();
            tank.Awake();

            Assert.AreEqual(Time.time,tank.LastSynchronizationTime);
        }
コード例 #5
0
        public ParticulaPo(float velocidadeMedia, float perturbacao, Random random, Color cor, Tank tank, Matrix worldSistema)
        {
            this.worldSistema = worldSistema;

            //Inicializar o array de vértices (dois vértices para cada particula)
            vertexes = new VertexPositionColor[2];

            Vector3 posicao = Vector3.Zero;
            posicao.X = (float)random.NextDouble() * 1.8f * 0.5f - 0.5f;

            //Inicilizar propriedades
            this.posicao = posicao;
            this.velocidadeMedia = velocidadeMedia;
            this.perturbacao = perturbacao;
            this.totalTimePassed = 0;

            //Gerar os dois vértices da particula, um ligeiramente mais abaixo que o outro
            vertexes[0] = new VertexPositionColor(this.posicao, cor);
            vertexes[1] = new VertexPositionColor(this.posicao - new Vector3(0, 0.01f, 0), cor);

            direcao = Vector3.Zero;
            //Calcular direção da particula
            direcao.X = tank.inclinationMatrix.Backward.X * (float)random.NextDouble() * (1f * perturbacao - perturbacao);
            direcao.Z = tank.inclinationMatrix.Backward.Z * (float)random.NextDouble() * (1f * perturbacao - perturbacao);
            direcao += new Vector3(0, 0.01f, -0.01f);
            direcao.Normalize();
            direcao *= (float)random.NextDouble() * velocidadeMedia + perturbacao;
        }
コード例 #6
0
 public ITank ManufactureTank(string name, double attackPoints, double defensePoints)
 {
     // Tank (name) manufactured - attack: (attack); defense: (defense)
     ITank tank = new Tank(name, attackPoints, defensePoints);
     //Console.WriteLine("Tank {0} manufactured - attack: {1}; defense: {2}", tank.Name, tank.AttackPoints, tank.DefensePoints);
     return tank;
 }
コード例 #7
0
 public override bool Control( GameEntity control, TimeSpan gameTime, Microsoft.Xna.Framework.Input.KeyboardState keyState )
 {
     if ( selectedTank == null )
     {
         List<Tank> TanksCopy = new List<Tank>( Tanks );
         if ( TanksCopy.Count == 0 )
             return true;
         int i = r.Next( TanksCopy.Count );
         while ( TanksCopy[ i ].Controller is MindController )
         {
             TanksCopy.RemoveAt( i );
             i = r.Next( TanksCopy.Count );
             if ( TanksCopy.Count == 0 )
                 return true;
         }
         selectedTank = TanksCopy[ i ];
     }
     if ( controlKeys == null )
     {
         controlKeys = selectedTank.Keys;
         selectedTank.Keys = Owner.Keys;
         Owner.Keys = new KeySet( Keys.None, Keys.None, Keys.None, Keys.None, Owner.Keys.KeyPlace, Keys.None );
     }
     base.Control( control, gameTime, keyState );
     return true;
 }
コード例 #8
0
        public override BitmapBase Draw(Tank tank)
        {
            var outline = new Pen(new SolidColorBrush(Colors.Black), 1);
            var outlineInner = new Pen(new SolidColorBrush(Color.FromArgb(50, 255, 255, 255)), 1);

            var hsv = ColorHSV.FromColor(BackColor.GetColorWpf(tank));
            var brush = new LinearGradientBrush
            {
                GradientStops = new GradientStopCollection
                {
                    new GradientStop(hsv.ToColorWpf(), 0.1),
                    new GradientStop(hsv.ScaleValue(0.56).ToColorWpf(), 0.49),
                    new GradientStop(hsv.ScaleValue(0.39).ToColorWpf(), 0.51),
                    new GradientStop(hsv.ScaleValue(0.56).ToColorWpf(), 0.9),
                },
                StartPoint = new Point(0, 0),
                EndPoint = new Point(0, 1),
            };

            return Ut.NewBitmapWpf(ParentStyle.IconWidth, ParentStyle.IconHeight, dc =>
            {
                dc.DrawRectangle(brush, outline, new Rect(0.5, 1.5, ParentStyle.IconWidth - 1, ParentStyle.IconHeight - 3));
                dc.DrawRectangle(null, outlineInner, new Rect(1.5, 2.5, ParentStyle.IconWidth - 3, ParentStyle.IconHeight - 5));
            }).ToBitmapRam();
        }
コード例 #9
0
 public SistemaParticulasPo(Random random, int nParticulas, Tank tank)
 {
     //Inicializar as propriedades
     this.nParticulasSegundo = nParticulas;
     particulas = new List<ParticulaPo>(1000);
     offset = new Vector3(0, 0f, -0.15f);
 }
コード例 #10
0
 protected override void ExecuteInsertUnitCommand(string[] commandWords)
 {
     switch (commandWords[1])
     {
         case "Tank":
             var tank = new Tank(commandWords[2]);
             this.InsertUnit(tank);
             break;
         case "Marine":
             var marine = new Marine(commandWords[2]);
             this.InsertUnit(marine);
             break;
         case "Parasite":
             var parasite = new Parasite(commandWords[2]);
             this.InsertUnit(parasite);
             break;
         case "Queen":
             var queen = new Queen(commandWords[2]);
             this.InsertUnit(queen);
             break;
         default:
             base.ExecuteInsertUnitCommand(commandWords);
             break;
     }
 }
コード例 #11
0
        private void inserirNovaParticula(Random random, Tank tank)
        {
            if (tank.moving)
            {
                rotacao = Matrix.CreateTranslation(offset) * Matrix.CreateFromQuaternion(tank.inclinationMatrix.Rotation);
                Vector3 transformedOffset = Vector3.Transform(offset, rotacao);

                Vector3 posicao = Vector3.Zero;

                float velocidadeMedia = 0.01f;
                float perturbacao = 0.005f;

                Matrix worldSistema = rotacao;
                worldSistema.Translation = transformedOffset + tank.position;

                Color cor;
                //Inicilizar propriedades
                if (tank.position.Y < 1.5f)
                {
                    cor = Color.Blue;
                }
                else
                {
                    cor = Color.Chocolate;
                }

                //Adicionar nova particula à lista de particulas deste sistema
                particulas.Add(new ParticulaPo(velocidadeMedia, perturbacao, random, cor, tank, worldSistema));
            }
        }
コード例 #12
0
        public void Painter_should_paint_tank_with_given_color()
        {
            var painter = new Painter();
            var tank = new Tank("REG");
            painter.Paint(tank, Color.DarkOliveGreen);

            Assert.AreEqual(Color.DarkOliveGreen, tank.Color);
        }
コード例 #13
0
ファイル: Bullet.cs プロジェクト: StarTrekCenter/TankWar
 private void Hit(Tank tank)
 {
     if(this.owner == null || this.owner != tank && (this.owner.team == 0 || this.owner.team != tank.team))
     {
         tank.Hit(this.damage);
         Destroy(this.gameObject);
     }
 }
コード例 #14
0
ファイル: ScrapFactory.cs プロジェクト: hatefi-arman/Modules
        public ScrapDetail CreateScrapDetail(Scrap scrap, double rob, double price, Currency currency, Good good, GoodUnit unit, Tank tank)
        {
            var scrapDetail = new ScrapDetail(rob, price, currency, good, unit, tank, scrap,
                scrapDomainService, tankDomainService, currencyDomainService,
                goodDomainService, goodUnitDomainService);

            return scrapDetail;
        }
コード例 #15
0
 public void Draw(GraphicsDevice graphics, BasicEffect efeito, Tank tank)
 {
     //Desenhar as particulas geridas por este sistema
     foreach (ParticulaPo particula in particulas)
     {
         particula.Draw(graphics, efeito);
     }
 }
コード例 #16
0
ファイル: MainWindow.cs プロジェクト: isuru-c/thunder-tank
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        Build ();
        myTank = new Tank ();

        pictureBox.
    }
コード例 #17
0
ファイル: FlipEffect.cs プロジェクト: rstarkov/TankIconMaker
 public override BitmapBase Apply(Tank tank, BitmapBase layer)
 {
     if (FlipHorz)
         layer.FlipHorz();
     if (FlipVert)
         layer.FlipVert();
     return layer;
 }
コード例 #18
0
ファイル: ShiftEffect.cs プロジェクト: rstarkov/TankIconMaker
 public override BitmapBase Apply(Tank tank, BitmapBase layer)
 {
     if (ShiftX == 0 && ShiftY == 0)
         return layer;
     var result = new BitmapRam(layer.Width, layer.Height);
     result.DrawImage(layer, ShiftX, ShiftY);
     return result;
 }
コード例 #19
0
ファイル: MachineFactory.cs プロジェクト: damy90/Telerik-all
        public ITank ManufactureTank(string name, double attackPoints, double defensePoints)
        {
            IsNameInUse(name);

            Tank tank = new Tank(name, attackPoints, defensePoints);
            machines.Add(tank);
            return tank;
        }
コード例 #20
0
ファイル: GasInterchange.cs プロジェクト: Booljayj/BREACH
 //connect a new tank to the interchange
 public void AddTank(Tank tank, string channel)
 {
     if (channels.ContainsKey(channel)) {
         if (!channels[channel].Contains(tank)) {
             channels[channel].Add(tank);
         }
     }
 }
コード例 #21
0
ファイル: CollisionDetector.cs プロジェクト: neutmute/TankWar
 public void Detect(Shell shell, Tank tank)
 {
     var hit = IsHit(shell.Point, tank.Target);
     if (hit)
     {
         _notifyHitMethod(tank.Owner, shell);
     }
 }
コード例 #22
0
ファイル: GasInterchange.cs プロジェクト: Booljayj/BREACH
 //disconnect a tank from the interchange
 public void RemoveTank(Tank tank, string channel)
 {
     if (channels.ContainsKey(channel)) {
         if (channels[channel].Contains(tank)) {
             channels[channel].Remove(tank);
         }
     }
 }
コード例 #23
0
ファイル: Tank.cs プロジェクト: eiseneker/ghost-game
 // Use this for initialization
 void Start()
 {
     myRigidBody = GetComponent<Rigidbody2D>();
     tank = this;
     points = 0;
     originalScale = transform.localScale;
     foodMeter = 0;
 }
コード例 #24
0
 public override BitmapBase Apply(Tank tank, BitmapBase layer)
 {
     if (_blur == null || _blur.Radius != Radius)
         lock (this)
             if (_blur == null || _blur.Radius != Radius)
                 _blur = new GaussianBlur(Radius);
     layer.Blur(_blur, Edge);
     return layer;
 }
コード例 #25
0
ファイル: Shockwave.cs プロジェクト: nitzanbueno/TanksDropTwo
 public Knockback( Tank Owner, float MaxDistance, float SpeedFactor )
     : base()
 {
     this.owner = Owner;
     this.position = Owner.Position;
     this.maxdist = MaxDistance;
     this.startspeed = MaxDistance * ( 1 - speedFactor );
     this.speedFactor = SpeedFactor;
 }
コード例 #26
0
        public void AddTank(string teamName, Tank tank)
        {
            if (!Teams.ContainsKey(teamName))
                AddTeam(teamName);
            Teams[teamName].Enqueue(tank);

            if(currTank == null)
                currTank = tank;
        }
コード例 #27
0
 public void Update(Random random, GameTime gameTime, Tank tank)
 {
     //Atualizar as particulas de chuva
     foreach (ParticulaPo particula in particulas)
     {
         particula.Update(gameTime);
     }
     //Verificar particulas que devem morrer e criar novas particulas para as substituir
     matarERenascerParticulas(random, tank);
 }
コード例 #28
0
        public void Shoot(Tank enemy)
        {
            if (this.Shells == 0)
            {
                throw new TankException("Not enough shells to shoot");
            }

            enemy.Health -= ShellDamage;
            this.Shells--;
        }
コード例 #29
0
    public override void Move(Tank self, World world, Move move)
    {
        myOtherSelf.historyX[world.Tick] = self.X;
        myOtherSelf.historyY[world.Tick] = self.Y;

        if (IsDead(teammates[0]))
        {
            myOtherSelf.CommonMove(self, world, move);
            return;
        }
        teammate = teammates[0];

        bool forward;
        Bonus bonus = GetBonus(out forward);

        #if TEDDY_BEARS
        //bonus = null;
        #endif
        bool shootOnlyToVictim = false;
        cornerX = cornerY = -1;
        if (bonus != null && (world.Tick > runToCornerTime || bonus.Type == BonusType.AmmoCrate))
        {
            MoveToBonus(bonus, forward);
        }
        else
        {
            MoveBackwards();
        }

        Tank victim = GetVictim();//GetWithSmallestDistSum();
        if (victim != null)
            TurnToMovingTank(victim, false);

        TryShoot(victim, shootOnlyToVictim);

        /*if (world.Tick > runToCornerTime && AliveEnemyCnt() <= 1)
        {
            var tank = GetMostAngryEnemy();
            if (tank != null)
                StayPerpendicular(tank);
        }*/

        if (AliveEnemyCnt() == 1)
        {
            Tank enemy = PickEnemy();
            if(MustRush(enemy))
                MoveTo(enemy, true);
        }

        bool bonusSaves = BonusSaves(self, bonus);

        if (world.Tick > runToCornerTime && victim != null && !HaveTimeToTurn(victim) && !bonusSaves)
            TurnToMovingTank(victim, true);
    }
コード例 #30
0
ファイル: AI.cs プロジェクト: pedroabgmarques/IP3D---3DTank
 //Dirigir-se para uma determinada posição
 public static Vector3 moverParaDirecao(Tank tank, Vector3 posicao, bool alvoSargento)
 {
     if (tank.sargento && alvoSargento)
     {
         return (posicao - tank.position) / 50f;
     }
     else
     {
         return (posicao - tank.position) / 20f;
     }
 }
コード例 #31
0
 private Tank tank;                   // "has a" combination
 public Dectorator(Tank tank)
 {
     this.tank = tank;
 }
コード例 #32
0
ファイル: ProjectilePatch.cs プロジェクト: FLSoz/WeaponAimMod
            public static void Postfix(ref TargetAimer __instance)
            {
                try
                {
                    Visible  target   = __instance.Target;
                    FireData fireData = __instance.GetComponentInParent <FireData>();
                    if (fireData != null && __instance.HasTarget && target.IsNotNull() && !Singleton.Manager <ManPauseGame> .inst.IsPaused && ((target.type == ObjectTypes.Vehicle && target.tank.IsNotNull()) || (target.type == ObjectTypes.Block && target.block.IsNotNull())))
                    {
                        TankBlock block = (TankBlock)ProjectilePatch.m_Block.GetValue(__instance);
                        Tank      tank  = (bool)(UnityEngine.Object)block ? block.tank : (Tank)null;

                        string        name      = block ? block.name : "UNKNOWN";
                        TimedFuseData timedFuse = __instance.GetComponentInParent <TimedFuseData>();

                        bool enemyWeapon = tank == null || !ManSpawn.IsPlayerTeam(tank.Team);

                        if (((enemyWeapon && WeaponAimSettings.EnemyLead) || (!enemyWeapon && WeaponAimSettings.PlayerLead)) && !(fireData is FireDataShotgun) && fireData.m_MuzzleVelocity > 0.0f)
                        {
                            Vector3     AimPointVector = (Vector3)ProjectilePatch.m_TargetPosition.GetValue(__instance);
                            Vector3     relDist        = AimPointVector - __instance.transform.position;
                            WeaponRound bulletPrefab   = fireData.m_BulletPrefab;

                            bool useGravity = false;
                            if (bulletPrefab != null && bulletPrefab is Projectile projectile && projectile.rbody != null)
                            {
                                if (projectile is MissileProjectile missileProjectile)
                                {
                                    useGravity = missileProjectile.rbody.useGravity || WeaponAimSettings.BallisticMissile;
                                }
                                else
                                {
                                    useGravity = projectile.rbody.useGravity;
                                }
                            }

                            Rigidbody rbodyTank = __instance.GetComponentInParent <Tank>().rbody;

                            Vector3 angularToggle    = rbodyTank.angularVelocity;
                            Vector3 relativeVelocity = (__instance.Target.rbody ? __instance.Target.rbody.velocity : Vector3.zero) - (rbodyTank.velocity + angularToggle);

                            float   time = relDist.magnitude / fireData.m_MuzzleVelocity;
                            Vector3 relativeAcceleration = target.type == ObjectTypes.Vehicle ? TargetManager.GetAcceleration(target.tank) : Vector3.zero;

                            if (useGravity)
                            {
                                relativeAcceleration -= Physics.gravity;
                            }

                            float   exactTime    = BallisticEquations.SolveBallisticArc(__instance.transform.position, fireData.m_MuzzleVelocity, AimPointVector, relativeVelocity, relativeAcceleration);
                            Vector3 adjIntercept = AimPointVector + (relativeVelocity * time);
                            if (exactTime != Mathf.Infinity)
                            {
                                time         = exactTime;
                                adjIntercept = AimPointVector + (relativeVelocity * time) + ((relativeAcceleration + (useGravity ? Physics.gravity : Vector3.zero)) / 2 * time * time);
                            }

                            if (timedFuse != null)
                            {
                                timedFuse.m_FuseTime = time;
                            }

                            ProjectilePatch.m_TargetPosition.SetValue(__instance, adjIntercept);
                        }
                        // Either disabled for enemy, or is a beam weapon
                        else
                        {
                            if (timedFuse != null)
                            {
                                timedFuse.m_FuseTime = 0.0f;
                            }
                        }
                    }
                }
                catch (NullReferenceException exception)
                {
                    Console.WriteLine("[WeaponAimMod] TargetAimer.UpdateTarget PATCH FAILED");
                    Console.WriteLine(exception.Message);
                }
            }
コード例 #33
0
        public static bool Prefix(ref TargetAimer __instance, ref float rotateSpeed)
        {
            TankBlock block = (TankBlock)m_Block.GetValue(__instance);

            // Has a target
            if (WeaponAimSettings.OctantAim && block && block.tank && __instance.HasTarget)
            {
                Tank tank        = block.tank;
                bool enemyWeapon = !ManSpawn.IsPlayerTeam(tank.Team);

                if (enemyWeapon && WeaponAimSettings.EnemyLead || !enemyWeapon && WeaponAimSettings.PlayerLead)
                {
                    Vector3 targetWorld = (Vector3)m_TargetPosition.GetValue(__instance);
                    Func <Vector3, Vector3> aimDelegate = (Func <Vector3, Vector3>)AimDelegate.GetValue(__instance);
                    if (__instance.HasTarget && aimDelegate != null)
                    {
                        targetWorld = aimDelegate(targetWorld);
                    }

                    // Check if we can aim
                    List <GimbalAimer> gimbalAimers = (List <GimbalAimer>)m_GimbalAimers.GetValue(__instance);
                    bool canAim = true;
                    foreach (GimbalAimer aimer in gimbalAimers)
                    {
                        if (__instance.Target && canAim)
                        {
                            canAim = aimer.CanAim(targetWorld);
                            if (!canAim)
                            {
                                break;
                            }
                        }
                    }

                    // If we can aim, is all good - continue as normal (will do aim calculation for gimbals twice)
                    if (canAim)
                    {
                        return(true);
                    }

                    IModuleWeapon moduleWeapon = block.GetComponent <IModuleWeapon>();

                    OctantVision octantVision = tank.GetComponent <OctantVision>();
                    if (octantVision && gimbalAimers.Count > 0)
                    {
                        float[] XConstraints = new float[2];
                        float[] YConstraints = new float[2];

                        GimbalAimer XGimbal    = null;
                        GimbalAimer YGimbal    = null;
                        GimbalAimer FreeGimbal = null;

                        bool free = false;
                        foreach (GimbalAimer aimer in gimbalAimers)
                        {
                            if (aimer.rotationAxis == GimbalAimer.AxisConstraint.X)
                            {
                                XConstraints = aimer.rotationLimits;
                                XGimbal      = aimer;
                            }
                            else if (aimer.rotationAxis == GimbalAimer.AxisConstraint.Y)
                            {
                                YConstraints = aimer.rotationLimits;
                                YGimbal      = aimer;
                            }
                            else
                            {
                                FreeGimbal = aimer;
                                free       = true;
                                break;
                            }
                        }
                        int[] octants;
                        if (free)
                        {
                            octants = new int[8] {
                                0, 1, 2, 3, 4, 5, 6, 7
                            };
                            OctantVision.Limits limits = new OctantVision.Limits
                            {
                                localToBlock  = block.trans.InverseTransformPoint(FreeGimbal.transform.position),
                                localToGimbal = Vector3.zero,
                                localToBarrel = Vector3.zero,

                                XConstraints = new float[2],
                                YConstraints = new float[2]
                            };
                            Visible betterTarget = octantVision.GetFirstVisibleTechIsEnemy(octants, limits, block, null, null, aimDelegate);
                            if (betterTarget)
                            {
                                Target.SetValue(__instance, betterTarget);
                                UpdateTarget.Invoke(__instance, null);
                            }
                        }
                        else if (XGimbal || YGimbal)
                        {
                            if (moduleWeapon != null)
                            {
                                GimbalAimer parentGimbal = null;
                                GimbalAimer childGimbal  = null;
                                if (XGimbal)
                                {
                                    if (YGimbal)
                                    {
                                        if (YGimbal.transform.IsChildOf(XGimbal.transform))
                                        {
                                            parentGimbal = XGimbal;
                                            childGimbal  = YGimbal;
                                        }
                                        else
                                        {
                                            parentGimbal = YGimbal;
                                            childGimbal  = XGimbal;
                                        }
                                    }
                                    else
                                    {
                                        parentGimbal = XGimbal;
                                    }
                                }
                                else
                                {
                                    parentGimbal = YGimbal;
                                }

                                Vector3 gimbalBlockLocalPosition = block.trans.InverseTransformPoint(parentGimbal.transform.position);
                                Vector3 gimbalLocalPosition      = Vector3.zero;
                                if (parentGimbal && childGimbal)
                                {
                                    gimbalLocalPosition = parentGimbal.transform.InverseTransformPoint(childGimbal.transform.position);
                                }

                                Vector3     fireLocalPosition = Vector3.zero;
                                GimbalAimer localChildGimbal  = childGimbal ? childGimbal : parentGimbal;
                                if (moduleWeapon is ModuleWeaponGun moduleWeaponGun)
                                {
                                    CannonBarrel[] cannonBarrels = (CannonBarrel[])m_CannonBarrels.GetValue(moduleWeaponGun);
                                    foreach (CannonBarrel cannonBarrel in cannonBarrels)
                                    {
                                        fireLocalPosition += localChildGimbal.transform.InverseTransformPoint(cannonBarrel.projectileSpawnPoint.position);
                                    }
                                    fireLocalPosition /= cannonBarrels.Length;
                                }
                                else if (moduleWeapon is ModuleWeaponFlamethrower moduleWeaponFlamethrower)
                                {
                                    fireLocalPosition = localChildGimbal.transform.InverseTransformPoint(moduleWeaponFlamethrower.GetFireTransform().position);
                                }

                                OctantVision.Limits limits = new OctantVision.Limits
                                {
                                    localToBlock  = gimbalBlockLocalPosition,
                                    localToGimbal = gimbalLocalPosition,
                                    localToBarrel = fireLocalPosition,

                                    XConstraints = XConstraints,
                                    YConstraints = YConstraints
                                };
                                octants = OctantVision.GetOctants(limits, parentGimbal, block);

                                Visible betterTarget = octantVision.GetFirstVisibleTechIsEnemy(octants, limits, block, XGimbal, YGimbal, aimDelegate);
                                if (betterTarget != null)
                                {
                                    Target.SetValue(__instance, betterTarget);
                                    UpdateTarget.Invoke(__instance, null);
                                }
                            }
                        }
                    }
                }
            }
            return(true);
        }
コード例 #34
0
        static void Main(string[] args)
        {
            Random rand = new Random();
            int countPantera = 0;
            int countT34 = 0;
            int side = 1;
            string menu = "";
            int size = 5;

            while (true)
            {
                Console.WriteLine("Press 1 to start Tank Game");
                Console.WriteLine("Press any key to exit");
                menu = Console.ReadLine();
                if (menu == "1")
                {
                    Tank[] T34 = new Tank[size];
                    Tank[] Pantera = new Tank[size];

                    Console.WriteLine();
                    Console.WriteLine("Calculating Tanks Parameters. Please wait");
                    for (int i = 0; i < T34.Length; i++)
                    {
                        T34[i] = new Tank("T34 " + (i + 1));
                        Thread.Sleep(rand.Next(850, 950));
                        Console.Write('*');
                        Console.Write(' ');
                    }
                    for (int i = 0; i < Pantera.Length; i++)
                    {
                        Pantera[i] = new Tank("Pantera " + (i + 1));
                        Thread.Sleep(rand.Next(600, 800));
                        Console.Write('*');
                        Console.Write(' ');
                    }

                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("Choose your side: ");
                    Console.WriteLine("1 - T34 ");
                    Console.WriteLine("2 - Pantera ");
                    Console.WriteLine("Any key for random ");
                    string menuSide = Console.ReadLine();
                    if (menuSide == "1")
                    {
                        side = 1;
                    }
                    else if (menuSide == "2")
                    {
                        side = 2;
                    }
                    else
                    {
                        side = rand.Next(1, 3);
                        Console.WriteLine("Your side is " + side);
                    }
                    Console.WriteLine("Loading");
                    for (int i = 0; i < 10; i++)
                    {
                        Console.Write('*');
                        Console.Write(' ');
                        Thread.Sleep(350);
                    }
                    Console.WriteLine();
                    Console.WriteLine();

                    for (int i = 0; i < size; i++)
                    {
                        string result = T34[i] * Pantera[i];
                        Console.WriteLine(result);
                        Console.WriteLine();
                        if (result.Contains("T34"))
                        {
                            countT34++;
                        }
                        else if (result.Contains("Pantera"))
                        {
                            countPantera++;
                        }
                    }
                    Console.WriteLine();

                    try
                    {
                        if (side == 1 && countT34 > countPantera)
                        {
                            throw new Exception("You Win! For Soviet Union!");
                        }
                        else if (side == 2 && countT34 < countPantera)
                        {
                            throw new Exception("You Win! Hail Hydra!");

                        }
                        else if ((side == 1 || side == 2) && countT34 == countPantera)
                        {
                            throw new Exception("Draw!");
                        }

                        else throw new Exception("You Lose! Motherland will never forgive you!");
                    }

                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                }

                else Environment.Exit(0);
            }
            Console.ReadLine();

        }
コード例 #35
0
 public override void Use(Tank tank)
 {
     tank.SetHealth(30);//这里写让tank血量恢复的代码
     //玩家索引是传入的参数
     //tank.SetOil()之类的
 }
コード例 #36
0
 public TankWrapper(Tank tank, float aiDelay)
 {
     _tank    = tank;
     _aiDelay = aiDelay;
 }
コード例 #37
0
 private void SetTank(Tank tank, double val)
 {
     tank.Value = val;
 }
コード例 #38
0
ファイル: RoomHandler.cs プロジェクト: mengtest/TankTCP
    private void OnReqEnterRoom(UserToken token, SocketModel model)
    {
        ReqEnterRoom req = SerializeUtil.Deserialize <ReqEnterRoom>(model.message);
        AccountData  acc = CacheManager.instance.GetAccount(token.accountid);

        if (acc.roomid != 0)
        {
            return;
        }

        Room r = CacheManager.instance.GetWaitRoom((EBattle)req.battleType, req.limitNumber);

        r.AddAccount(acc);

        RspEnterRoom rsp = new RspEnterRoom();

        rsp.roomid = r.roomid;
        NetworkManager.Send <RspEnterRoom>(token, (int)MsgID.RspEnterRoom, rsp);

        //房间满
        if (r.accounts.Count >= r.limtNum)
        {
            Battle b = null;
            if (req.battleType == (int)EBattle.Arena)
            {
                b = CacheManager.instance.CreateArena(r.limtNum, r.accounts);
            }
            else
            {
                b = CacheManager.instance.CreateSurvival(r.limtNum, r.accounts);
            }

            //清空roomid
            for (int i = 0; i < r.accounts.Count; i++)
            {
                r.accounts[i].roomid = 0;
            }

            //通知战斗开始
            NotifyBattleStart notify = new NotifyBattleStart();
            notify.battleid    = b.battleid;
            notify.battleType  = req.battleType;
            notify.numberLimit = req.limitNumber;

            List <Tank> tanks = b.GetALLTanks();

            for (int i = 0; i < tanks.Count; i++)
            {
                Tank    t1  = tanks[i];
                TankDTO dto = new TankDTO();
                dto.id       = t1.uid;
                dto.hp       = t1.hp;
                dto.nickName = t1.nickName;
                dto.pos      = Tools.ToVec_3(t1.pos);
                dto.color    = Tools.UC2TC(t1.color);
                dto.team     = (int)t1.team;
                notify.tanks.Add(dto);
            }
            MsgSender.SendAll <NotifyBattleStart>(r.accounts, (int)MsgID.NotifyBattleStart, notify);
            CacheManager.instance.RemoveRoom(r.roomid);
        }
    }
コード例 #39
0
        public unsafe override BitmapBase Apply(RenderTask renderTask, BitmapBase layer)
        {
            Tank tank = renderTask.Tank;

            using (layer.UseWrite())
            {
                // Just scale the brightness and alpha channels so as to normalize the maximum value.
                // This is crude but gives good results; a better algorithm would try to fit the histogram
                // to a predefined standard by scaling non-linearly.
                double maxBrightness = -1;
                double maxAlpha      = -1;
                for (int y = 0; y < layer.Height; y++)
                {
                    byte *ptr = layer.Data + y * layer.Stride;
                    byte *end = ptr + layer.Width * 4;
                    while (ptr < end)
                    {
                        byte alpha = *(ptr + 3);
                        if (alpha > 0) // there are a lot of non-black pixels in the fully-transparent regions
                        {
                            if (NormalizeBrightness)
                            {
                                double brightness = *(ptr + 0) * 0.0722 + *(ptr + 1) * 0.7152 + *(ptr + 2) * 0.2126;
                                if (brightness > maxBrightness)
                                {
                                    maxBrightness = brightness;
                                }
                            }
                            if (NormalizeAlpha)
                            {
                                if (alpha > maxAlpha)
                                {
                                    maxAlpha = alpha;
                                }
                            }
                        }
                        ptr += 4;
                    }
                }

                double scaleBrightness = (double)MaxBrightness / maxBrightness;
                double scaleAlpha      = (double)MaxAlpha / maxAlpha;
                for (int y = 0; y < layer.Height; y++)
                {
                    byte *ptr = layer.Data + y * layer.Stride;
                    byte *end = ptr + layer.Width * 4;
                    while (ptr < end)
                    {
                        byte alpha = *(ptr + 3);
                        if (alpha > 0)
                        {
                            if (NormalizeBrightness)
                            {
                                if (Grayscale)
                                {
                                    double brightness = *(ptr + 0) * 0.0722 + *(ptr + 1) * 0.7152 + *(ptr + 2) * 0.2126;
                                    *(ptr + 0) = *(ptr + 1) = *(ptr + 2) = (byte)(brightness * scaleBrightness).ClipMax(255);
                                }
                                else
                                {
                                    // TODO: the clipping here alters the hue. Ideally the color should be clipped without altering hue, by increasing brightness until white.
                                    *(ptr + 0) = (byte)(*(ptr + 0) * scaleBrightness).ClipMax(255);
                                    *(ptr + 1) = (byte)(*(ptr + 1) * scaleBrightness).ClipMax(255);
                                    *(ptr + 2) = (byte)(*(ptr + 2) * scaleBrightness).ClipMax(255);
                                }
                            }
                            else if (Grayscale)
                            {
                                double brightness = *(ptr + 0) * 0.0722 + *(ptr + 1) * 0.7152 + *(ptr + 2) * 0.2126;
                                *(ptr + 0) = *(ptr + 1) = *(ptr + 2) = (byte)brightness;
                            }
                            if (NormalizeAlpha)
                            {
                                *(ptr + 3) = (byte)(alpha * scaleAlpha);
                            }
                        }
                        ptr += 4;
                    }
                }
            }
            return(layer);
        }
コード例 #40
0
 static void PrintBattleResult(Tank T1, ConsoleColor C1, Tank T2, ConsoleColor C2)
 {
     Console.ForegroundColor = C1; Console.Write(T1 + "\n");
     Console.ForegroundColor = C2; Console.Write(T2);
     Console.ForegroundColor = ConsoleColor.White;
 }
コード例 #41
0
 private void Awake()
 {
     academy = FindObjectOfType <AquariumAcademy>();
     tank    = gameObject.transform.parent.GetComponent <Tank>();
 }
コード例 #42
0
public class DecoratorA : Decorator { //ConcreteDecoratorA
    public DecoratorA(Tank tank) : base(tank)
    {
    }
コード例 #43
0
ファイル: Combat.cs プロジェクト: thadeusb/MagitekRoutine
        public static async Task <bool> Execute()
        {
            if (!Core.Me.HasTarget || !Core.Me.CurrentTarget.ThoroughCanAttack())
            {
                return(false);
            }

            if (await CustomOpenerLogic.Opener())
            {
                return(true);
            }

            if (BotManager.Current.IsAutonomous)
            {
                Movement.NavigateToUnitLos(Core.Me.CurrentTarget, 4);
            }

            if (await SingleTarget.LowBlow())
            {
                return(true);
            }
            if (await SingleTarget.Interject())
            {
                return(true);
            }
            if (await Buff.Stance())
            {
                return(true);
            }

            if (Utilities.Routines.Warrior.OnGcd)
            {
                if (await Defensive.ExecuteTankBusters())
                {
                    return(true);
                }
                if (await Defensive.Defensives())
                {
                    return(true);
                }
            }

            if (WarriorSettings.Instance.IsMainTank)
            {
                if (await Tank.Provoke(WarriorSettings.Instance))
                {
                    return(true);
                }
                if (await SingleTarget.TomahawkOnLostAggro())
                {
                    return(true);
                }
                if (await Buff.InnerReleaseMainTank())
                {
                    return(true);
                }
                if (await Aoe.SteelCyclone())
                {
                    return(true);
                }
                if (await SingleTarget.InnerBeast())
                {
                    return(true);
                }
            }
            else
            {
                if (await Buff.InnerReleaseOffTank())
                {
                    return(true);
                }
                if (await SingleTarget.InnerReleaseFellCleaveSpam())
                {
                    return(true);
                }
                if (await Aoe.Decimate())
                {
                    return(true);
                }
                if (await SingleTarget.FellCleave())
                {
                    return(true);
                }
            }

            if (await SingleTarget.Onslaught())
            {
                return(true);
            }
            if (await Buff.Beserk())
            {
                return(true);
            }
            if (await Buff.Infuriate())
            {
                return(true);
            }
            if (await SingleTarget.Upheaval())
            {
                return(true);
            }
            if (await Aoe.Overpower())
            {
                return(true);
            }

            // Main Rotation Part

            if (await SingleTarget.StormsEye())
            {
                return(true);
            }
            if (await SingleTarget.StormsPath())
            {
                return(true);
            }
            if (await SingleTarget.Maim())
            {
                return(true);
            }
            if (await SingleTarget.HeavySwing())
            {
                return(true);
            }
            return(await SingleTarget.Tomahawk());
        }
コード例 #44
0
        public Visible GetFirstVisibleTechIsEnemy(int[] octants, Limits limits, TankBlock block, GimbalAimer XGimbal, GimbalAimer YGimbal, Func <Vector3, Vector3> aimDelegate)
        {
            Visible overallBest = null;

            bool hasX = limits.XConstraints[0] != limits.XConstraints[1];
            bool hasY = limits.YConstraints[0] != limits.YConstraints[1];

            List <int> sortedOctantId = new List <int>();

            int[] indices = new int[octants.Length];
            for (int i = 0; i < octants.Length; i++)
            {
                indices[i] = 0;
                if (this.m_Visibles[octants[i]].Count > 0)
                {
                    sortedOctantId.Add(i);
                }
            }
            sortedOctantId.Sort((int a, int b) => (int)(this.m_Visibles[octants[a]][indices[a]].distSq * 1000f - this.m_Visibles[octants[b]][indices[b]].distSq * 1000f));

            // Continuously keep a sorted list of visibles to go through
            while (sortedOctantId.Count > 0)
            {
                int currentOctantId = sortedOctantId[0];
                sortedOctantId.RemoveAt(0);

                int octant = octants[currentOctantId];
                int index  = indices[currentOctantId];

                // Check if targetable. If it is, then return it
                Visible.ConeFiltered filteredVisible = this.m_Visibles[octant][index];
                if (filteredVisible.visible != null)
                {
                    Visible visible = filteredVisible.visible;
                    Tank    tank    = filteredVisible.visible.tank;

                    bool    canAim      = true;
                    Vector3 targetWorld = tank.transform.position;
                    if (aimDelegate != null)
                    {
                        targetWorld = aimDelegate(targetWorld);
                    }

                    float leeway = Mathf.Max(5.0f, (float)Math.Atan2(tank.blockBounds.size.magnitude / 2, (targetWorld - block.transform.position).magnitude) * Mathf.Rad2Deg);
                    float YAngle = 0f, XAngle = 0f;
                    if (hasY && YGimbal)
                    {
                        Vector3 targetRelative = YGimbal.transform.parent.InverseTransformDirection(targetWorld - YGimbal.transform.position);
                        YAngle = Mathf.Atan2(targetRelative.x, targetRelative.z) * Mathf.Rad2Deg;
                        canAim = YAngle >= limits.YConstraints[0] - leeway && YAngle <= limits.YConstraints[1] + leeway;
                    }
                    if (canAim && hasX && XGimbal)
                    {
                        Vector3 targetRelative = XGimbal.transform.parent.InverseTransformDirection(targetWorld - XGimbal.transform.position);
                        XAngle = Mathf.Atan2(-targetRelative.y, targetRelative.z) * Mathf.Rad2Deg;
                        canAim = XAngle >= limits.XConstraints[0] - leeway && XAngle <= limits.XConstraints[1] + leeway;
                    }

                    if (canAim)
                    {
                        RaycastHit raycastHit;
                        float      length         = Mathf.Max(block.tank.blockBounds.size.magnitude, 1f);
                        Vector3    barrelRelative = limits.localToBarrel + limits.localToGimbal + limits.localToBlock;

                        Vector3 ray = (targetWorld - block.transform.position).normalized;

                        if (!Physics.Raycast(block.transform.position + (ray * barrelRelative.magnitude), ray, out raycastHit, length, Globals.inst.layerTank.mask, QueryTriggerInteraction.Ignore) || raycastHit.rigidbody != block.tank.rbody)
                        {
                            float sqrMagnitude = (base.Tech.trans.position - tank.trans.position).sqrMagnitude;
                            return(visible);
                        }
                    }
                }

                indices[currentOctantId]++;
                // If stuff left in visibles, add to sorted list
                if (this.m_Visibles[octant].Count > index + 1)
                {
                    int sortIndex = sortedOctantId.BinarySearch(currentOctantId, (int a, int b) => (int)(this.m_Visibles[octants[a]][indices[a]].distSq * 1000f - this.m_Visibles[octants[b]][indices[b]].distSq * 1000f));
                    if (sortIndex < 0)
                    {
                        sortIndex = ~sortIndex;
                    }
                    sortedOctantId.Insert(sortIndex, currentOctantId);
                }
            }
            return(overallBest);
        }
コード例 #45
0
 public string CreateTank(Tank tank)
 {
     return(_tankRepository.Add(tank));
 }
コード例 #46
0
 public void AddTank(Tank t)
 {
     tanks.Add(t);
 }
コード例 #47
0
        public static async Task <bool> Combat()
        {
            if (!Core.Me.HasTarget || !Core.Me.CurrentTarget.ThoroughCanAttack())
            {
                return(false);
            }

            if (await CustomOpenerLogic.Opener())
            {
                return(true);
            }

            if (BotManager.Current.IsAutonomous)
            {
                Movement.NavigateToUnitLos(Core.Me.CurrentTarget, 4);
            }

            if (await Tank.Interrupt(WarriorSettings.Instance))
            {
                return(true);
            }
            if (await Buff.Defiance())
            {
                return(true);
            }

            if (Weaving.GetCurrentWeavingCounter() < 2 && Spells.HeavySwing.Cooldown.TotalMilliseconds > 800 + BaseSettings.Instance.UserLatencyOffset)
            {
                if (await Defensive.ExecuteTankBusters())
                {
                    return(true);
                }
                if (await Defensive.Defensives())
                {
                    return(true);
                }
                if (await Buff.Beserk())
                {
                    return(true);
                }
                if (await Buff.InnerRelease())
                {
                    return(true);
                }
                if (await Buff.Infuriate())
                {
                    return(true);
                }
                if (await Buff.Equilibrium())
                {
                    return(true);
                }
                if (await SingleTarget.Onslaught())
                {
                    return(true);
                }
                if (await SingleTarget.Upheaval())
                {
                    return(true);
                }
            }

            if (WarriorSettings.Instance.UseDefiance)
            {
                if (await Tank.Provoke(WarriorSettings.Instance))
                {
                    return(true);
                }
                if (await SingleTarget.TomahawkOnLostAggro())
                {
                    return(true);
                }
            }

            if (await Aoe.SteelCyclone())
            {
                return(true);
            }
            if (await Aoe.Decimate())
            {
                return(true);
            }
            if (await Aoe.InnerReleaseDecimateSpam())
            {
                return(true);
            }
            if (await Aoe.Overpower())
            {
                return(true);
            }
            if (await SingleTarget.InnerBeast())
            {
                return(true);
            }
            if (await SingleTarget.FellCleave())
            {
                return(true);
            }
            if (await SingleTarget.InnerReleaseFellCleaveSpam())
            {
                return(true);
            }

            // Main Rotation Part

            if (await SingleTarget.StormsEye())
            {
                return(true);
            }
            if (await SingleTarget.StormsPath())
            {
                return(true);
            }
            if (await SingleTarget.Maim())
            {
                return(true);
            }
            if (await SingleTarget.HeavySwing())
            {
                return(true);
            }
            return(await SingleTarget.Tomahawk());
        }
コード例 #48
0
ファイル: GarageMenu.cs プロジェクト: Siran1994/HillsOfSteel
    private IEnumerator TankScrollRoutine()
    {
        float            velocity      = 0f;
        float            multiple      = 1f / (float)(tanks.Length - 1);
        int              lastIndex     = -1;
        float            timeSinceLast = 0f;
        CustomScrollRect sr            = tankScrollRect;

        sr.horizontalNormalizedPosition = (float)tankIndex * multiple;
        while (true)
        {
            float target = (float)tankIndex * multiple;
            int   curr   = tankIndex;
            if (!tankScrollRect.IsDragging)
            {
                sr.horizontalNormalizedPosition = Mathf.SmoothDamp(sr.horizontalNormalizedPosition, target, ref velocity, 0.1f);
            }
            else
            {
                SetTank(Mathf.RoundToInt(Mathf.Clamp01(sr.horizontalNormalizedPosition + Mathf.Sign(sr.velocity.x) * (0f - multiple) * 0.4f) / multiple));
            }
            Vector3 localPosition = tankSlider.transform.localPosition;
            localPosition.x = sr.horizontalNormalizedPosition * tankOffset * (float)(tanks.Length - 1) + tankCameraOffset;
            tankSlider.transform.localPosition = localPosition;
            if (curr != lastIndex && !MenuController.GetMenu <BundlePopup>().isActiveAndEnabled)
            {
                if (garageShootRoutine != null)
                {
                    StopCoroutine(garageShootRoutine);
                    for (int i = 0; i < tanks.Length; i++)
                    {
                        tanks[i].Shoot(val: false);
                    }
                }
                if (timeSinceLast > 0.75f)
                {
                    Tank tank = Variables.instance.GetTank(curr);
                    if (tank.bullet.type == BulletType.Missile || tank.bullet.type == BulletType.Laser)
                    {
                        garageShootRoutine = StartCoroutine(MissileShoot(tanks[curr]));
                    }
                    else if (tank.bullet.type == BulletType.Flame)
                    {
                        garageShootRoutine = StartCoroutine(FlamerShoot(tanks[curr]));
                    }
                    else if (tank.bullet.type == BulletType.Small)
                    {
                        garageShootRoutine = StartCoroutine(BulletShoot(tanks[curr]));
                    }
                    else if (tank.bullet.type == BulletType.Lightning)
                    {
                        garageShootRoutine = StartCoroutine(LightningShoot(tanks[curr]));
                    }
                    else
                    {
                        tanks[curr].Shoot();
                    }
                    lastIndex = tankIndex;
                }
                else
                {
                    timeSinceLast += Time.deltaTime;
                }
            }
            yield return(null);

            if (curr != tankIndex)
            {
                timeSinceLast = 0f;
                lastIndex     = -1;
            }
        }
    }
コード例 #49
0
    public override void ActionTick()
    {
        if (waitingDraggable != null && waitingDraggable)
        {
            ai.movement.SetMoveTarget(waitingDraggable.transform.position, 100f);

            Vector2 delta = waitingDraggable.transform.position - craft.transform.position;
            if (ai.movement.targetIsInRange() && shellcore.GetTractorTarget() != null && shellcore.GetTractorTarget().gameObject.GetComponent <EnergySphereScript>() == null)
            {
                shellcore.SetTractorTarget(waitingDraggable);
            }
        }
        switch (state)
        {
        case BattleState.Attack:
            if (shellcore.GetTractorTarget() == null)
            {
                if (attackTurret == null)
                {
                    Turret t           = null;
                    float  minDistance = float.MaxValue;
                    for (int i = 0; i < AIData.entities.Count; i++)
                    {
                        if (AIData.entities[i] != null && AIData.entities[i] &&
                            AIData.entities[i] is Turret &&
                            AIData.entities[i].faction == craft.faction &&
                            AIData.entities[i].GetComponentInChildren <WeaponAbility>() != null &&
                            AIData.entities[i].GetComponentInChildren <WeaponAbility>().GetID() != 16)
                        {
                            float d = (AIData.entities[i].transform.position - craft.transform.position).sqrMagnitude;
                            if (d < minDistance)
                            {
                                t           = AIData.entities[i] as Turret;
                                minDistance = d;
                            }
                        }
                    }
                    attackTurret = t;
                }
                else
                {
                    float d = (attackTurret.transform.position - shellcore.transform.position).sqrMagnitude;
                    if (d < 150)
                    {
                        shellcore.SetTractorTarget(attackTurret.GetComponent <Draggable>());
                    }
                }
            }

            // go to nearest enemy construct, attack units / turrets if in visual range
            if ((primaryTarget == null && nextSearchTime < Time.time) || nextSearchTime < Time.time - 3f)
            {
                // get nearest construct
                primaryTarget  = AirCraftAI.getNearestEntity <AirConstruct>(craft.transform.position, craft.faction, true);   //TODO: Exclude turrets?
                nextSearchTime = Time.time + 1f;

                //if(primaryTarget)
                //    Debug.Log("AggroTarget: " + primaryTarget.name + " Factions: " + primaryTarget.faction + " - " + craft.faction);
            }
            if (primaryTarget != null)
            {
                ai.movement.SetMoveTarget(primaryTarget.transform.position);
                //craft.MoveCraft((primaryTarget.transform.position - craft.transform.position).normalized);
            }
            //TODO: AI Attack:
            // action sequences
            // Use existing turrets:
            // -Drag torpedo turrets to enemy bunkers
            // -Drag siege turrets to outposts
            // ground attack location = own bunker location
            // drag tanks from one platform to another "LandPlatformGenerator.getEnemiesOnPlatform(Vector2 platformLocation, int faction)"?
            // how to react to different pressures on land and air?
            break;

        case BattleState.Defend:
            // destroy enemy units around base, ignore everything outside siege range
            if (primaryTarget && !primaryTarget.GetIsDead())
            {
                ai.movement.SetMoveTarget(primaryTarget.transform.position);
            }
            // buy a turret matching the biggest threat's element, if possible
            break;

        case BattleState.Collect:
            // go from outpost to outpost, (also less fortified enemy outposts [count enemy units nearby {TODO}]) and collect energy
            if (findNewTarget || collectTarget == null)
            {
                // Find new target
                float      minD       = float.MaxValue;
                EnergyRock targetRock = null;
                int        maxEnergy  = -1;

                for (int i = 0; i < AIData.energyRocks.Count; i++)
                {
                    if (AirCraftAI.getEnemyCountInRange(AIData.energyRocks[i].transform.position, 10f, craft.faction) > 2)
                    {
                        continue;
                    }

                    int energy = 0;
                    for (int j = 0; j < AIData.energySpheres.Count; j++)
                    {
                        if ((AIData.energySpheres[j].transform.position - AIData.energyRocks[i].transform.position).sqrMagnitude < 16)
                        {
                            energy++;
                        }
                    }
                    float d = (craft.transform.position - AIData.energyRocks[i].transform.position).sqrMagnitude;
                    if ((maxEnergy < energy || d * 1.5f < minD || (maxEnergy == energy && d < minD)) && AIData.energyRocks[i] != collectTarget)
                    {
                        minD       = d;
                        maxEnergy  = energy;
                        targetRock = AIData.energyRocks[i];
                    }
                }
                collectTarget = targetRock;

                if (collectTarget != null)
                {
                    findNewTarget = false;
                }

                //Debug.LogFormat("Faction {0} collect target: {1}", craft.faction, collectTarget);
            }
            if (collectTarget != null)
            {
                ai.movement.SetMoveTarget(collectTarget.transform.position);
                if (ai.movement.targetIsInRange())
                {
                    findNewTarget = true;
                }
            }
            break;

        case BattleState.Fortify:
            // TODO: place turrets
            // set primary target to an outpost with least defending turrets
            if (fortificationTarget == null || !fortificationTarget)
            {
                UpdateTargetInfluences();

                float closestToZero = float.MaxValue;

                for (int i = 0; i < AITargets.Count; i++)
                {
                    if (Mathf.Abs(AITargets[i].influence) < closestToZero && AITargets[i].entity.faction == shellcore.faction)
                    {
                        fortificationTarget = AITargets[i].entity;
                    }
                }
            }
            else if (attackTurret == null || !attackTurret)
            {
                UpdateTargetInfluences();

                float minDistance = float.MaxValue;

                for (int i = 0; i < AIData.entities.Count; i++)
                {
                    if (AIData.entities[i] is Turret)
                    {
                        float d  = (craft.transform.position - AIData.entities[i].transform.position).sqrMagnitude;
                        float d2 = (fortificationTarget.transform.position - AIData.entities[i].transform.position).sqrMagnitude;
                        if (d < minDistance && d2 > 150f)
                        {
                            minDistance  = d;
                            attackTurret = AIData.entities[i] as Turret;
                        }
                    }
                }
                if (attackTurret == null)
                {
                    state = BattleState.Attack;
                    ActionTick();
                    nextStateCheckTime += 1f;
                    return;
                }
            }
            else if (shellcore.GetTractorTarget() != attackTurret)
            {
                ai.movement.SetMoveTarget(attackTurret.transform.position, 100f);
                if (ai.movement.targetIsInRange())
                {
                    var target = shellcore.GetTractorTarget();
                    if (target != null && target)
                    {
                        if (target.gameObject.GetComponent <EnergySphereScript>() == null)
                        {
                            shellcore.SetTractorTarget(attackTurret.GetComponent <Draggable>());
                        }
                    }
                }
            }
            else
            {
                Vector2 turretDelta    = fortificationTarget.transform.position - attackTurret.transform.position;
                Vector2 targetPosition = (Vector2)fortificationTarget.transform.position + turretDelta.normalized * 16f;
                Vector2 delta          = targetPosition - (Vector2)craft.transform.position;
                if (turretDelta.sqrMagnitude < 16f)
                {
                    shellcore.SetTractorTarget(null);
                }
            }

            break;

        default:
            break;
        }

        int energyCount = 0;

        // always collect energy
        if (shellcore.GetTractorTarget() != null && shellcore.GetTractorTarget().gameObject.GetComponent <EnergySphereScript>() == null)
        {
            for (int i = 0; i < AIData.energySpheres.Count; i++)
            {
                if ((AIData.energySpheres[i].transform.position - shellcore.transform.position).sqrMagnitude < 150)
                {
                    energyCount++;
                    if (shellcore.GetTractorTarget() != null)
                    {
                        waitingDraggable = shellcore.GetTractorTarget();
                        shellcore.SetTractorTarget(null);
                    }
                }
            }
        }
        else if (shellcore.GetTractorTarget() == null && waitingDraggable != null)
        {
            for (int i = 0; i < AIData.energySpheres.Count; i++)
            {
                if ((AIData.energySpheres[i].transform.position - shellcore.transform.position).sqrMagnitude < 150)
                {
                    energyCount++;
                }
            }
            if (energyCount == 0)
            {
                shellcore.SetTractorTarget(waitingDraggable);
                if (shellcore.GetTractorTarget() == waitingDraggable)
                {
                    waitingDraggable = null;
                }
            }
        }

        // always buy more turrets/tanks
        if (shellcore.unitsCommanding.Count < shellcore.GetTotalCommandLimit() && energyCount == 0)
        {
            for (int i = 0; i < AIData.vendors.Count; i++)
            {
                if ((AIData.vendors[i].transform.position - craft.transform.position).sqrMagnitude < 380f && AIData.vendors[i].faction == craft.faction)
                {
                    IVendor vendor = AIData.vendors[i] as IVendor;

                    if (vendor.GetVendingBlueprint() == null)
                    {
                        continue;
                    }

                    int itemIndex = -1;

                    if (state == BattleState.Attack)
                    {
                        bool ownGroundExists = false;
                        for (int j = 0; j < AIData.entities.Count; j++)
                        {
                            if (AIData.entities[j].faction == craft.faction && AIData.entities[j].Terrain == Entity.TerrainType.Ground)
                            {
                                ownGroundExists = true;
                                break;
                            }
                        }
                        if (!ownGroundExists && enemyGroundTargets(true) && shellcore.GetPower() >= 150)
                        {
                            // Attack & enemy holds all ground
                            itemIndex = vendor.GetVendingBlueprint().getItemIndex("Torpedo Turret");
                        }
                        else
                        {
                            if (shellcore.GetPower() >= 200)
                            {
                                itemIndex = vendor.GetVendingBlueprint().getItemIndex("Missile Turret");
                            }
                            else if (shellcore.GetPower() >= 100)
                            {
                                itemIndex = vendor.GetVendingBlueprint().getItemIndex("Defense Turret");
                            }
                        }
                    }
                    if (itemIndex == -1)
                    {
                        for (int j = 0; j < vendor.GetVendingBlueprint().items.Count; j++)
                        {
                            if (vendor.GetVendingBlueprint().items[j].cost <= shellcore.GetPower() && shellcore.unitsCommanding.Count < shellcore.GetTotalCommandLimit())
                            {
                                if (itemIndex != -1 && vendor.GetVendingBlueprint().items[j].cost <= vendor.GetVendingBlueprint().items[itemIndex].cost) // more expensive => better (TODO: choose based on the situation)
                                {
                                    continue;
                                }

                                if (vendor.GetVendingBlueprint().items[j].entityBlueprint.intendedType == EntityBlueprint.IntendedType.Tank && !enemyGroundTargets(true)) //TODO: get turret / tank attack category from somewhere else
                                {
                                    continue;
                                }

                                itemIndex = j;
                            }
                        }
                    }

                    if (itemIndex != -1)
                    {
                        GameObject creation = new GameObject();
                        creation.transform.position = AIData.vendors[i].transform.position;
                        switch (vendor.GetVendingBlueprint().items[itemIndex].entityBlueprint.intendedType)
                        {
                        case EntityBlueprint.IntendedType.Turret:
                            creation.name = "Turret";
                            Turret tur = creation.AddComponent <Turret>();
                            tur.blueprint = vendor.GetVendingBlueprint().items[itemIndex].entityBlueprint;
                            tur.SetOwner(shellcore);
                            tur.faction = craft.faction;
                            shellcore.SetTractorTarget(creation.GetComponent <Draggable>());
                            break;

                        case EntityBlueprint.IntendedType.Tank:
                            creation.name = "Tank";
                            Tank tank = creation.AddComponent <Tank>();
                            tank.blueprint   = vendor.GetVendingBlueprint().items[itemIndex].entityBlueprint;
                            tank.enginePower = 250;
                            tank.SetOwner(shellcore);
                            tank.faction = craft.faction;
                            break;

                        default:
                            break;
                        }
                        shellcore.sectorMngr.InsertPersistentObject(vendor.GetVendingBlueprint().items[itemIndex].entityBlueprint.name, creation);
                        creation.GetComponent <Entity>().spawnPoint = AIData.vendors[i].transform.position;
                        shellcore.AddPower(-vendor.GetVendingBlueprint().items[itemIndex].cost);

                        break;
                    }
                }
            }
        }
    }
コード例 #50
0
        protected override void OnUpdate()
        {
            base.OnUpdate();

            if (HP <= 50)
            {
                Move(Match.instance.GetRebornPos(Team));
            }
            else
            {
                bool    hasStar        = false;
                float   nearestDist    = float.MaxValue;
                Vector3 nearestStarPos = Vector3.zero;
                foreach (var pair in Match.instance.GetStars())
                {
                    Star s = pair.Value;
                    if (s.IsSuperStar)
                    {
                        hasStar        = true;
                        nearestStarPos = s.Position;
                        break;
                    }
                    else
                    {
                        float dist = (s.Position - Position).sqrMagnitude;
                        if (dist < nearestDist)
                        {
                            hasStar        = true;
                            nearestDist    = dist;
                            nearestStarPos = s.Position;
                        }
                    }
                }
                if (hasStar == true)
                {
                    Move(nearestStarPos);
                }
                else
                {
                    if (Time.time > m_LastTime)
                    {
                        if (ApproachNextDestination())
                        {
                            m_LastTime = Time.time + Random.Range(3, 8);
                        }
                    }
                }
            }
            Tank oppTank = Match.instance.GetOppositeTank(Team);

            if (oppTank != null)
            {
                if (CanSeeOthers(oppTank))
                {
                    TurretTurnTo(oppTank.Position);
                    Vector3 toTarget = oppTank.Position - FirePos;
                    toTarget.y = 0;
                    toTarget.Normalize();
                    if (Vector3.Dot(TurretAiming, toTarget) > 0.98f)
                    {
                        Fire();
                    }
                }
                else
                {
                    TurretTurnTo(Position + Forward);
                }
            }
        }
コード例 #51
0
 private void StartAttack(Tank tank)
 {
     CameraController.Instance.SetTankView(tank, () => MessageBus.Instance.StartTankAttack(tank));
 }
コード例 #52
0
 private void Start()
 {
     _tank   = FindObjectOfType <Tank>();
     _towers = FindObjectsOfType <Tower>().ToList();
     ResumeGame();
 }
コード例 #53
0
 public TankController(Tank tank, IMissileController missileController)
 {
     _tank = tank;
     _missileController = missileController;
 }
コード例 #54
0
        public bool DoTankControls(float pSeconds)
        {
            bool tankMoved = false;

            if (Tank.Health() > 0)
            {
                if (Controller.IsPressedWithCharge(Control.LEFT_TRACK_FORWARDS))
                {
                    tankMoved = true;
                    if (Controller.IsPressedWithCharge(Control.RIGHT_TRACK_FORWARDS))
                    {
                        Tank.BothTracksForward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.LEFT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else if (Controller.IsPressedWithCharge(Control.RIGHT_TRACK_BACKWARDS))
                    {
                        Tank.LeftTrackForward();
                        Tank.RightTrackBackward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.LEFT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else
                    {
                        Tank.LeftTrackForward();
                        Controller.DepleteCharge(Control.LEFT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                }
                else if (Controller.IsPressedWithCharge(Control.LEFT_TRACK_BACKWARDS))
                {
                    tankMoved = true;
                    if (Controller.IsPressedWithCharge(Control.RIGHT_TRACK_BACKWARDS))
                    {
                        Tank.BothTracksBackward();
                        Controller.DepleteCharge(Control.LEFT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.RIGHT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else if (Controller.IsPressedWithCharge(Control.RIGHT_TRACK_FORWARDS))
                    {
                        Tank.LeftTrackBackward();
                        Tank.RightTrackForward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.LEFT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else
                    {
                        Tank.LeftTrackBackward();
                        Controller.DepleteCharge(Control.LEFT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                }
                else if (Controller.IsPressedWithCharge(Control.RIGHT_TRACK_FORWARDS))
                {
                    tankMoved = true;
                    if (Controller.IsPressedWithCharge(Control.LEFT_TRACK_FORWARDS))
                    {
                        Tank.BothTracksForward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.LEFT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else if (Controller.IsPressedWithCharge(Control.LEFT_TRACK_BACKWARDS))
                    {
                        Tank.LeftTrackBackward();
                        Tank.RightTrackForward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.LEFT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else
                    {
                        Tank.RightTrackForward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                }
                else if (Controller.IsPressedWithCharge(Control.RIGHT_TRACK_BACKWARDS))
                {
                    tankMoved = true;
                    if (Controller.IsPressedWithCharge(Control.LEFT_TRACK_BACKWARDS))
                    {
                        Tank.BothTracksBackward();
                        Controller.DepleteCharge(Control.LEFT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.RIGHT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else if (Controller.IsPressedWithCharge(Control.LEFT_TRACK_FORWARDS))
                    {
                        Tank.LeftTrackForward();
                        Tank.RightTrackBackward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                        Controller.DepleteCharge(Control.LEFT_TRACK_FORWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                    else
                    {
                        Tank.RightTrackBackward();
                        Controller.DepleteCharge(Control.RIGHT_TRACK_BACKWARDS, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                    }
                }

                if (Controller.IsPressedWithCharge(Control.TURRET_LEFT))
                {
                    Tank.CannonLeft();
                    Controller.DepleteCharge(Control.TURRET_LEFT, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                }
                else if (Controller.IsPressedWithCharge(Control.TURRET_RIGHT))
                {
                    Tank.CannonRight();
                    Controller.DepleteCharge(Control.TURRET_RIGHT, DGS.Instance.GetFloat("TRACK_DEPLETION_RATE") * pSeconds);
                }

                if (Controller.IsPressedWithCharge(Control.FIRE))
                {
                    Tank.PrimingWeapon(pSeconds);
                }
                else
                {
                    if (Tank.FireIfPrimed())
                    {
                        SoundEffectInstance bulletShot = Tankontroller.Instance().GetSoundManager().GetSoundEffectInstance("Sounds/Tank_Gun");
                        bulletShot.Play();
                        Controller.DepleteCharge(Control.FIRE, DGS.Instance.GetFloat("BULLET_CHARGE_DEPLETION")); // BULLET CHARGE HERE
                        Tank.SetFired(DGS.Instance.GetInt("BLAST_DELAY"));
                    }
                }

                if (Controller.IsPressed(Control.RECHARGE))
                {
                    if (!Tank.ChargeDown)
                    {
                        Tank.ChargePressed();
                        Controller.AddCharge(Control.RECHARGE, DGS.Instance.GetFloat("CHARGE_AMOUNT"));
                    }
                }
                else
                {
                    Tank.ChargeReleased();
                }
            }
            if (Tank.Fired() > 0)
            {
                Tank.DecFired();
            }
            return(tankMoved);
        }
コード例 #55
0
 protected override void OnTriggerEffect(Tank trigger)
 {
     GameManager.Instance.Upgrade(trigger, 1);
 }
コード例 #56
0
        public Visible GetFirstVisibleTechIsEnemy(int team)
        {
            bool flag = true;

            if (Singleton.Manager <ManNetwork> .inst.IsMultiplayer())
            {
                if (base.Tech.netTech == null)
                {
                    flag = false;
                }
                else if (base.Tech.netTech.NetPlayer == null)
                {
                    flag = ManNetwork.IsHost;
                }
                else
                {
                    flag = (base.Tech.netTech.NetPlayer == Singleton.Manager <ManNetwork> .inst.MyPlayer);
                }
            }
            if (flag && Time.time > this.m_UpdateClosestEnemyTimeout)
            {
                this.m_UpdateClosestEnemyTimeout = Time.time + this.m_RefreshInterval;
                if (this.m_SearchSphereNeedsRecalc)
                {
                    this.m_SearchSphereNeedsRecalc = false;
                    this.RecalculateSearchSphere();
                }
                Vector3 searchPosition = base.Tech.trans.TransformPoint(this.m_SearchEpicentre);
                Visible visible        = null;
                float   bestDist       = 0f;
                this.ClearVisibles();
                foreach (Visible visible2 in Singleton.Manager <ManWorld> .inst.TileManager.IterateVisibles(ObjectTypes.Vehicle, searchPosition, this.m_SearchRadius))
                {
                    Tank tank = visible2.tank;
                    if (Singleton.Manager <ManNetwork> .inst.IsMultiplayer() && Singleton.Manager <ManNetwork> .inst.NetController != null)
                    {
                        NetTech notableTech = Singleton.Manager <ManNetwork> .inst.NetController.GetNotableTech();

                        if (notableTech != null && notableTech.tech == tank && tank.IsEnemy(team) && notableTech.InitialSpawnShieldID == 0U)
                        {
                            visible = notableTech.tech.visible;
                            break;
                        }
                    }
                    if (tank != null && tank.IsEnemy(team) && tank.ShouldShowOverlay)
                    {
                        float sqrMagnitude = (searchPosition - tank.trans.position).sqrMagnitude;
                        float num2;
                        if (sqrMagnitude < this.m_SearchRadius * this.m_SearchRadius && this.AnyModuleCanSee(tank.visible, out num2))
                        {
                            Vector3 localPosition = base.Tech.trans.InverseTransformPoint(tank.trans.position);
                            int     octant        = localPosition.x > 0 ? 4 : 0 + localPosition.y > 0 ? 2 : 0 + localPosition.z > 0 ? 1 : 0;

                            this.m_Visibles[octant].Add(new Visible.ConeFiltered
                            {
                                visible = tank.visible,
                                distSq  = sqrMagnitude
                            });
                            if (visible == null || sqrMagnitude < bestDist)
                            {
                                visible  = tank.visible;
                                bestDist = sqrMagnitude;
                            }
                        }
                    }
                }
                this.m_ClosestEnemy.Set(visible);
                for (int i = 0; i < 8; i++)
                {
                    this.m_Visibles[i].Sort((Visible.ConeFiltered a, Visible.ConeFiltered b) => (int)(a.distSq * 1000f - b.distSq * 1000f));
                    Visible octantBest = null;
                    if (this.m_Visibles[i].Count > 0)
                    {
                        octantBest = this.m_Visibles[i][0].visible;
                    }
                    this.m_ClosestOctantEnemy[i].Set(octantBest);
                }
            }
            return(this.m_ClosestEnemy.Get());
        }
コード例 #57
0
ファイル: Program.cs プロジェクト: neazimi777/game_git
        static void Main(string[] args)
        {
            Random ran    = new Random();
            Dog    dog1   = new Dog();
            Horse  horse1 = new Horse();
            Human  human1 = new Human();
            Human  human2 = new Human();
            Human  human3 = new Human();
            Alien  alien1 = new Alien();
            Alien  alien2 = new Alien();


            List <Character> charaterList = new List <Character>();

            charaterList.Add(dog1);
            charaterList.Add(horse1);
            charaterList.Add(human1);
            charaterList.Add(human2);
            charaterList.Add(human3);
            charaterList.Add(alien1);
            charaterList.Add(alien2);

            for (int i = 0; i <= 5; i++)
            {
                Console.Write("enter  " + charaterList[i] + "  name:");
                charaterList[i].Name = Console.ReadLine();
                Console.WriteLine(" name of " + charaterList[i] + " is : " + charaterList[i].Name + "\n");
            }

            for (int i = 0; i <= 1; i++)
            {
                Console.Write("enter " + charaterList[i] + " age:");
                charaterList[i].Age = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("age of " + charaterList[i] + " is : " + charaterList[i].Age + "\n");
            }

            for (int i = 2; i < 7; i++)
            {
                Console.Write("  character  " + charaterList[i] + " energy :");
                charaterList[i].Energy = ran.Next(100);
                Console.WriteLine(" energy of" + charaterList[i] + "is : " + charaterList[i].Energy + "\n");
            }

            for (int i = 2; i <= 4; i++)
            {
                Console.WriteLine("Select one of the options:fruit-meat-vegtable ");
                charaterList[i].Food = Console.ReadLine();
                Console.WriteLine(" food of " + charaterList[i] + " is : " + charaterList[i].Food + "\n");
            }

            for (int i = 0; i <= 1; i++)
            {
                Console.Write("enter  " + charaterList[i] + " color:");
                charaterList[i].Color = Console.ReadLine();
                Console.WriteLine(" color of " + charaterList[i] + " is : " + charaterList[i].Color + "\n");
            }

            for (int i = 0; i <= 1; i++)
            {
                Console.Write("enter  " + charaterList[i] + " breed:");
                charaterList[i].Breed = Console.ReadLine();
                Console.WriteLine(" breed of " + charaterList[i] + " is : " + charaterList[i].Breed + "\n");
            }

            for (int i = 0; i <= 1; i++)
            {
                Console.Write("enter " + charaterList[i] + " gender:");
                charaterList[i].Gender = Console.ReadLine();
                Console.WriteLine(" gender of " + charaterList[i] + " is : " + charaterList[i].Gender + "\n");
            }

            for (int i = 0; i <= 1; i++)
            {
                charaterList[i].animalSound();
            }


            Tank myTank = new Tank();

            myTank.passenger(human1, myTank);
            Console.WriteLine("enter tank color :");
            myTank.Color    = Console.ReadLine( );
            myTank.MaxSpeed = ran.Next(50, 100);
            myTank.Power    = ran.Next(100);
            myTank.Weight   = ran.Next(2000);
            myTank.Damage   = ran.Next(100);
            Console.Write("Choose one of the options: autumn ,firefighter :  ");
            myTank.Pattern = Console.ReadLine();
            Console.WriteLine("pattern " + myTank.Pattern);
            Console.Write("Choose one of the options: Gatling M134 , mpulomet-41:");
            myTank.TypeOfGun = Console.ReadLine();

            Console.WriteLine("color of tank : " + myTank.Color);
            Console.WriteLine("type of gun " + myTank.TypeOfGun);
            Console.WriteLine("maxspeed of tank: " + myTank.MaxSpeed);
            Console.WriteLine("power of tank: " + myTank.Power);
            Console.WriteLine("weight of tank: " + myTank.Weight);
            Console.WriteLine("damade of tank: " + myTank.Damage);
            Console.WriteLine("pattern of tank: " + myTank.Pattern);

            Console.WriteLine("************************************************************************");



            Dog myDog = new Dog();

            Console.Write("enter  dog name:");
            myDog.Name = Console.ReadLine();
            Console.Write("enter  dog color:");
            myDog.Color = Console.ReadLine();
            Console.Write("enter dog breed :");
            myDog.Breed = Console.ReadLine();
            Console.Write("enter dog gender:");
            myDog.Gender = Console.ReadLine();
            Console.Write("enter dog age:");
            myDog.Age = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("name " + myDog.Name);
            Console.WriteLine("color " + myDog.Color);
            Console.WriteLine(" breed " + myDog.Breed);
            Console.WriteLine("gender " + myDog.Gender);
            Console.WriteLine("age " + myDog.Age);
            Console.WriteLine("************************************************************************");

            Horse myHorse = new Horse();

            Console.Write("enter horse name:");
            myHorse.Name = Console.ReadLine();
            Console.Write("enter horse color:");
            myHorse.Color = Console.ReadLine();
            Console.Write("enter horse breed :");
            myHorse.Breed = Console.ReadLine();
            Console.Write("enter horse gender:");
            myHorse.Gender = Console.ReadLine();
            Console.Write("enter horse age:");
            myHorse.Age = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("name " + myHorse.Name);
            Console.WriteLine("color " + myHorse.Color);
            Console.WriteLine(" breed " + myHorse.Breed);
            Console.WriteLine("gender " + myHorse.Gender);
            Console.WriteLine("age " + myHorse.Age);

            Console.WriteLine("************************************************************************");


            Car mycar = new Car();

            myTank.passenger(human1, mycar);
            mycar.MaxSpeed = ran.Next(400);
            Console.WriteLine("enter color:");
            mycar.Color        = Console.ReadLine( );
            mycar.Power        = ran.Next(100);
            mycar.Weight       = ran.Next(2000);
            mycar.Acceleration = ran.Next(4);
            mycar.Handling     = ran.Next(100);

            Console.WriteLine("max speed of car " + mycar.MaxSpeed);
            Console.WriteLine("color of car " + mycar.Color);
            Console.WriteLine("power of car " + mycar.Power);
            Console.WriteLine("weight of car " + mycar.Weight);
            Console.WriteLine("acceleration  of car" + mycar.Acceleration);
            Console.WriteLine("handelin of car" + mycar.Handling);

            Console.WriteLine("************************************************************************");

            Human myCharacter = new Human();

            Console.WriteLine("Enter character name:");
            myCharacter.Name = Console.ReadLine();
            Console.Write("enter character age :");
            myCharacter.Age = Convert.ToInt32(Console.ReadLine());
            Console.Write("energy of character  :");
            myCharacter.Energy = ran.Next(100);
            Console.WriteLine("Select one of the options:fruit-meat-vegtable ");
            myCharacter.Food = Console.ReadLine();

            Console.WriteLine("character name  " + myCharacter.Name);
            Console.WriteLine("character age  " + myCharacter.Age);
            Console.WriteLine("charater energy  " + myCharacter.Energy);
            Console.WriteLine("charater food " + myCharacter.Food);

            Console.WriteLine("************************************************************************");

            Alien myCharacter1 = new Alien();

            Console.Write("energy of alien  :");
            myCharacter1.Energy = ran.Next(100);
            Console.Write("energy of alien : " + myCharacter1.Energy);

            Console.WriteLine("************************************************************************");

            Gun colt = new Gun();

            colt.Name       = "colt";
            colt.Accuracy   = ran.Next(100);
            colt.Damage     = ran.Next(100);
            colt.RateOfFire = ran.Next(100);
            colt.Handling   = ran.Next(100);
            colt.Range      = ran.Next(100);

            Console.WriteLine("name of gun  " + colt.Name);
            Console.WriteLine("accuracy of gun " + colt.Accuracy);
            Console.WriteLine("damage of gun  " + colt.Damage);
            Console.WriteLine("Rate of fire  of gun " + colt.RateOfFire);
            Console.WriteLine("handling  of gun " + colt.Handling);
            Console.WriteLine("range of gun " + colt.Range);
            Console.WriteLine("************************************************************************");

            Gun ak47 = new Gun();

            ak47.Name = "ak47";

            ak47.Accuracy   = ran.Next(100);
            ak47.Damage     = ran.Next(100);
            ak47.RateOfFire = ran.Next(100);
            ak47.Handling   = ran.Next(100);
            ak47.Range      = ran.Next(100);

            Console.WriteLine("range of gun  " + ak47.Range);
            Console.WriteLine("name of gun " + ak47.Name);
            Console.WriteLine("accuracy of gun " + ak47.Accuracy);
            Console.WriteLine("damage of gun " + ak47.Damage);
            Console.WriteLine("Rate of fire of gun  " + ak47.RateOfFire);
            Console.WriteLine("handling of gun" + ak47.Handling);
            Console.WriteLine("************************************************************************");

            Health he = new Health();

            he.Heartbeat      = ran.Next(70, 150);
            he.Temperature    = ran.Next(30, 40);
            he.MovingDistance = ran.Next(100000);
            he.StepCounter    = ran.Next(10000);
            Console.WriteLine("heartbeat " + he.Heartbeat);
            Console.WriteLine("temperature " + he.Temperature);
            Console.WriteLine("moving distance " + he.MovingDistance);
            Console.WriteLine("step couner " + he.StepCounter);

            Console.WriteLine("************************************************************************");

            Spaceship mySpaceship = new Spaceship();

            mySpaceship.CargoHoldCapacity = ran.Next(2000);


            mySpaceship.MaxSpeed = ran.Next(1000);


            Console.Write("Choose one of the options: Gatling M134 , mpulomet-41:");
            mySpaceship.TypeOfGun = Console.ReadLine();
            myTank.Power          = ran.Next(100);
            myTank.Weight         = ran.Next(5000);
            myTank.Damage         = ran.Next(100);
            myTank.RateOfFire     = ran.Next(1000);

            Console.WriteLine("argoHoldCapacity  " + mySpaceship.CargoHoldCapacity);
            Console.WriteLine("speed " + mySpaceship.MaxSpeed);
            Console.WriteLine("type of gun " + mySpaceship.TypeOfGun);
            Console.Write("power of space ship: " + mySpaceship.Power);
            Console.Write("weight of space ship : " + mySpaceship.Weight);
            Console.Write("damade of space ship : " + mySpaceship.Damage);
            Console.Write("RateOfFire of space ship : " + mySpaceship.RateOfFire);
            Console.WriteLine("************************************************************************");

            Shield myShield = new Shield();

            Console.WriteLine("enter durability:");
            myShield.Durability = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Choose one of the options: small ,medium, large:");
            myShield.Size = Console.ReadLine();
            Console.WriteLine("Choose one of the options: wood ,iron, steel ,");
            myShield.BodyMaterial = Console.ReadLine();
            Console.WriteLine(myShield.BodyMaterial);
            Console.WriteLine("enter handling:");
            myShield.Handling = Convert.ToInt32(Console.Read());

            Console.WriteLine("Durability of shield : " + myShield.Durability);
            Console.WriteLine("size of shield : " + myShield.Size);
            Console.WriteLine("body material : " + myShield.BodyMaterial);
            Console.WriteLine("handling  : " + myShield.Handling);
        }
コード例 #58
0
        static void Main()
        {
            Console.Write(" Enter the number of teams".PadRight(40, ' ') + ": ");
            int countTeam = int.Parse(Console.ReadLine() ?? string.Empty);

            //-----------------------------------------------------------------
            Console.Write(" Enter the number of tanks in the team".PadRight(40, ' ') + ": ");
            int countTank = int.Parse(Console.ReadLine() ?? string.Empty);

            //-----------------------------------------------------------------
            int[] count = new int[countTeam];
            for (var i = 0; i < count.Length; i++)
            {
                count[i] = countTank;
            }
            //-----------------------------------------------------------------
            Console.Write((" Enter " + countTeam + " models").PadRight(40, ' ') + ": ");
            string[] arrModel = Console.ReadLine().Split(new[] { ' ', ',', ';', '.' }, StringSplitOptions.RemoveEmptyEntries);
            Console.CursorVisible = false;
            //-----------------------------------------------------------------
            Tank[][] array = new Tank[countTeam][];
            for (var i = 0; i < array.Length; i++)
            {
                array[i] = new Tank[countTank];
                for (int j = 0; j < countTank; j++)
                {
                    array[i][j] = new Tank(arrModel[i]);
                }
            }
            //-----------------------------------------------------------------

            int countMin = countTank;

            while (countTeam > 1)
            {
                Console.Write("\n\n" + (" Battle ".PadLeft(23, '-')).PadRight(39, '-'));
                for (int i = 0; i < countMin; i++)
                {
                    Tank[] winners = new Tank[countTeam];
                    int    cw      = 0; // Количество победителей
                    winners[cw] = array[0][i];

                    // Боевое столкновение, сохранение списка победителей
                    for (int j = 1; j < countTeam; j++)
                    {
                        for (int k = 0; k <= cw; k++)
                        {
                            Console.Write((i == 0 && j == 1 ? "\n" : "\n\n" + "".PadLeft(39, '-') + '\n'));
                            int result = winners[k] * array[j][i]; // Бой

                            Console.Write(winners[k] + "\n" + array[j][i]);
                            CursorBack();

                            if (result != 0)
                            {
                                if (result > 0) // Победил первый
                                {
                                    PrintBattleResult(winners[k], ConsoleColor.Red, array[j][i], ConsoleColor.Green);
                                    if (cw > 0)
                                    {
                                        winners = new Tank[countTeam];
                                        cw      = 0;
                                    }
                                    winners[cw] = array[j][i];
                                    break;
                                }
                                else // Победил второй
                                {
                                    PrintBattleResult(winners[k], ConsoleColor.Green, array[j][i], ConsoleColor.Red);
                                    break;
                                }
                            }
                            else // Ничья
                            {
                                PrintBattleResult(winners[k], ConsoleColor.Yellow, array[j][i], ConsoleColor.Yellow);
                                winners[++cw] = array[j][i];
                                break;
                            }
                        }
                    }

                    // Обнуление уничтоженной техники
                    for (int j = 0; j < countTeam; j++)
                    {
                        bool check = false;
                        foreach (var winner in winners)
                        {
                            if (winner == null)
                            {
                                break;
                            }
                            if (array[j][i].Equals(winner))
                            {
                                check = true;
                                break;
                            }
                        }
                        if (!check)
                        {
                            array[j][i] = null;
                        }
                    }
                }

                // Удаляем уничтоженные танки
                int      countTeamTmp = countTeam;
                Tank[][] arrTmp       = new Tank[countTeam][];
                for (int i = 0; i < countTeamTmp; i++)
                {
                    int countNull = 0;
                    for (int j = 0; j < array[i].Length; j++)
                    {
                        if (array[i][j] == null)
                        {
                            countNull++;
                        }
                    }

                    if (countNull != array[i].Length)
                    {
                        arrTmp[i] = new Tank[array[i].Length - countNull];
                        for (int j = 0, k = 0; j < array[i].Length; j++)
                        {
                            if (array[i][j] != null)
                            {
                                arrTmp[i][k++] = array[i][j];
                            }
                        }
                    }
                    else
                    {
                        countTeam--;
                    }
                }
                array = arrTmp;

                // Удаляем пустые команды
                arrTmp = new Tank[countTeam][];
                if (countTeamTmp != countTeam)
                {
                    for (int i = 0, k = 0; i < countTeamTmp; i++)
                    {
                        if (array[i] != null)
                        {
                            arrTmp[k] = new Tank[array[i].Length];
                            for (int j = 0; j < array[i].Length; j++)
                            {
                                arrTmp[k][j] = array[i][j];
                            }
                            k++;
                        }
                    }
                    array = arrTmp;
                }

                // Подсчет минимального кол-ва танков в команде
                countMin = countTank;
                for (int i = 0; i < countTeam; i++)
                {
                    if (array[i].Length < countMin)
                    {
                        countMin = array[i].Length;
                    }
                }

                // Вывод списка выживших
                Console.Write("\n\n\n" + (" Alive ".PadLeft(23, '-')).PadRight(39, '-') + '\n');
                for (int i = 0; i < countTeam; i++)
                {
                    for (int j = 0; j < array[i].Length; j++)
                    {
                        Console.WriteLine(array[i][j]);
                    }
                    if (i != countTeam - 1)
                    {
                        Console.Write("\n" + "".PadLeft(39, '-') + '\n');
                    }
                }

                // Перемешать технику внутри команд
                for (var i = 0; i < array.Length; i++)
                {
                    Mix(ref array[i]);
                }

                Console.Write("\n\n 'Enter' to next battle..\n");
                while (Console.ReadKey(true).Key != ConsoleKey.Enter)
                {
                    ;
                }
            }
            //-----------------------------------------------------------------
            Console.Read();
        }
コード例 #59
0
        protected override bool OnEvaluate(IAgent agent, BlackboardMemory workingMemory)
        {
            Tank t = (Tank)agent;

            return(t.CanFire());
        }
コード例 #60
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            _tank = new Tank(50.0, 50.0, 0.0);

            base.Initialize();
        }