/// <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 tank = new Tank(); children.Add(tank); foreach (Entity entity in children) { entity.Initialize(); } base.Initialize(); }
/// <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() { playerTank = new Tank(); enemyTank = new AITank(); enemyTank.pos = new Vector2(ScreenWidth / 2, 400); children.Add(playerTank); children.Add(enemyTank); for ( int i = 0; i < children.Count(); i++ ) { children[i].Initialize(); } base.Initialize(); }
public void Update(KeyboardState keyboard, MouseState mouse, GameTime gameTime, Tank tank1) { if (keyboard.IsKeyDown(Keys.F3)) { mode = PlayerMode.CameraSurfaceFollow; Mouse.SetPosition(this.graphicsDevice.Viewport.Width / 2, this.graphicsDevice.Viewport.Height / 2); } if (keyboard.IsKeyDown(Keys.F2)) { mode = PlayerMode.CameraFree; Mouse.SetPosition(this.graphicsDevice.Viewport.Width / 2, this.graphicsDevice.Viewport.Height / 2); } if (keyboard.IsKeyDown(Keys.F1)) { mode = PlayerMode.CameraTank; } if (mode == PlayerMode.CameraSurfaceFollow) { int centroX = graphicsDevice.Viewport.Width / 2; int centroY = graphicsDevice.Viewport.Height / 2; int deltaX = mouse.X - centroX; int deltaY = mouse.Y - centroY; yaw = yaw - deltaX * escalaRadianosPorPixel; pitch = pitch + deltaY * escalaRadianosPorPixel; pitch = MathHelper.Clamp(pitch, -1, 1); Matrix rotacao = Matrix.CreateFromYawPitchRoll(yaw, pitch, 0); Vector3 dir = Vector3.Transform(-Vector3.UnitZ, rotacao); Vector3 right = Vector3.Cross(dir, Vector3.Up); if (keyboard.IsKeyDown(Keys.NumPad8)) // { // pos = pos + dir * cameraSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; // } // if (keyboard.IsKeyDown(Keys.NumPad5)) // { // pos = pos - dir * cameraSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; // } // Controlo de movimento da camara if (keyboard.IsKeyDown(Keys.NumPad4)) // { // pos = pos - right * cameraSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; // } // if (keyboard.IsKeyDown(Keys.NumPad6)) { // pos = pos + right * cameraSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; // } if (pos.X < terreno.vertices[0].Position.X) // { pos.X = terreno.vertices[0].Position.X; // } if (pos.Z < terreno.vertices[0].Position.Z) // { pos.Z = terreno.vertices[0].Position.Z; // Mantém a camara dentro dos limites do terreno } if (pos.X > terreno.vertices[terreno.vertices.Length - 1].Position.X) // { pos.X = terreno.vertices[terreno.vertices.Length - 1].Position.X - 0.0001f; // } if (pos.Z > terreno.vertices[terreno.vertices.Length - 1].Position.Z) // { pos.Z = terreno.vertices[terreno.vertices.Length - 1].Position.Z - 0.0001f; // } Vector3[] vectors = terreno.GetVerticesFromXZ((int)pos.X, (int)pos.Z); // Vai buscar os vetores que circulam a camara float YA = vectors[0].Y; // float YB = vectors[1].Y; // Posição Y de cada vetor float YC = vectors[2].Y; // float YD = vectors[3].Y; // float YAB = ((((int)pos.Z + 1) - pos.Z) * YA + (pos.Z - (int)pos.Z) * YB); // Interpolação do Y entre A e B float YCD = ((((int)pos.Z + 1) - pos.Z) * YC + (pos.Z - (int)pos.Z) * YD); // Interpolação do Y entre C e D pos.Y = ((((int)pos.X + 1) - pos.X) * YAB + (pos.X - ((int)pos.X)) * YCD) + 2f; // Interpolação final para encontrar novo Y da camara, adicionando 2 à altura para não haver clipping target = pos + dir; // Atualiza o target viewMatrix = Matrix.CreateLookAt(pos, target, Vector3.Up); // Atualiza a viewMatrix Mouse.SetPosition(centroX, centroY); // Coloca o cursor no centro do ecrã } if (mode == PlayerMode.CameraFree) { //primeira coisa a ver é quanto o rato andou , mas apenas sabemos a posição dele, podemos tambem no fim da frame o rato sempre a meio da janela portanto prendemos o rato a meio da janela //neste caso o rato não mexe por isso usamos o device int centroX = graphicsDevice.Viewport.Width / 2; int centroY = graphicsDevice.Viewport.Height / 2; int deltaX = mouse.X - centroX;//é a nova posição do x - o centro do x yaw = yaw - deltaX * escalaRadianosPorPixel; int deltaY = mouse.Y - centroY; pitch -= deltaY * escalaRadianosPorPixel; pitch = MathHelper.Clamp(pitch, -1, 1); Matrix rotacao = Matrix.CreateFromYawPitchRoll(yaw, pitch, 0); //criar uma rotação Vector3 dir = Vector3.Transform(Vector3.UnitZ /*é um vetor base ,direção inicial olhar para frente*/, rotacao /*vetor rotação*/); //transformar vetor base(naão a yaw nem pitch) com a rotação Vector3 right = Vector3.Cross(dir, Vector3.Up); //cross do vetor que estamos a andar com a vertical //atualização da posição target = pos + dir; this.viewMatrix = Matrix.CreateLookAt(pos, target, Vector3.Up); Mouse.SetPosition(centroX, centroY); float vel = 30; if (keyboard.IsKeyDown(Keys.NumPad8)) { pos = pos + dir * vel * (float)gameTime.ElapsedGameTime.TotalSeconds; } if (keyboard.IsKeyDown(Keys.NumPad5)) { pos = pos - dir * vel * (float)gameTime.ElapsedGameTime.TotalSeconds; } if (keyboard.IsKeyDown(Keys.NumPad4)) { pos = pos - right * vel * (float)gameTime.ElapsedGameTime.TotalSeconds; } if (keyboard.IsKeyDown(Keys.NumPad6)) { pos = pos + right * vel * (float)gameTime.ElapsedGameTime.TotalSeconds; } if (keyboard.IsKeyDown(Keys.NumPad7)) { pos.Y += 0.5f; } if (keyboard.IsKeyDown(Keys.NumPad1)) { pos.Y -= 0.5f; } } if (mode == PlayerMode.CameraTank) { Vector3 cameraTarget = tank1.pos + tank1.dir + new Vector3(0, 3, 0); //target da camara calculado com posição e direção do tank e somado um vector3 para não olhar demasiado para baixo pos = tank1.pos - Vector3.Normalize(tank1.rotation.Backward) * 3f + new Vector3(0, 4, 0); //posição da camara calculado com posição da camara e vetor de tras da rotação da mesma, sendo somado um vector3 para a camara nao estar dentro do tank viewMatrix = Matrix.CreateLookAt(pos, cameraTarget, Vector3.Up); //atualização da viewMatrix } }
public Form2(string p1, string p2, string mf) { // Load data from previous form InitializeComponent(); player1Name = p1; player2Name = p2; mapFile = mf; // Load MapFile data Size = new System.Drawing.Size(800, 600); MapFile file = new MapFile(Application.StartupPath + "\\" + mapFile); file.loadData(); // Load tanks for MapFile tank1 = (Tank)file.Tanks[0]; tank2 = (Tank)file.Tanks[1]; // Create tanks -------------------------------------------------------------------------------- // Set locations of tanks Point point1 = new Point(tank1.Horizontal, tank1.Vertical); greentank.Location = point1; Point point2 = new Point(tank2.Horizontal, tank2.Vertical); redtank.Location = point2; // Set sizes of tanks greentank.Size = new System.Drawing.Size(60, 60); greentank.BackColor = Color.Transparent; redtank.Size = new System.Drawing.Size(60, 60); // Set image of greentank switch (tank1.Direction) { case 0: greentank.Image = greenimage0; break; case 1: greentank.Image = greenimage1; break; case 2: greentank.Image = greenimage2; break; case 3: greentank.Image = greenimage3; break; } // Set image of redtank switch (tank2.Direction) { case 0: redtank.Image = redimage0; break; case 1: redtank.Image = redimage1; break; case 2: redtank.Image = redimage2; break; case 3: redtank.Image = redimage3; break; } // Add tanks to form this.Controls.Add(greentank); this.Refresh(); this.Controls.Add(redtank); this.Refresh(); // Create bullets ------------------------------------------------------------------------------ // Set locations of bullets Point point3 = new Point(-100, -100); bullet1.Location = point3; bullet2.Location = point3; // Set sizes of bullets bullet1.Size = new System.Drawing.Size(30, 30); bullet2.Size = new System.Drawing.Size(30, 30); // Set image of bullets bullet1.Image = bulletimage; bullet2.Image = bulletimage; // Add bullets to form this.Controls.Add(bullet1); this.Refresh(); this.Controls.Add(bullet2); this.Refresh(); // Create walls -------------------------------------------------------------------------------- walls[0] = wall1; walls[1] = wall2; walls[2] = wall3; walls[3] = wall4; walls[4] = wall5; // Set wall attributes and load to form /*for(int i = 0; i < 5; i++) * { * Wall newWall = (Wall)file.Walls[i]; * Point point4 = new Point(newWall.Horizontal, newWall.Vertical); * walls[i].Location = point4; * walls[i].Size = new System.Drawing.Size(60,60); * walls[i].Image = wallimage; * this.Controls.Add(walls[i]); * this.Refresh(); * } */ timer1.Start(); this.Select(); }
public void loadData() { try { // Reads file StreamReader input = new StreamReader(file); // Reads tank lines String s1 = input.ReadLine(); String s2 = input.ReadLine(); // Puts split strings into string array string[] split1 = s1.Split(','); string[] split2 = s2.Split(','); // Creates int arrays int[] int1 = new int[3]; int[] int2 = new int[3]; int num; // Changes split string into split ints for (int i = 0; i < split1.Length; i++) { num = int.Parse(split1[i]); int1[i] = num; } for (int i = 0; i < split2.Length; i++) { num = int.Parse(split2[i]); int2[i] = num; } // Creates tank objects Tank tank1 = new Tank(null, int1[2], int1[0], int1[1]); Tank tank2 = new Tank(null, int2[2], int2[0], int2[1]); // Puts tank objects into tank collection tanks.Add(tank1); tanks.Add(tank2); String c = ""; while (c != null) { c = input.ReadLine(); string[] split3 = c.Split(','); int[] int3 = new int[2]; for (int i = 0; i < split3.Length; i++) { num = int.Parse(split3[i]); int3[i] = num; } Wall wall = new Wall(int3[0], int3[1]); walls.Add(wall); } // Closes file input.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <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() { basis = new Vector2(0, -1); playerTank = new Tank(); enemyTank = new AITank(); children.Add(playerTank); children.Add(enemyTank); for ( int i = 0; i < children.Count(); i++ ) { children[i].Initialize(); } base.Initialize(); }
// Use this for initialization void Start() { _mover = GetComponentInParent <TransformMover>(); _myPlayer = GetComponentInParent <Tank>(); }
public void PlayerDied(Tank tank) { tank.gameObject.SetActive(false); StartCoroutine(RespawnTimer(_deathTime, tank)); }
//********************************************************** //** methods: //********************************************************** public void Render(Tank tank) { RenderBody(tank); RenderBarrel(tank); RenderDirection(tank); }
public void LoadData() { try { StreamReader input = new StreamReader(this.mapFile); // Reads tank lines String s1 = input.ReadLine(); String s2 = input.ReadLine(); // Puts split strings into string array string[] split1 = s1.Split(','); string[] split2 = s2.Split(','); // Creates int arrays int[] int1 = new int[3]; int[] int2 = new int[3]; int num; // Changes split string into split ints for (int i = 0; i < split1.Length; i++) { num = int.Parse(split1[i]); int1[i] = num; } for (int i = 0; i < split2.Length; i++) { num = int.Parse(split2[i]); int2[i] = num; } // Creates tank objects Tank tank1 = new Tank(null, int1[2], int1[0], int1[1]); Tank tank2 = new Tank(null, int2[2], int2[0], int2[1]); // Puts tank objects into tank collection tanks.Add(tank1); tanks.Add(tank2); String c = String.Empty; while (c != null) { c = input.ReadLine(); string[] split3 = c.Split(','); int[] int3 = new int[2]; for (int i = 0; i < split3.Length; i++) { num = int.Parse(split3[i]); int3[i] = num; } Wall wall = new Wall(int3[0], int3[1]); walls.Add(wall); } // Closes mapFile input.Close(); } catch(System.Exception e) //TODO remove Exception { Console.WriteLine(e.Message); } }
public void Init(Tank owner) { _owner = owner; }
/** * 创建神经网络 */ private void Awake() { target = GetComponent <Tank>(); inputNum = considerTargets * 5 + 3; }
public override void Update(GameTime gameTime) { float timeDelta = (float)gameTime.ElapsedGameTime.TotalSeconds; Tank enemyTank = Game1.Instance.Tank; Vector2 toTarget = enemyTank.pos - pos; float distance = toTarget.Length(); if (distance < 150.0f) { if (toTarget.X < 0) { targetRotation = (float)-Math.Acos(Vector2.Dot(basis, Vector2.Normalize(toTarget))); } else { targetRotation = (float)Math.Acos(Vector2.Dot(basis, Vector2.Normalize(toTarget))); } attack = true; } else { attack = false; } float rotAmount = 1.0f; if (!attack) { // Not attacked: AI movement look.X = (float)-Math.Cos(rotation); look.Y = (float)Math.Sin(rotation); pos += look * speed * timeDelta; // Window boundaries detect if (pos.X < sprite.Width / 2) { rotation = MathHelper.Pi; } if (pos.X > Game1.Instance.Window.ClientBounds.Width - sprite.Width / 2) { rotation = 0.0f; } if (pos.Y < sprite.Height / 2) { pos.Y += speed * timeDelta; } if (pos.Y > Game1.Instance.Window.ClientBounds.Height - sprite.Height / 2) { pos.Y -= speed * timeDelta; } } else { // Attacked: move towards playerTank and fire bullets float direction = targetRotation - rotation; if (direction < 0) { rotation -= rotAmount * timeDelta; } else { rotation += rotAmount * timeDelta; } look.X = (float)Math.Sin(rotation); look.Y = (float)-Math.Cos(rotation); pos += look * speed * timeDelta; if (elapsedTime > (1.0f / fireRate)) { fireBullet(); elapsedTime = 0; } elapsedTime += timeDelta; if (elapsedTime >= 100) { elapsedTime = 100; } } }
public static bool Open(Tank myTank, Tank enemyTank) //Функция вызова контекстного меню { if (myTank.MyHealth <= 0) //Проверка на поражение { Console.WriteLine("Вы проиграли!"); Console.WriteLine("\nНажмите для выхода.."); Console.ReadKey(); return(true); } if (enemyTank.MyHealth <= 0)//Проверка на победу { Console.WriteLine("Победа!"); Console.WriteLine("\nНажмите для выхода.."); Console.ReadKey(); return(true); } Console.ForegroundColor = ConsoleColor.Green; myTank.GetStatus(); //Выводим текущее состояние нашего танка Console.ForegroundColor = ConsoleColor.Red; enemyTank.GetStatus(); //Выводим текущее состояние вражеского танка Console.ResetColor(); Console.WriteLine("\nВаш ход!\n"); int int_choice; Show(); //Выводим варианты действий try //Отлавливаем исключения при вводе данных { string _choice = Console.ReadLine(); //Выбираем с клавиатуры режим int_choice = Convert.ToInt32(_choice); //Преобразуем в int для более удобной работы switch (int_choice) //Рекурсивный выбор { case 1: //Выстрел myTank.Shot(enemyTank); //Игрок стреляет EnemyStep(myTank, enemyTank); break; case 2: //Починка myTank.Repair(); //Игрок ремонтируется EnemyStep(myTank, enemyTank); break; case 3: //Перезарядка myTank.Reload(); EnemyStep(myTank, enemyTank); break; case 4: //Выход break; default: //Неверный ввод Console.WriteLine("Неверный ввод. Нажмите чтоб продолжить.."); Console.ReadKey(); Console.Clear(); Open(myTank, enemyTank); break; } } catch (System.FormatException)//Перезапуск меню при ошибке ввода { Console.WriteLine("Неверный ввод. Нажмите чтоб продолжить.."); Console.ReadKey(); Console.Clear(); Open(myTank, enemyTank);//Перезапуск хода путем вызова игрового меню } return(true); }
public Form2(string playerOne, string playerTwo, string mapFile) { // Load data from previous form this.InitializeComponent(); this.playerOneName = playerOne; this.playerTwoName = playerTwo; this.mapFile = mapFile; // Load MapMapFile data this.Size = new System.Drawing.Size(800, 600); MapFile file = new MapFile("C:\\Users\\Frankie\\Documents\\C#\\TankGame\\" + this.mapFile); file.LoadData(); // Load tanks for MapMapFile this.tank1 = (Tank)file.Tanks[0]; this.tank2 = (Tank)file.Tanks[1]; // Create tanks -------------------------------------------------------------------------------- // Set locations of tanks Point point1 = new Point(this.tank1.Horizontal, this.tank1.Vertical); this.greentank.Location = point1; Point point2 = new Point(this.tank2.Horizontal, this.tank2.Vertical); this.redtank.Location = point2; // Set sizes of tanks this.greentank.Size = new System.Drawing.Size(60, 60); this.redtank.Size = new System.Drawing.Size(60, 60); // Set image of greentank switch (this.tank1.Direction) { case 0: this.greentank.Image = this.greenimage0; break; case 1: this.greentank.Image = this.greenimage1; break; case 2: this.greentank.Image = this.greenimage2; break; case 3: this.greentank.Image = this.greenimage3; break; } // Set image of redtank switch (this.tank2.Direction) { case 0: this.redtank.Image = this.redimage0; break; case 1: this.redtank.Image = this.redimage1; break; case 2: this.redtank.Image = this.redimage2; break; case 3: this.redtank.Image = this.redimage3; break; } // Add tanks to form this.Controls.Add(this.greentank); this.Refresh(); this.Controls.Add(this.redtank); this.Refresh(); // Create bullets ------------------------------------------------------------------------------ // Set locations of bullets Point point3 = new Point(-100, -100); this.bullet1.Location = point3; this.bullet2.Location = point3; // Set sizes of bullets this.bullet1.Size = new System.Drawing.Size(30, 30); this.bullet2.Size = new System.Drawing.Size(30, 30); // Set image of bullets this.bullet1.Image = this.bulletimage; this.bullet2.Image = this.bulletimage; // Add bullets to form this.Controls.Add(this.bullet1); this.Refresh(); this.Controls.Add(this.bullet2); this.Refresh(); // Create walls -------------------------------------------------------------------------------- this.walls[0] = this.wall1; this.walls[1] = this.wall2; this.walls[2] = this.wall3; this.walls[3] = this.wall4; this.walls[4] = this.wall5; // Set wall attributes and load to form for (int i = 0; i < 5; i++) { Wall newWall = (Wall)file.Walls[i]; Point point4 = new Point(newWall.Horizontal, newWall.Vertical); this.walls[i].Location = point4; this.walls[i].Size = new System.Drawing.Size(60,60); this.walls[i].Image = this.wallimage; this.Controls.Add(this.walls[i]); this.Refresh(); } this.timer1.Start(); this.Select(); }
public bool HasAttemptedBomb(Tank tank) { return(false); }