Exemplo n.º 1
0
        public override string Run(Tank t)
        {
            angleWithBase += angularVelocity;

            string result = "id: " + id;
            result += ", angleWithBase: " + angleWithBase;

            PointF pos = t.pos;
            double ang1 = t.orientation + angleWithBase - viewAngle / 2;
            double ang2 = t.orientation + angleWithBase + viewAngle / 2;

            Tank closestTank = null;
            double minDist = maxViewDistance;
            foreach (var tnk in tanks)
            {
                double ang = Math.Atan2(tnk.pos.Y - pos.Y, tnk.pos.X - pos.X);
                if (ang1 < ang && ang2 > ang)
                {
                    double dist = Math.Sqrt((tnk.pos.X - pos.X) * (tnk.pos.X - pos.X) + (tnk.pos.Y - pos.Y) * (tnk.pos.Y - pos.Y));
                    if (dist <= minDist)
                    {
                        closestTank = tnk;
                        minDist = dist;
                    }
                }
            }

            if(closestTank != null)
                result += ", closestTank: " + closestTank.id + ", distance: " + minDist;
            else
                result += ", closestTank: null, distance: -1";

            return result;
        }
Exemplo n.º 2
0
 public void LoadLevel(string path)
 {
     using(StreamReader sr = new StreamReader(path))
     {
         m_n = Convert.ToInt32(sr.ReadLine());
         m_m = Convert.ToInt32(sr.ReadLine());
         while (!sr.EndOfStream)
         {
             string type = sr.ReadLine();
             ISerializable unit;
             switch (type)
             {
                 case "floor":
                     unit = new Floor();
                     break;
                 case "wall":
                     unit = new Wall();
                     break;
                 case "tank":
                     unit = new Tank();
                     break;
                 default:
                     unit = new Floor();
                     break;
             }
             unit.Load(sr);
             IPositionable positionOfUnit = unit as IPositionable;
             m_field[positionOfUnit.Position.X, positionOfUnit.Position.Y] = positionOfUnit;
         }
     }
 }
Exemplo n.º 3
0
        public override string Run(Tank t)
        {
            angleWithBase += angularVelocity;

            string result = "id: " + id;
            result += ", angleWithBase: " + angleWithBase;

            PointF pos = t.pos;
            double ang1 = t.orientation + angleWithBase - viewAngle / 2;
            double ang2 = t.orientation + angleWithBase + viewAngle / 2;

            List<KeyValuePair<Tank, double>> tanksInRegion = new List<KeyValuePair<Tank, double>>();
            foreach (var tnk in tanks)
            {
                double ang = Math.Atan2(tnk.pos.Y - pos.Y, tnk.pos.X - pos.X);
                if (ang1 < ang && ang2 > ang)
                {
                    double dist = Math.Sqrt((tnk.pos.X - pos.X) * (tnk.pos.X - pos.X) + (tnk.pos.Y - pos.Y) * (tnk.pos.Y - pos.Y));
                    if (dist > maxViewDistance) continue;
                    tanksInRegion.Add(new KeyValuePair<Tank, double>(tnk, dist));
                }
            }

            result += ", count: " + tanksInRegion.Count;
            tanksInRegion.ForEach(pair => result += ", id: " + pair.Key.id + ", distance: " + pair.Value);

            return result;
        }
Exemplo n.º 4
0
 private ITank CreateOneTank(int id, Label label)
 {
     var tank = new Tank(id, label);
     tank.Direction = MathUtils.GenerateVector();
     tank.Velocity = velocity;
     return tank;
 }
Exemplo n.º 5
0
 public override void Draw(Graphics g, Tank t)
 {
     double ang1 = t.orientation + angleWithBase - viewAngle / 2;
     double ang2 = t.orientation + angleWithBase + viewAngle / 2;
     g.FillPie(new SolidBrush(Color.FromArgb(drawAlpha, color))
         , (int)t.pos.X - maxViewDistance, (int)t.pos.Y - maxViewDistance
         , 2 * maxViewDistance, 2 * maxViewDistance, (int)ang1, (int)ang2);
 }
Exemplo n.º 6
0
 // <Constructors>
 public Missile(Tank tank)
 {
     this.currentTank = tank;
     this.missleDirection = tank.Direction;
     this.missileLeft = currentTank.leftPos;
     this.missileTop = currentTank.topPos;
     //Launch();
 }
Exemplo n.º 7
0
 // Since its only a regular weapon it ignores target ID
 public override void Fire(Tank t, int targetID)
 {
     if ((DateTime.Now - lastFireTime).Milliseconds > reloadTime)
     {
         bullets.Add(new RegularBullet(speed + t.currentSpeed, t.orientation, t.pos, color));
         lastFireTime = DateTime.Now;
     }
 }
Exemplo n.º 8
0
 // Constructor
 public EnemyMissile(Tank.direction direction, int missileLeft, int missileTop)
 {
     //this.currentTank = tank;
     this.missleDirection = direction;
     this.missileLeft = missileLeft;
     this.missileTop = missileTop;
     //Launch();
 }
Exemplo n.º 9
0
        public virtual void Draw(Graphics g, Tank t)
        {
            // TODO: Fill here

            Rectangle rect = new Rectangle((int)pos.X - width / 2, (int)pos.Y - height / 2, width, height);

            Matrix m = new Matrix();
            m.RotateAt((float)orientation, pos);

            g.FillRectangle(new SolidBrush(color), rect);
            g.ResetTransform();
        }
Exemplo n.º 10
0
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            tank = new Tank(new Vector2(100,100), Color.White, 
                Content.Load<Texture2D>("Tankk"), 
                Content.Load<Texture2D>("TankCcc"),
                Keys.W, Keys.S , Keys.D , Keys.A );

            crosshair = Content.Load<Texture2D>("ch1");
            background = Content.Load<Texture2D>("Background");
            bullet = Content.Load<Texture2D>("Bullet");
        }
Exemplo n.º 11
0
        // Since its a smart weapon it won't ignore target ID
        public override void Fire(Tank t, int targetID)
        {
            if ((DateTime.Now - lastFireTime).Milliseconds > reloadTime)
            {
                Tank tnk = tanks.First(_t => _t.id == targetID);

                PointF pos = t.pos;
                double ang1 = t.orientation - viewAngle / 2;
                double ang2 = t.orientation + viewAngle / 2;
                double ang = Math.Atan2(tnk.pos.Y - pos.Y, tnk.pos.X - pos.X);
                double dist = Math.Sqrt((tnk.pos.X - pos.X) * (tnk.pos.X - pos.X) + (tnk.pos.Y - pos.Y) * (tnk.pos.Y - pos.Y));
                if (ang1 < ang && ang2 > ang && dist <= maxDistance)
                {
                    bullets.Add(new HomingBullet(speed, t.orientation, t.pos, t, color));
                    lastFireTime = DateTime.Now;
                }
            }
        }
Exemplo n.º 12
0
        private void button2_Click(object sender, EventArgs e)
        {
            m_level.LoadLevel(tbxLevelPath.Text);

            for (int i = 0; i < count; i++)
            {
                Tank tank = new Tank();
                tank.SetColor(cbxList[i].SelectedItem.ToString());
                //using (StreamReader sr = new StreamReader(tbxList[i].Text))
                //{
                //    while (!sr.EndOfStream)
                //    {
                //        tank.AddCommand(tank.GetCommand(sr.ReadLine()));
                //    }
                //}
                //m_level.AddTank(tank);
            }
            
        }
Exemplo n.º 13
0
        } // Удаление пули

        private void MaxTouch(Tank tnk)
        {
        }
Exemplo n.º 14
0
        } // Отрисовка карты

        private void InitializanionTank()
        {
            tank = new PlayerTank("1", 0, 0, "танк");
            windowTank.Add(tank);
            windowTank.Add(new BotTank("2", (int)Coordinat_Bot_Tank.X, (int)Coordinat_Bot_Tank.Y, "EvilTank"));
        } // Добавление танков на карту
Exemplo n.º 15
0
        public override void Draw(Graphics g, Tank t)
        {
            int r = (int)((double)drawRMax * drawTime / drawTimeMax);

            g.FillEllipse(new SolidBrush(Color.FromArgb(drawAlpha, color)), t.pos.X - r, t.pos.Y - r, 2 * r, 2 * r);
        }
Exemplo n.º 16
0
 public void LoadMap(string pathFileMap)
 {
     var lines = File.ReadAllLines(pathFileMap);
     try
     {
         var countColums = int.Parse(lines[0].Split(' ')[0]);
         var countRows = int.Parse(lines[0].Split(' ')[1]);
         this.SizeMap = new Size(countRows, countColums);
         this.Map = new CellMap[countRows, countColums];
         for (var i = 0; i < countRows; i++)
         {
             var arr = lines[i + 1];
             for (var k = 0; k < countColums; k++)
             {
                 switch (arr[k])
                 {
                     case 'S':
                         this.Map[i, k] = CellMap.Brick;
                         break;
                     case 'X':
                         this.Map[i, k] = CellMap.Ground;
                         this.UserTank = new Tank(this.CanvasGame, new Point(k, i));
                         break;
                     case 'Y':
                         this.Map[i, k] = CellMap.ComputerTank;
                         break;
                     case ' ':
                         this.Map[i, k] = CellMap.Ground;
                         break;
                     case 'W':
                         this.Map[i, k] = CellMap.Water;
                         break;
                 }
             }
         }
     }
     catch (Exception)
     {
         this.IsLoadMap = false;
     }
     this.IsLoadMap = true;
 }
Exemplo n.º 17
0
        // test enemyTank
        //static EnemyTank enemyTank1 = new EnemyTank(1, Battlefield.FieldWidth - 5);
        static void Main()
        {
            // set the encoding to print the extendet ASCII table
            //Console.OutputEncoding = System.Text.Encoding.GetEncoding(1252);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("T A N K S\n");
            Console.WriteLine("Created By: HomerSimpson Team\n");
            Console.Write("Enter Player's Name: ");
            playerName = Console.ReadLine();
            Console.Clear();

            // Generate player tank
            playerTank = new Tank(36, 20, "green");
            // Create a number of enemies based on the difficult
            enemyTanks = EnemyTank.GenerateEnemyTanks(difficult);

            // Create a battlefield playing grid
            Battlefield.SetBattlefield();

            Thread enemyTanksTh = new Thread(new ThreadStart(RunEnemyTank));
            Thread playerTankTh = new Thread(new ThreadStart(Run));
            enemyTanksTh.Start();
            playerTankTh.Start();
            enemyTanksTh.Join();
            playerTankTh.Join();

            //Battlefield.Add(40, 30, 'a');
        }
Exemplo n.º 18
0
 public override void Draw(Graphics g, Tank t)
 {
     bullets.ForEach(b => b.Draw(g, t));
 }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            //Изображение игрока и компьютера
            string[] leftTankSpr = { "        \n",
                                     "------  \n",
                                     "|   ----\n",
                                     "|   ----\n",
                                     "------  \n",
                                     "        \n" };

            string[] rightTankSpr = { "        \n",
                                      "  ------\n",
                                      "----   |\n",
                                      "----   |\n",
                                      "  ------\n",
                                      "        \n" };
            //Устанавливает размеры поля
            int width  = 50;
            int height = 20;

            GameField.SetField(width, height);

            //Создаем класс отрисовки
            Display disp = new Display();
            //Класс управление игрока
            PlayerController playerContoller = new PlayerController();
            //Класс танка игрока
            Tank playerTank = new Tank(0, 0, leftTankSpr);

            //Подписка танка на события контроллера
            playerContoller.move  += playerTank.OnMove;
            playerContoller.shoot += playerTank.OnShoot;
            playerContoller.exit  += playerTank.OnExit;
            //Подписка отрисовщика на события танка
            playerTank.move  += disp.OnMoveUpdate;
            playerTank.shoot += disp.OnShootUpdate;
            playerTank.exit  += disp.Exit;

            //Тоже самое что у игрока
            AIController aiController = new AIController();
            Tank         aiTank       = new Tank(GameField.MaxWidth, 0, rightTankSpr);

            aiController.move  += aiTank.OnMove;
            aiController.shoot += aiTank.OnShoot;
            aiController.exit  += aiTank.OnExit;
            aiTank.move        += disp.OnMoveUpdate;
            aiTank.shoot       += disp.OnShootUpdate;
            aiTank.exit        += disp.Exit;

            //Запуск асинхронных действий компьютера и игрока
            aiController.AsyncAction();
            playerContoller.AsyncAction();

            //Бесконечный цикл пока игра не закончена
            while (!GameField.IsEndGame)
            {
            }

            //Считать нажатие так как поток игрока в режиме ожидания нажатия клавишы
            Console.ReadKey();
        }
Exemplo n.º 20
0
 public override string Run(Tank t)
 {
     string result = "id: " + id + ", x: " + t.pos.X + ", y: " + t.pos.Y;
     return result;
 }
Exemplo n.º 21
0
 public TankWithOptics(Tank tank, double opticsIncreaser) : base(tank)
 {
     _opticsIncreaser = opticsIncreaser;
 }
Exemplo n.º 22
0
 abstract public void Fire(Tank t, int targetID);
Exemplo n.º 23
0
 public abstract void Fire(Tank t, int targetID);
Exemplo n.º 24
0
        }// Проверка на столкновение пули с объектом карты

        private void PositionСhange(Tank tank)
        {
            Dispatcher.Invoke(() => Canvas.SetTop(tank.GetImage(), tank.GetCoordinates.CordinateToY));
            Dispatcher.Invoke(() => Canvas.SetLeft(tank.GetImage(), tank.GetCoordinates.CordinateToX));
        } // Перемещение танка
Exemplo n.º 25
0
        private async void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                TcpClient client = new TcpClient();
                client.Connect(new IPEndPoint(IPAddress.Loopback, 8888));
                stream      = client.GetStream();
                FormClosed += (s1, e1) => { closed = true; client.Close(); };

                while (true)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] data = new byte[4096];
                        do
                        {
                            int bytes = await stream.ReadAsync(data, 0, data.Length);

                            ms.Write(data, 0, bytes);
                        } while (stream.DataAvailable);

                        foreach (XElement element in XElement.Parse($"<r>{Encoding.Unicode.GetString(ms.ToArray())}</r>").Elements())
                        {
                            switch (element.Name.ToString())
                            {
                            case "Id":
                                id = element.Value;
                                tanks.Add(new Tank(id, this, tanks, stream));
                                break;

                            case "Players":
                                foreach (XElement playerId in element.Elements())
                                {
                                    tanks.Add(new Tank(playerId.Value, this, tanks));
                                }
                                break;

                            case "Player":
                                switch (element.Attribute("Action").Value)
                                {
                                case "Join":
                                    tanks.Add(new Tank(element.Attribute("Id").Value, this, tanks));
                                    break;

                                case "Leave":
                                    tanks.First(x => x.Id == element.Attribute("Id").Value).Dispose();
                                    break;

                                case "Move":
                                    Tank tank = tanks.First(x => x.Id == element.Attribute("Id").Value);
                                    tank.Picture.Location = new Point(
                                        int.Parse(element.Attribute("X").Value),
                                        int.Parse(element.Attribute("Y").Value));
                                    tank.Direction = int.Parse(element.Attribute("Direction").Value);
                                    break;

                                case "Shoot":
                                    tanks.First(x => x.Id == element.Attribute("Id").Value).Shoot();
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch when(closed)
            {
            }
        }
Exemplo n.º 26
0
 abstract public string Run(Tank t);
Exemplo n.º 27
0
 public TankWithRecharger(Tank tank, double rechargerDecreaser) : base(tank)
 {
     _rechargerDecreaser = rechargerDecreaser;
 }
Exemplo n.º 28
0
 abstract public void Draw(Graphics g, Tank t);
Exemplo n.º 29
0
 public abstract void Draw(Graphics g, Tank t);
Exemplo n.º 30
0
 private bool CanMove(Tank tank)
 {
     var p = tank.Position;
     switch (tank.Direction)
     {
         case Direction.Up:
             return Map[(int)p.Y - 1, (int)p.X] == CellMap.Ground;
         case Direction.Left:
             return Map[(int)p.Y, (int)p.X - 1] == CellMap.Ground;
         case Direction.Right:
             return Map[(int)p.Y, (int)p.X + 1] == CellMap.Ground;
         case Direction.Down:
             return Map[(int)p.Y + 1, (int)p.X] == CellMap.Ground;
         default:
             return false;
     }
 }
Exemplo n.º 31
0
 public override void Draw(Graphics g, Tank t)
 {
     bullets.ForEach(b => b.Draw(g, t));
 }
Exemplo n.º 32
0
 public abstract string Run(Tank t);
Exemplo n.º 33
0
 public HomingBullet(double speed, double orientation, PointF pos, Tank t, Color color)
     : base(speed, orientation, pos, color)
 {
     this.t = t;
 }
Exemplo n.º 34
0
 public HomingBullet(double speed, double orientation, PointF pos, Tank t, Color color)
     : base(speed, orientation, pos, color)
 {
     this.t = t;
 }