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; }
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; } } }
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; }
private ITank CreateOneTank(int id, Label label) { var tank = new Tank(id, label); tank.Direction = MathUtils.GenerateVector(); tank.Velocity = velocity; return tank; }
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); }
// <Constructors> public Missile(Tank tank) { this.currentTank = tank; this.missleDirection = tank.Direction; this.missileLeft = currentTank.leftPos; this.missileTop = currentTank.topPos; //Launch(); }
// 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; } }
// Constructor public EnemyMissile(Tank.direction direction, int missileLeft, int missileTop) { //this.currentTank = tank; this.missleDirection = direction; this.missileLeft = missileLeft; this.missileTop = missileTop; //Launch(); }
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(); }
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"); }
// 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; } } }
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); } }
} // Удаление пули private void MaxTouch(Tank tnk) { }
} // Отрисовка карты 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")); } // Добавление танков на карту
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); }
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; }
// 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'); }
public override void Draw(Graphics g, Tank t) { bullets.ForEach(b => b.Draw(g, t)); }
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(); }
public override string Run(Tank t) { string result = "id: " + id + ", x: " + t.pos.X + ", y: " + t.pos.Y; return result; }
public TankWithOptics(Tank tank, double opticsIncreaser) : base(tank) { _opticsIncreaser = opticsIncreaser; }
abstract public void Fire(Tank t, int targetID);
public abstract void Fire(Tank t, int targetID);
}// Проверка на столкновение пули с объектом карты private void PositionСhange(Tank tank) { Dispatcher.Invoke(() => Canvas.SetTop(tank.GetImage(), tank.GetCoordinates.CordinateToY)); Dispatcher.Invoke(() => Canvas.SetLeft(tank.GetImage(), tank.GetCoordinates.CordinateToX)); } // Перемещение танка
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) { } }
abstract public string Run(Tank t);
public TankWithRecharger(Tank tank, double rechargerDecreaser) : base(tank) { _rechargerDecreaser = rechargerDecreaser; }
abstract public void Draw(Graphics g, Tank t);
public abstract void Draw(Graphics g, Tank t);
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; } }
public abstract string Run(Tank t);
public HomingBullet(double speed, double orientation, PointF pos, Tank t, Color color) : base(speed, orientation, pos, color) { this.t = t; }