#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Windows.Devices.Sensors;
using Windows.Foundation;
using Microsoft.Xna.Framework.Input.Touch;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using Microsoft.Xna.Framework.Audio;
#endregion
namespace SkyWar
{
/// <summary>
/// This screen implements the actual game logic. It is just a
/// placeholder to get the idea across: you'll probably want to
/// put some more interesting gameplay in here!
/// </summary>
class GameplayScreen : GameScreen
{
#region Fields
SpriteFont gameStatusFont;
Texture2D playership, gameOver, t2dTouchGas, t2dTouchFire;
public Rectangle GasTouchBound { get { return new Rectangle(0, _gameData.GameScreenHeight - t2dTouchGas.Height, t2dTouchGas.Width, t2dTouchGas.Height); } }
public Rectangle FireTouchBound { get { return new Rectangle(_gameData.GameScreenWidth - t2dTouchFire.Width, _gameData.GameScreenHeight - t2dTouchFire.Height, t2dTouchFire.Width, t2dTouchFire.Height); } }
ContentManager content;
GameData _gameData = null;
SpriteFont gameStatFont;
float fGameOverExitTime = 1.0f;
float fGameOver = 0.0f;
InputAction pauseAction;
//background
Background background;
//spaceship
public SpaceShip SpaceShipComponent
{
get { return spaceShipObj; }
private set { spaceShipObj = value; }
}
SpaceShip spaceShipObj;
int iMaxHorizontalSpeed = 15;
int iMinHorizontalSpeen = -7;
public int iPlayAreaLeft = 0;
public int iPlayAreaRight = 1024;
float fBoardUpdateDelay = 0f;
float fBoardUpdateInterval = 0.01f;
Accelerometer _accelerometer;
readonly object _accelerometerObjectLock = new object();
Vector2 acceloVelocity = new Vector2(0, 0);
float acceleoSpeed = 50.0f;
bool _touchGasFlag = false;
float accelThreshold = 0.10f;
//bullets
static int iMaxBullets = 40;
Bullet[] bullets = new Bullet[iMaxBullets];
float fBulletDelayTimer = 0.0f;
float fFireDelay = 0.15f;
SoundEffectInstance[] laserGunSound = new SoundEffectInstance[2];
//aliens
Dictionary<string, AlienType> _alienTypes;
LevelData _levelData;
public int Level;
AliensComponent alienCompnts;
//explosion
AnimatedSprite explosionSprt;
//add lifelines
Random rndGen = new Random();
static int iMaxPowerups = 4;
PowerUp[] powerups = new PowerUp[iMaxPowerups];
float fSuperBombTimer = 5.0f;
float fPowerUpSpawnCounter = 0.0f;
float fPowerUpSpawnDelay = 30.0f;
int[] iBulletFacingOffsets = new int[2] { 70, 0 };
int iBulletVerticalOffset = 12;
SoundEffectInstance powerUpPickupSound;
SoundEffectInstance powerDisplay;
SoundEffectInstance gameOverSound;
#endregion
#region Initialization
public GameplayScreen()
{
TransitionOnTime = TimeSpan.FromSeconds(1.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
pauseAction = new InputAction(
new Buttons[] { Buttons.Start, Buttons.Back },
new Keys[] { Keys.Escape },
true);
_gameData = GameData.GetGameDataInstance();
_gameData.PlayerHealth = 100;
_gameData.PlayerLives = 3;
_gameData.TotalScore = 0;
_gameData.IsGameOver = false;
}
public override void Activate(bool instancePreserved)
{
if (!instancePreserved)
{
if (content == null)
content = new ContentManager(ScreenManager.Game.Services, "Content");
//game statstics font
gameStatFont = content.Load<SpriteFont>("fonts/gamefont");
//game over screen
gameOver = content.Load<Texture2D>("images/gameover");
//create space ship
spaceShipObj = new SpaceShip(content, "images/plane");
iPlayAreaRight = _gameData.GameScreenWidth - _gameData.SpaceShipWidth;
//load game background
background = new Background(content, "images/galaxy", "images/ParallaxStars");
//load texture for gas and fire
t2dTouchGas = content.Load<Texture2D>("images/gas");
t2dTouchFire = content.Load<Texture2D>("images/fire");
//explosion
Texture2D explosion = content.Load<Texture2D>("images/explosions");
_gameData.Explosion = explosion;
explosionSprt = new AnimatedSprite(explosion, 0, 448, 64, 64, 16);
//load spaceship
playership = content.Load<Texture2D>("images/plane");
_gameData.SpaceShipHeight = playership.Height;
_gameData.SpaceShipWidth = playership.Width;
//enable bullets
for (int x = 0; x < iMaxBullets; x++)
{
bullets[x] = new Bullet(content, "images/laser");
bullets[x].Facing = spaceShipObj.Facing;
}
//initialize powers
for (int i = 0; i < iMaxPowerups; i++)
{
powerups[i] = new PowerUp(content.Load<Texture2D>("images/lifeline"));
}
//initialize sounds
laserGunSound[0] = _gameData.AudioLibarary.SingleLaserGun;
laserGunSound[1] = _gameData.AudioLibarary.DoubleLaserGun;
powerUpPickupSound = _gameData.AudioLibarary.PowerGet;
powerDisplay = _gameData.AudioLibarary.PowerDisplay;
gameOverSound = _gameData.AudioLibarary.GameOver;
//create aliens
_alienTypes = (from at in XElement.Load("Data/AlienTypes.xml").Descendants("AlienType")
select new AlienType
{
Name = (string)at.Attribute("Name"),
Score = (int)at.Attribute("Score"),
MaxXSpeed = (float)at.Attribute("MaxXSpeed"),
MaxYSpeed = (float)at.Attribute("MaxYSpeed"),
Texture = content.Load<Texture2D>((string)at.Attribute("Texture")),
FirstFrame = ParseRectangle((string)at.Attribute("FirstFrame")),
Space = (int)at.Attribute("Space"),
Frames = (int)at.Attribute("Frames"),
AnimationRate = TimeSpan.FromMilliseconds((int)at.Attribute("AnimationRate")),
Bullets = (int)at.Attribute("Bullets")
}).ToDictionary(t => t.Name);
InitLevel(1);
alienCompnts = new AliensComponent(this, content);
//add accelerometer for spaceship
_accelerometer = Accelerometer.GetDefault();
if (_accelerometer != null)
{
_accelerometer.ReportInterval = 16;
_accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
}
// A real game would probably have more content than this sample, so
// it would take longer to load. We simulate that by delaying for a
// while, giving you a chance to admire the beautiful loading screen.
//Thread.Sleep(1000);
// once the load has finished, we use ResetElapsedTime to tell the game's
// timing mechanism that we have just finished a very long frame, and that
// it should not try to catch up.
ScreenManager.Game.ResetElapsedTime();
}
#if WINDOWS_PHONE
if (Microsoft.Phone.Shell.PhoneApplicationService.Current.State.ContainsKey("PlayerPosition"))
{
playerPosition = (Vector2)Microsoft.Phone.Shell.PhoneApplicationService.Current.State["PlayerPosition"];
enemyPosition = (Vector2)Microsoft.Phone.Shell.PhoneApplicationService.Current.State["EnemyPosition"];
}
#endif
}
internal LevelData GetCurrentLevelData()
{
return _levelData;
}
internal AlienType GetAlienType(string name)
{
return _alienTypes[name];
}
public void InitLevel(int levelNum)
{
// if could not able to load next level then game ends...show game finishing screen
try
{
Level = levelNum;
_levelData = (from level in XElement.Load("Data/Levels.xml").Descendants("Level")
where (int)level.Attribute("Number") == levelNum
select new LevelData
{
Number = levelNum,
ChangeDirChance = (int)level.Attribute("ChangeDirChance"),
MaxActiveAliens = (int)level.Attribute("MaxActiveAliens"),
TotalAliensToFinish = (int)level.Attribute("TotalAliensToFinish"),
Boss = _alienTypes[(string)level.Attribute("Boss")],
FireChance = (int)level.Attribute("FireChance"),
MaxAlienBullets = (int)level.Attribute("MaxAlienBullets"),
AlienGenerationTime = TimeSpan.FromMilliseconds((int)level.Attribute("AlienGenerationTime")),
SelectionData = (from sel in level.Descendants("AlienType")
select new AlienSelectionData
{
Chance = (int)sel.Attribute("Chance"),
Alien = _alienTypes[(string)sel.Attribute("Name")]
}).ToList()
}).SingleOrDefault();
}
catch (Exception ex)
{
_gameData.IsGameOver = true;
fGameOverExitTime = 6.0f;
}
}
public static Rectangle ParseRectangle(string p)
{
string[] nums = p.Split(',');
//Debug.Assert(nums.Length == 4);
return new Rectangle(int.Parse(nums[0]), int.Parse(nums[1]), int.Parse(nums[2]), int.Parse(nums[3]));
}
private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
{
acceloVelocity.X = (float)e.Reading.AccelerationX;
//lock (_accelerometerObjectLock)
//{
// acceloVelocity.X = (float)e.Reading.AccelerationX * acceleoSpeed;
//}
}
public override void Deactivate()
{
#if WINDOWS_PHONE
Microsoft.Phone.Shell.PhoneApplicationService.Current.State["PlayerPosition"] = playerPosition;
Microsoft.Phone.Shell.PhoneApplicationService.Current.State["EnemyPosition"] = enemyPosition;
#endif
base.Deactivate();
}
/// <summary>
/// Unload graphics content used by the game.
/// </summary>
public override void Unload()
{
content.Unload();
#if WINDOWS_PHONE
Microsoft.Phone.Shell.PhoneApplicationService.Current.State.Remove("PlayerPosition");
Microsoft.Phone.Shell.PhoneApplicationService.Current.State.Remove("EnemyPosition");
#endif
}
#endregion
#region Update and Draw
protected void CheckVerticalMovementKeys(KeyboardState ksKeys, GamePadState gsPad)
{
bool bResetTimer = false;
spaceShipObj.Thrusting = false;
//if ((ksKeys.IsKeyDown(Keys.Down)) ||
// (gsPad.ThumbSticks.Left.Y > 0))
//{
//if (spaceShipObj.ScrollRate < iMaxHorizontalSpeed)
//{
// spaceShipObj.ScrollRate += spaceShipObj.AccelerationRate;
// if (spaceShipObj.ScrollRate > iMaxHorizontalSpeed)
// spaceShipObj.ScrollRate = iMaxHorizontalSpeed;
// bResetTimer = true;
//}
//spaceShipObj.Thrusting = true;
//spaceShipObj.Facing = 0;
//}
//if ((ksKeys.IsKeyDown(Keys.Up)) ||
// (gsPad.ThumbSticks.Left.Y < 0))
//{
if (spaceShipObj.ScrollRate > -iMaxHorizontalSpeed)
{
spaceShipObj.ScrollRate -= spaceShipObj.AccelerationRate;
if (spaceShipObj.ScrollRate < -iMaxHorizontalSpeed)
spaceShipObj.ScrollRate = -iMaxHorizontalSpeed;
bResetTimer = true;
}
spaceShipObj.Thrusting = true;
spaceShipObj.Facing = 1;
//}
if (bResetTimer)
spaceShipObj.SpeedChangeCount = 0.0f;
}
protected void UpdateShipSpeed()
{
if (_touchGasFlag)
{
spaceShipObj.ScrollRate = spaceShipObj.ScrollRate + 1;
if (spaceShipObj.ScrollRate >= iMinHorizontalSpeen)
spaceShipObj.ScrollRate = iMinHorizontalSpeen;
}
}
protected void CheckHorizontalMovementKeys(KeyboardState ksKeys, GamePadState gsPad)
{
if (ksKeys.IsKeyDown(Keys.Left))
{
spaceShipObj.X -= 5;
if (spaceShipObj.X < iPlayAreaLeft)
spaceShipObj.X = iPlayAreaLeft;
}
if (ksKeys.IsKeyDown(Keys.Right))
{
spaceShipObj.X += 5;
if (spaceShipObj.X + spaceShipObj.ShipWidth > iPlayAreaRight)
spaceShipObj.X = iPlayAreaRight - spaceShipObj.ShipWidth;
}
//bool bResetTimer = false;
//if ((ksKeys.IsKeyDown(Keys.Left)) || (gsPad.ThumbSticks.Left.X > 0) || spaceShipObj.X > iPlayAreaLeft)
//{
// if (spaceShipObj.X > iPlayAreaLeft)
// {
// spaceShipObj.X -= spaceShipObj.VerticalMovementRate;
// bResetTimer = true;
// }
//}
//if ((ksKeys.IsKeyDown(Keys.Right)) || (gsPad.ThumbSticks.Left.X < 0) || spaceShipObj.X < iPlayAreaRight)
//{
// if (spaceShipObj.X < iPlayAreaRight)
// {
// spaceShipObj.X += spaceShipObj.VerticalMovementRate;
// bResetTimer = true;
// }
//}
//if (bResetTimer)
// spaceShipObj.VerticalChangeCount = 0f;
}
public void UpdateBoard()
{
background.BackgroundOffset += spaceShipObj.ScrollRate;
background.ParallaxOffset += spaceShipObj.ScrollRate * 2;
}
protected void UpdateBullets(GameTime gameTime)
{
// Updates the location of all of thell active spaceShip bullets.
for (int x = 0; x < iMaxBullets; x++)
{
if (bullets[x].IsActive)
{
bullets[x].Update(gameTime);
foreach (var alien in alienCompnts.Aliens)
{
if (alien != null && alien.Active && !alien.IsDead && bullets[x].Collide(alien))
{
// alien hit!
bullets[x].IsActive = false;
_gameData.TotalScore += alien.Type.Score * Level;
alien.Hit();
}
}
if (alienCompnts.BossAlien != null && alienCompnts.BossAlien.Active && (!alienCompnts.BossAlien.IsDead) && bullets[x].Collide(alienCompnts.BossAlien))
{
//boss alien hit
bullets[x].IsActive = false;
_gameData.TotalScore += alienCompnts.BossAlien.Type.Score * Level;
alienCompnts.BossAlien.Hit();
}
}
}
}
protected void FireBullet(int iVerticalOffset)
{
// Find and fire a free bullet
for (int x = 0; x < iMaxBullets; x++)
{
if (!bullets[x].IsActive)
{
//if (!bullets[x].IsActive)
//{
// //bullets[x].Fire(spaceShipObj.X + iBulletFacingOffsets[spaceShipObj.Facing],
// // spaceShipObj.Y + iBulletVerticalOffset + iVerticalOffset,
// // spaceShipObj.Facing);
// bullets[x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 2 - 7,
// iBulletFacingOffsets[spaceShipObj.Facing] + spaceShipObj.Y + spaceShipObj.ShipHeight / 2 + iBulletVerticalOffset + iVerticalOffset, spaceShipObj.Facing);
// break;
//}
if (spaceShipObj.Facing == 1) // ie up
{
if (spaceShipObj.WeaponLevel > 0)
{
bullets[x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 4, spaceShipObj.Y - spaceShipObj.ShipHeight / 2, spaceShipObj.Facing);
bullets[++x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 2 + 7, spaceShipObj.Y - spaceShipObj.ShipHeight / 2, spaceShipObj.Facing);
}
else
bullets[x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 2 - 7, spaceShipObj.Y - spaceShipObj.ShipHeight / 2, spaceShipObj.Facing);
}
else
{
if (spaceShipObj.WeaponLevel > 0)
{
bullets[x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 4, spaceShipObj.Y - spaceShipObj.ShipHeight / 2, spaceShipObj.Facing);
bullets[++x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 2 + 7, spaceShipObj.Y - spaceShipObj.ShipHeight / 2, spaceShipObj.Facing);
}
else
bullets[x].Fire(spaceShipObj.X + spaceShipObj.ShipWidth / 2 - 7, spaceShipObj.Y + spaceShipObj.ShipHeight / 2, spaceShipObj.Facing);
}
break;
}
}
//if (iVerticalOffset == 0)
laserGunSound[spaceShipObj.WeaponLevel].Play();
}
protected void CheckOtherKeys()
{
if (fBulletDelayTimer >= fFireDelay)
{
FireBullet(0);
fBulletDelayTimer = 0.0f;
if (spaceShipObj.WeaponLevel == 1)
{
FireBullet(-4);
}
}
if ((fSuperBombTimer > spaceShipObj.SuperBombDelay) &&
(spaceShipObj.SuperBombs > 0))
{
spaceShipObj.SuperBombs--;
fSuperBombTimer = 0f;
ExecuteSuperBomb();
}
}
protected bool Intersects(Rectangle rectA, Rectangle rectB)
{
// Returns True if rectA and rectB contain any overlapping points
return (rectA.Right > rectB.Left && rectA.Left < rectB.Right &&
rectA.Bottom > rectB.Top && rectA.Top < rectB.Bottom);
}
protected void ExecuteSuperBomb()
{
foreach (Alien alien in alienCompnts.Aliens)
{
if (alien != null)
{
if (Intersects(alien.BoundingRect, new Rectangle(0, 0, _gameData.GameScreenWidth, _gameData.GameScreenHeight)))
alien.Hit();
}
}
}
protected void GeneratePowerup()
{
for (int x = 0; x < iMaxPowerups; x++)
{
if (!powerups[x].IsActive)
{
powerups[x].X = rndGen.Next(75, _gameData.BackgroundWidth - 75);
powerups[x].Y = rndGen.Next(0, _gameData.BackgroundHeight);
powerups[x].PowerUpType = rndGen.Next(0, 6);
powerups[x].Offset = background.BackgroundOffset;
powerups[x].Activate();
powerDisplay.Play();
break;
}
}
}
protected void UpdateLifeLines()
{
for (int x = 0; x < iMaxPowerups; x++)
{
if ((powerups[x].IsActive) && (Intersects(spaceShipObj.BoundingBox, powerups[x].BoundingBox)))
{
switch (powerups[x].PowerUpType)
{
case 0: //an extra life
_gameData.PlayerLives++;
break;
case 1: //give an extra superbomb
spaceShipObj.SuperBombs++;
break;
case 2: //increase acceleration
spaceShipObj.AccelerationBonus++;
break;
case 3: //change firing type to 2 bullets
spaceShipObj.WeaponLevel = 1;
break;
case 4: //increase fire rate
spaceShipObj.FireRate++;
break;
case 5: //increase health to 100%
_gameData.PlayerHealth = 100;
break;
}
powerups[x].IsActive = false;
powerUpPickupSound.Play();
}
}
}
bool explosionFlag = true,gameOverSoundPlayFlag=false;
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, false);
if (IsActive)
{
spaceShipObj.Update(gameTime);
float gameElapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (_gameData.IsGameOver || _gameData.IsGameCompleted)
{
if (_gameData.IsGameOver && (!gameOverSoundPlayFlag))
{
gameOverSound.Play();
gameOverSoundPlayFlag = true;
}
fGameOver += gameElapsedTime;
if (fGameOver > fGameOverExitTime)
{
ExitScreen();
LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(), new MainMenuScreen());
}
}
if (spaceShipObj.IsSpaceShipActive)
{
explosionFlag = true;
//if space is active then only update it
//Vector2 vel = new Vector2(spaceShipObj.X, spaceShipObj.Y);
//lock (_accelerometerObjectLock)
//{
// vel.X = acceloVelocity.X;
//}
float movement = 0.0f;
if (System.Math.Abs(acceloVelocity.X) > accelThreshold)
{
movement = acceloVelocity.X * acceleoSpeed;
}
//update spaceship postision
spaceShipObj.X += (int)movement;
spaceShipObj.Update(gameTime);
if (spaceShipObj.X <= iPlayAreaLeft)
spaceShipObj.X = iPlayAreaLeft;
if (spaceShipObj.X + spaceShipObj.ShipWidth >= iPlayAreaRight)
spaceShipObj.X = iPlayAreaRight - spaceShipObj.ShipWidth;
spaceShipObj.SpeedChangeCount += gameElapsedTime;
spaceShipObj.VerticalChangeCount += gameElapsedTime;
//check if gas or fire is touched or not
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed) || (tl.State == TouchLocationState.Moved))
{
//check gas
if (GasTouchBound.Intersects(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 80, 80)))
{
_touchGasFlag = true;
if (spaceShipObj.SpeedChangeCount > spaceShipObj.SpeedChangeDelay)
CheckVerticalMovementKeys(Keyboard.GetState(), GamePad.GetState(PlayerIndex.One));
}
else
UpdateShipSpeed();
//check fire
if (FireTouchBound.Intersects(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 80, 80)))
{
CheckOtherKeys();
}
}
}
if (touchCollection.Count == 0)
{
UpdateShipSpeed();
}
//give keyboard support
KeyboardState keyboardState = Keyboard.GetState();
if (spaceShipObj.SpeedChangeCount > spaceShipObj.SpeedChangeDelay)
{
if (keyboardState.IsKeyDown(Keys.Up))
CheckVerticalMovementKeys(Keyboard.GetState(), GamePad.GetState(PlayerIndex.One));
else
UpdateShipSpeed();
}
if (spaceShipObj.VerticalChangeCount > spaceShipObj.VerticalChangeDelay)
{
CheckHorizontalMovementKeys(keyboardState, GamePad.GetState(PlayerIndex.One));
}
if (keyboardState.IsKeyDown(Keys.Space))
CheckOtherKeys();
//Accumulate time since the last super bomb was fired
fSuperBombTimer += gameElapsedTime;
//Accumulate time since the last powerup was generated
fPowerUpSpawnCounter += gameElapsedTime;
if (fPowerUpSpawnCounter > fPowerUpSpawnDelay)
{
GeneratePowerup();
fPowerUpSpawnCounter = 0.0f;
}
// Update Powerups
for (int x = 0; x < iMaxPowerups; x++)
powerups[x].Update(gameTime, background.BackgroundOffset);
//spaceShipObj.VerticalChangeCount += (float)gameTime.ElapsedGameTime.TotalSeconds;
//if (spaceShipObj.VerticalChangeCount > spaceShipObj.VerticalChangeDelay)
//{
// CheckHorizontalMovementKeys(Keyboard.GetState(), GamePad.GetState(PlayerIndex.One));
//}
//update lifelines
UpdateLifeLines();
fBoardUpdateDelay += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (fBoardUpdateDelay > fBoardUpdateInterval)
{
fBoardUpdateDelay = 0f;
UpdateBoard();
}
fBulletDelayTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
}
else
{
if (explosionFlag)
{
explosionSprt.OneShotAnimation = true;
explosionSprt.DeactivateOnAnimationOver = true;
explosionFlag = false;
explosionSprt.IsActive = true;
}
explosionSprt.Update(gameTime);
}
UpdateBullets(gameTime);
alienCompnts.Update(gameTime);
}
}
public override void HandleInput(GameTime gameTime, InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
// Look up inputs for the active player profile.
int playerIndex = (int)ControllingPlayer.Value;
KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];
// The game pauses either if the user presses the pause button, or if
// they unplug the active gamepad. This requires us to keep track of
// whether a gamepad was ever plugged in, because we don't want to pause
// on PC if they are playing with a keyboard and have no gamepad at all!
bool gamePadDisconnected = !gamePadState.IsConnected && input.GamePadWasConnected[playerIndex];
PlayerIndex player;
if (pauseAction.Evaluate(input, ControllingPlayer, out player) || gamePadDisconnected)
{
#if WINDOWS_PHONE
ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer);
#else
ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
#endif
}
else
{
// Otherwise move the player position.
//Vector2 movement = Vector2.Zero;
//if (keyboardState.IsKeyDown(Keys.Left))
// movement.X--;
//if (keyboardState.IsKeyDown(Keys.Right))
// movement.X++;
//if (keyboardState.IsKeyDown(Keys.Up))
// movement.Y--;
//if (keyboardState.IsKeyDown(Keys.Down))
// movement.Y++;
//Vector2 thumbstick = gamePadState.ThumbSticks.Left;
//movement.X += thumbstick.X;
//movement.Y -= thumbstick.Y;
//if (input.TouchState.Count > 0)
//{
// Vector2 touchPosition = input.TouchState[0].Position;
// Vector2 direction = touchPosition - playerPosition;
// direction.Normalize();
// movement += direction;
//}
//if (movement.Length() > 1)
// movement.Normalize();
//playerPosition += movement * 8f;
}
}
public override void Draw(GameTime gameTime)
{
ScreenManager.GraphicsDevice.Clear(ClearOptions.Target, Color.CornflowerBlue, 0, 0);
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
if ((!_gameData.IsGameOver) && (!_gameData.IsGameCompleted))
{
//always draw background first
//draw backgound
background.Draw(spriteBatch);
if (_accelerometer != null)
{
//draw gas and fire button
spriteBatch.Draw(t2dTouchGas, GasTouchBound, Color.White);
spriteBatch.Draw(t2dTouchFire, FireTouchBound, Color.White);
}
//draw spaceship
spaceShipObj.Draw(spriteBatch);
//draw explosion
if ((!spaceShipObj.IsSpaceShipActive) && explosionSprt.IsActive)
explosionSprt.Draw(spriteBatch, spaceShipObj.X + spaceShipObj.ShipWidth / 2, spaceShipObj.Y + spaceShipObj.ShipHeight / 2, false);
//draw powers
for (int i = 0; i < iMaxPowerups; i++)
{
powerups[i].Draw(spriteBatch);
}
// Draw any active player bullets on the screen
for (int i = 0; i < iMaxBullets; i++)
{
// Only draw active bullets
if (bullets[i].IsActive)
{
bullets[i].Draw(spriteBatch);
}
}
//draw aliens on screen
alienCompnts.Draw(gameTime, spriteBatch);
//game score
spriteBatch.DrawString(gameStatFont, string.Format("Score : {0,6}", _gameData.TotalScore), new Vector2(15, 15), Color.Yellow);
spriteBatch.DrawString(gameStatFont, string.Format("Health : {0,4}", _gameData.PlayerHealth), new Vector2(15, 50), Color.Yellow);
spriteBatch.DrawString(gameStatFont, string.Format("Level : {0,3}", Level), new Vector2(15, 85), Color.Yellow);
spriteBatch.Draw(playership, new Vector2(15, 135), new Rectangle(0, 0, playership.Width, playership.Height), Color.White, 0, Vector2.Zero, 0.7f, SpriteEffects.None, 0f);
spriteBatch.DrawString(gameStatFont, string.Format(" {0,3}", _gameData.PlayerLives), new Vector2(50, 125), Color.Yellow);
//for (int i = 0; i < _gameData.PlayerLives; i++)
// spriteBatch.Draw(playership, new Vector2(i * 60 + 15, 100), new Rectangle(0, 0, playership.Width, playership.Height), Color.White, 0, Vector2.Zero, 0.7f, SpriteEffects.None, 0f);
}
else
{
//explosionSprt.Draw(spriteBatch, spaceShipObj.X + spaceShipObj.ShipWidth / 2, spaceShipObj.Y + spaceShipObj.ShipHeight / 2, false);
spriteBatch.Draw(gameOver, new Rectangle(0, 0, _gameData.GameScreenWidth, _gameData.GameScreenHeight), Color.White);
if (_gameData.IsGameCompleted)
{
spriteBatch.DrawString(gameStatFont, "CONGRATULATIONS", new Vector2(_gameData.GameScreenWidth / 2 - 200, _gameData.GameScreenWidth / 4), Color.Yellow);
spriteBatch.DrawString(gameStatFont, "You have completed all levels", new Vector2(_gameData.GameScreenWidth / 2 - 200, _gameData.GameScreenWidth / 4 + 150), Color.Yellow);
}
else if (_gameData.IsGameOver)
spriteBatch.DrawString(gameStatFont, "GAME OVER", new Vector2(_gameData.GameScreenWidth / 2 - 100, _gameData.GameScreenWidth / 4), Color.Red);
}
spriteBatch.End();
}
#endregion
}
}