Created
August 13, 2013 07:27
-
-
Save JLChnToZ/6218676 to your computer and use it in GitHub Desktop.
Burn the falling pork game (Kinect ver.) source code (messy stuff)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using Microsoft.Xna.Framework; | |
using Microsoft.Xna.Framework.Audio; | |
using Microsoft.Xna.Framework.Graphics; | |
using Microsoft.Xna.Framework.Input; | |
using Microsoft.Kinect; | |
using libZPlay; | |
using XnaContentZipper; | |
namespace Pork { | |
/// <summary> | |
/// This is the main type for your game | |
/// </summary> | |
public class PorkGame:Microsoft.Xna.Framework.Game { | |
GraphicsDeviceManager G; | |
SpriteBatch SB; | |
ZippedContent C; | |
TimeSpan RGameTime; | |
Vector2 playerLocate; | |
ZPlay Z; | |
ulong score; | |
int totalPorks, allPorks, combos, maxCombos, difficulty, menuMode, trkID; | |
double nextFire, BoostAmount; | |
float life, Direction, HPBarValue, ChargeBarValue, handUpTime; | |
bool isPaused, showDesc; | |
string StatusText; | |
float[] K; | |
short[] KinectColorData; | |
byte[] KinectColorData2; | |
Texture2D PlayerTexture, EnemyTexture, backTexture, backTexture1, backTexture2, titleTexture, menuTexture, HPBarTexture, CursorTexture, KinectColorMap, KinectColorMap2; | |
Vector2[] HA, VA; | |
Effect GBlur, KinectEffect, KinectEffect2; | |
RenderTarget2D RT, RT_combine, RT_combine2, RT_BackBuffer, RT_BackBuffer2, RT_BackBuffer3; | |
SoundEffect BoostSound, FizzSound, GGSound, FullChargeSound, HoverSound, ClickSound; | |
KinectSensor Sensor; | |
KinectStatus KStatus; | |
Skeleton[] skeletons; | |
SpriteFont Font1, Font2; | |
List<GameObjects> PlayerObjects = new List<GameObjects>(); | |
List<GameObjects> EnemyObjects = new List<GameObjects>(); | |
List<FloatText> FloatTexts = new List<FloatText>(); | |
Random Rnd; | |
ObjectContainer<bool> SpaceBarState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> EnterState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> LKeyState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> RKeyState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> UKeyState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> DKeyState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> EscKeyState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> MouseState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> MouseHoverState = new ObjectContainer<bool>(); | |
ObjectContainer<bool> MouseHoverState2 = new ObjectContainer<bool>(); | |
ObjectContainer<bool> MouseHoverState3 = new ObjectContainer<bool>(); | |
const String BGM1Path = "bgm"; | |
const String BGM2Path = "bgm2"; | |
const String BGM3Path = "bgm3"; | |
private class GameObjects { | |
public GameObjects(Vector2 L, float D, float S, float P, float R, int F) { | |
this.Location = L; | |
this.Direction = D; | |
this.Strengh = this.MaxStrengh = S; | |
this.Speed = P; | |
this.Rotate = R; | |
this.Lifetime = 0; | |
this.Flag = F; | |
this.Score = 0; | |
} | |
public void Move(TimeSpan UpdateTime) { | |
Vector2 D = new Vector2((float)Math.Cos(Direction), (float)Math.Sin(Direction)) * new Vector2((float)(Speed * UpdateTime.TotalMilliseconds * 0.025)); | |
Location += D; | |
Lifetime += (float)(UpdateTime.TotalMilliseconds / 1000); | |
} | |
public float Rotate; | |
public Vector2 Location; | |
public float Direction, Strengh, MaxStrengh, Speed, Lifetime; | |
public int Flag, Score; | |
} | |
private class FloatText { | |
public Vector2 Locate; | |
public float Alpha; | |
public string T; | |
public FloatText(Vector2 L, string S) { | |
this.Alpha = 1; | |
this.Locate = L; | |
this.T = S; | |
} | |
public void Move(TimeSpan GT) { | |
this.Locate -= new Vector2(0, (float)(GT.TotalMilliseconds * 0.05)); | |
this.Alpha -= (float)(GT.TotalMilliseconds / 2000); | |
if(this.Alpha < 0) this.Alpha = 0; | |
} | |
} | |
public PorkGame() { | |
G = new GraphicsDeviceManager(this); | |
G.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8; | |
C = new ZippedContent("game.zcp", Services); | |
Z = new ZPlay(); | |
} | |
/// <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() { | |
DiscoverSeneor(); | |
G.PreferredBackBufferWidth = 640; | |
G.PreferredBackBufferHeight = 480; | |
G.PreferMultiSampling = true; | |
G.SynchronizeWithVerticalRetrace = false; | |
G.ApplyChanges(); | |
this.IsFixedTimeStep = false; | |
Font1 = C.Load<SpriteFont>("font"); | |
Font2 = C.Load<SpriteFont>("font2"); | |
BoostSound = C.Load<SoundEffect>("boost"); | |
FizzSound = C.Load<SoundEffect>("fizz"); | |
GGSound = C.Load<SoundEffect>("gg"); | |
FullChargeSound = C.Load<SoundEffect>("fullcharge"); | |
HoverSound = C.Load<SoundEffect>("hover"); | |
ClickSound = C.Load<SoundEffect>("click"); | |
PlayerTexture = C.Load<Texture2D>("water"); | |
EnemyTexture = C.Load<Texture2D>("fire"); | |
backTexture = C.Load<Texture2D>("bg"); | |
backTexture1 = C.Load<Texture2D>("bg2"); | |
backTexture2 = C.Load<Texture2D>("blr"); | |
titleTexture = C.Load<Texture2D>("title"); | |
menuTexture = C.Load<Texture2D>("menu"); | |
CursorTexture = C.Load<Texture2D>("cursor"); | |
GBlur = C.Load<Effect>("gblur"); | |
KinectEffect = C.Load<Effect>("kinectstream"); | |
KinectEffect2 = C.Load<Effect>("kinectstream2"); | |
RT = new RenderTarget2D(GraphicsDevice, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight, true, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents); | |
RT_combine = new RenderTarget2D(GraphicsDevice, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight, true, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents); | |
RT_combine2 = new RenderTarget2D(GraphicsDevice, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight, true, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents); | |
HPBarTexture = new Texture2D(GraphicsDevice, 1, 1); | |
HPBarTexture.SetData<Color>(new Color[] { Color.White }); | |
HPBarTexture = new Texture2D(GraphicsDevice, 1, 1); | |
HPBarTexture.SetData<Color>(new Color[] { Color.White }); | |
Z.SetSettings(libZPlay.TSettingID.sidAccurateSeek, 1); | |
RGameTime = TimeSpan.Zero; | |
Font1.Spacing = Font2.Spacing = -5; | |
trkID = -1; | |
isPaused = false; | |
difficulty = 1; | |
score = 0; | |
nextFire = 0; | |
Direction = 0; | |
life = 0; | |
HPBarValue = 0; | |
ChargeBarValue = 0; | |
BoostAmount = 0; | |
totalPorks = 0; | |
combos = 0; | |
maxCombos = 0; | |
allPorks = 0; | |
menuMode = 1; | |
handUpTime = 0; | |
showDesc = false; | |
KeyboardState K = Keyboard.GetState(); | |
EnterState.Value = K.IsKeyDown(Keys.Enter); | |
SpaceBarState.Value = false; | |
LKeyState.Value = K.IsKeyDown(Keys.Left); | |
RKeyState.Value = K.IsKeyDown(Keys.Right); | |
UKeyState.Value = K.IsKeyDown(Keys.Up); | |
DKeyState.Value = K.IsKeyDown(Keys.Down); | |
EscKeyState.Value = K.IsKeyDown(Keys.Escape); | |
Rnd = new Random(); | |
KinectSensor.KinectSensors.StatusChanged += KinectStatusChanged; | |
this.K = ComputeKernel(10, 1); | |
this.HA = ComputeOffsets(G.PreferredBackBufferWidth, 10, false); | |
this.VA = ComputeOffsets(G.PreferredBackBufferHeight, 10, true); | |
PlayLoop(BGM2Path); | |
base.Initialize(); | |
} | |
/// <summary> | |
/// LoadContent will be called once per game and is the place to load | |
/// all of your content. | |
/// </summary> | |
protected override void LoadContent() { | |
// Create a new SpriteBatch, which can be used to draw textures. | |
SB = new SpriteBatch(GraphicsDevice); | |
base.LoadContent(); | |
} | |
/// <summary> | |
/// UnloadContent will be called once per game and is the place to unload | |
/// all content. | |
/// </summary> | |
protected override void UnloadContent() { | |
// TODO: Unload any non ContentManager content here | |
base.UnloadContent(); | |
if(Sensor != null) Sensor.Stop(); | |
} | |
protected override void OnExiting(Object sender, EventArgs args) { | |
base.OnExiting(sender, args); | |
} | |
/// <summary> | |
/// Allows the game to run logic such as updating the world, | |
/// checking for collisions, gathering input, and playing audio. | |
/// </summary> | |
/// <param name="gameTime">Provides a snapshot of timing values.</param> | |
protected override void Update(GameTime GT) { | |
MouseState M = Mouse.GetState(); | |
KeyboardState K = Keyboard.GetState(); | |
float _angle = GetHandAngle(false); | |
if(IsActive) { | |
updateSkeleton(); | |
updateKinectImage(); | |
if(life > 0) | |
if(_angle < -0.5 && _angle > -1.5 && _angle != -99) { | |
handUpTime += (float)GT.ElapsedGameTime.TotalMilliseconds / 1000; | |
if (handUpTime > 1) { | |
handUpTime = 0; | |
isPaused = false; | |
} | |
} else { | |
handUpTime = 0; | |
if((_angle > 0.5 && _angle < 1.5) || _angle == -99) | |
isPaused = true; | |
} | |
} else { | |
isPaused = life > 0; | |
} | |
double TimeMultiplier = GT.ElapsedGameTime.TotalMilliseconds / 2; | |
if(K.IsKeyDown(Keys.LeftAlt) && K.IsKeyDown(Keys.Enter)) { | |
G.IsFullScreen = !G.IsFullScreen; | |
G.ApplyChanges(); | |
} | |
if(EscKeyState.SetValue(K.IsKeyDown(Keys.Escape)) && EscKeyState.Value) { | |
isPaused = false; | |
if(life > 0) life = -1; | |
else if(!showDesc) { | |
fadeOut(); | |
this.Exit(); | |
} | |
} | |
if(!isPaused) { | |
double DifficultMultiplier = Math.Max(1, Math.Log(Math.Max(1, score)) / Math.Log(4) / (3 - difficulty)); | |
if(life <= 0) DifficultMultiplier = 1; | |
Direction = _angle; | |
for(int i = PlayerObjects.Count - 1; i >= 0; i--) { | |
GameObjects PO = PlayerObjects[i]; | |
PO.Move(GT.ElapsedGameTime); | |
PO.Direction += (float)(Rnd.NextDouble() - 0.5) / 50; | |
PO.Strengh -= (float)TimeMultiplier / 1000; | |
foreach(GameObjects EO in EnemyObjects) if((PO.Location - EO.Location).Length() <= (PO.Strengh + EO.Strengh + PO.Lifetime / 10) * 30) { | |
int S = (int)Math.Ceiling(PO.Strengh * TimeMultiplier * DifficultMultiplier * (1 + BoostAmount * 10 + combos / 10)); | |
score += (ulong)S; | |
EO.Score += S; | |
if(PO.Flag != 1 && BoostAmount < 1 && life > 0) BoostAmount += PO.Strengh * TimeMultiplier / DifficultMultiplier / 2500; | |
EO.Strengh -= (float)(PO.Strengh / 50 / TimeMultiplier * DifficultMultiplier); | |
PO.Strengh -= (float)(PO.Strengh / 10 / TimeMultiplier); | |
} | |
if(PO.Strengh <= 0 || !isPointInScreen(PO.Location.X, PO.Location.Y)) PlayerObjects.Remove(PO); | |
} | |
for(int i = EnemyObjects.Count - 1; i >= 0; i--) { | |
GameObjects EO = EnemyObjects[i]; | |
EO.Move(GT.ElapsedGameTime); | |
EO.Rotate += (float)((EO.Rotate > 0 ? 1 : -1) * GT.ElapsedGameTime.TotalMilliseconds / 1000 * EO.Strengh); | |
EO.Speed = (float)(Math.Max(1, (1 - EO.Strengh) * 6) + DifficultMultiplier); | |
if(EO.Location.Y < G.PreferredBackBufferHeight * 1.2) { | |
if(EO.Strengh <= 0 && life > 0) { | |
combos++; | |
if(maxCombos < combos) maxCombos = combos; | |
totalPorks++; | |
if(combos > 1) { | |
FloatTexts.Add(new FloatText(new Vector2(15, G.PreferredBackBufferHeight - 80), combos + " Combos!")); | |
if(maxCombos == combos) FloatTexts.Add(new FloatText(new Vector2(15, G.PreferredBackBufferHeight - 68), "New Record!")); | |
} | |
} | |
} else if(life == 0) FloatTexts.Add(new FloatText(new Vector2(EO.Location.X, G.PreferredBackBufferHeight - 10), "OH!")); | |
else if(life < 0) { | |
life = -1; | |
FloatTexts.Add(new FloatText(new Vector2(EO.Location.X, G.PreferredBackBufferHeight - 10), "GG!")); | |
} else if(life > 0) { | |
life -= EO.Strengh * 10; | |
if(Math.Round(EO.Strengh * 10) > 0) FloatTexts.Add(new FloatText(new Vector2(EO.Location.X, G.PreferredBackBufferHeight - 10), "HP -" + Math.Round(EO.Strengh * 10) + "%")); | |
combos = 0; | |
} | |
if(EO.Strengh <= 0 || !isPointInScreen(EO.Location.X, EO.Location.Y)) { | |
if(life > 0) allPorks++; | |
FizzSound.Play((float)Math.Min(1, Math.Max(0, 1 - EO.Location.Y / (G.PreferredBackBufferHeight * 1.5))), (float)Math.Min(1, Math.Max(0, 0.5 - EO.MaxStrengh / DifficultMultiplier / 2)), (float)(Math.Max(Math.Min(EO.Location.X / G.PreferredBackBufferWidth, 1), 0) * 2 - 1)); | |
if(EO.Strengh <= 0) FloatTexts.Add(new FloatText(EO.Location, "+" + EO.Score)); | |
EnemyObjects.Remove(EO); | |
} | |
} | |
if(BoostAmount > 1) { | |
BoostAmount = 1; | |
score = (ulong)(score * 1.1); | |
if(life > 0) life += (100 - life) / 10; | |
FullChargeSound.Play(); | |
FloatTexts.Add(new FloatText(new Vector2(G.PreferredBackBufferWidth / 2 + 10, G.PreferredBackBufferHeight - 40), "Full Charge Bonus!")); | |
FloatTexts.Add(new FloatText(new Vector2(G.PreferredBackBufferWidth / 2 + 10, G.PreferredBackBufferHeight - 28), "+" + Math.Round((double)(score / 10)))); | |
} | |
for(int i = FloatTexts.Count - 1; i >= 0; i--) { | |
FloatText FT = FloatTexts[i]; | |
FT.Move(GT.ElapsedGameTime); | |
if(FT.Alpha <= 0) FloatTexts.Remove(FT); | |
} | |
if(BoostAmount < 0) BoostAmount = 0; | |
if(life > 0) { | |
RGameTime += GT.ElapsedGameTime; | |
if(RGameTime.TotalMilliseconds >= 500 / 60 / DifficultMultiplier) { | |
bool isComboDown = GetHandAngle(true) < 0; | |
if(isComboDown && BoostAmount > 0) { | |
if(SpaceBarState.SetValue(isComboDown)) BoostSound.Play((float)BoostAmount, (float)(1 - BoostAmount), 0); | |
for(int i = 0; i <= G.PreferredBackBufferWidth; i += 10) { | |
PlayerObjects.Add(new GameObjects(new Vector2((float)(i + Rnd.NextDouble() * 10 - 5), (float)playerLocate.Y), (float)(-Math.PI / 2), (float)(BoostAmount * 2), (float)(10 + DifficultMultiplier / 10), 0, 1)); | |
if(BoostAmount <= 0) break; | |
} | |
BoostAmount -= 0.02 * TimeMultiplier; | |
} else PlayerObjects.Add(new GameObjects(playerLocate, Direction, (float)(1), (float)(10 + DifficultMultiplier / 10), (float)(Direction + Math.PI / 2), 0)); | |
SpaceBarState.SetValue(isComboDown); | |
RGameTime = TimeSpan.Zero; | |
} | |
AddEnermy(TimeMultiplier, DifficultMultiplier); | |
int XMouseOffset = (int)(M.X - playerLocate.X); | |
float pos = getPlayerPosition(); | |
playerLocate.X = pos == -1 ? playerLocate.X : pos * G.PreferredBackBufferWidth; | |
if(playerLocate.X > G.PreferredBackBufferWidth / 5 * 4) playerLocate.X = G.PreferredBackBufferWidth / 5 * 4; | |
if(playerLocate.X < G.PreferredBackBufferWidth / 5) playerLocate.X = G.PreferredBackBufferWidth / 5; int NewRate = (int)Math.Max(100, 150 - life / 2); | |
if(Z.GetRate() != NewRate) Z.SetRate(NewRate); | |
} else if(life < 0) { | |
life = 0; | |
Z.SetRate(100); | |
if(!EscKeyState.Value) { | |
GGSound.Play(); | |
PlayLoop(BGM3Path); | |
} else { | |
PlayLoop(BGM2Path); | |
} | |
} if(GT.ElapsedGameTime.TotalMilliseconds > 0) { | |
HPBarValue += (float)((life - HPBarValue) / GT.ElapsedGameTime.TotalMilliseconds / 4); | |
if(HPBarValue > 100) HPBarValue = 100; | |
else if(HPBarValue < 0) HPBarValue = 0; | |
ChargeBarValue += (float)((BoostAmount - ChargeBarValue) / GT.ElapsedGameTime.TotalMilliseconds / 4); | |
if(ChargeBarValue > 1) ChargeBarValue = 1; | |
else if(ChargeBarValue < 0) ChargeBarValue = 0; | |
} | |
} | |
if(life <= 0) { | |
if(PlayerObjects.Count <= 0) AddEnermy(TimeMultiplier, 1); | |
if(!showDesc) { | |
if(UKeyState.SetValue(K.IsKeyDown(Keys.Up)) && UKeyState.Value) { | |
menuMode = (menuMode + 2) % 3; | |
HoverSound.Play(); | |
} else if(DKeyState.SetValue(K.IsKeyDown(Keys.Down)) && DKeyState.Value) { | |
menuMode = (menuMode + 1) % 3; | |
HoverSound.Play(); | |
} | |
if(MouseHoverState.SetValue(isHOver(new Rectangle(315, 350, 90, 20), M)) && MouseHoverState.Value) { | |
HoverSound.Play(1, 0, (float)M.X / G.PreferredBackBufferWidth * 2 - 1); | |
menuMode = 0; | |
} else if(MouseHoverState2.SetValue(isHOver(new Rectangle(315, 385, 90, 20), M)) && MouseHoverState2.Value) { | |
HoverSound.Play(1, 0, (float)M.X / G.PreferredBackBufferWidth * 2 - 1); | |
menuMode = 1; | |
} else if(MouseHoverState3.SetValue(isHOver(new Rectangle(315, 417, 90, 20), M)) && MouseHoverState3.Value) { | |
HoverSound.Play(1, 0, (float)M.X / G.PreferredBackBufferWidth * 2 - 1); | |
menuMode = 2; | |
} | |
if(this.IsActive) { | |
if(_angle < -0.5 && _angle > -1.5 && _angle != -99) { | |
handUpTime += (float)GT.ElapsedGameTime.TotalMilliseconds / 1000; | |
if (handUpTime > 1) { | |
startGame(); | |
handUpTime = 0; | |
} | |
} else | |
handUpTime = 0; | |
switch(menuMode) { | |
case 1: | |
if(LKeyState.SetValue(K.IsKeyDown(Keys.Left)) && LKeyState.Value && difficulty > 0) { | |
difficulty -= 1; | |
ClickSound.Play(); | |
} else if(RKeyState.SetValue(K.IsKeyDown(Keys.Right)) && RKeyState.Value && difficulty < 2) { | |
difficulty += 1; | |
ClickSound.Play(); | |
} else if((EnterState.SetValue(K.IsKeyDown(Keys.Enter)) && EnterState.Value && !K.IsKeyDown(Keys.LeftAlt)) || isClick(new Rectangle(315, 385, 90, 20), M)) { | |
difficulty = (difficulty + 1) % 3; | |
ClickSound.Play(); | |
} | |
break; | |
case 2: | |
if((EnterState.SetValue(K.IsKeyDown(Keys.Enter)) && EnterState.Value && !K.IsKeyDown(Keys.LeftAlt)) || isClick(new Rectangle(315, 417, 90, 20), M)) { | |
showDesc = true; | |
ClickSound.Play(); | |
} | |
break; | |
} | |
} | |
} else { | |
if(this.IsActive && ((EnterState.SetValue(K.GetPressedKeys().Length > 0) && EnterState.Value) || isClick(new Rectangle(0, 0, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight), M))) { | |
showDesc = false; | |
ClickSound.Play(); | |
} | |
} | |
EnterState.SetValue(K.IsKeyDown(Keys.Enter)); | |
} | |
StatusText = (isPaused ? "Paused..." : "Score: " + score); | |
base.Update(GT); | |
} | |
/// <summary> | |
/// This is called when the game should draw itself. | |
/// </summary> | |
/// <param name="gameTime">Provides a snapshot of timing values.</param> | |
protected override void Draw(GameTime GT) { | |
GraphicsDevice.SetRenderTarget(RT); | |
GraphicsDevice.Clear(Color.Black); | |
SB.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); | |
if(life > 0) { | |
SB.Draw(backTexture, new Rectangle(0, 0, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight), null, Color.White * (float)(0.5 + life / 200), 0, Vector2.Zero, SpriteEffects.None, 0.05F); | |
SB.Draw(backTexture2, new Rectangle(0, G.PreferredBackBufferHeight - 40, G.PreferredBackBufferWidth, 40), null, Color.Black, 0, Vector2.Zero, SpriteEffects.None, 0.9F); | |
} else { | |
SB.Draw(backTexture1, new Rectangle(0, 0, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.05F); | |
if(!showDesc) SB.Draw(menuTexture, new Rectangle(297, 344, 123, 102), new Rectangle(154 * difficulty, 128 * menuMode, 154, 128), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.1F); | |
} | |
foreach(GameObjects EO in EnemyObjects) SB.Draw(EnemyTexture, EO.Location, null, new Color((float)(EO.Strengh + 0.5), (float)(EO.Strengh + 0.5), (float)(EO.Strengh + 0.5)), EO.Rotate, new Vector2(EnemyTexture.Width / 2, EnemyTexture.Height / 2), (Math.Min(4, EO.Strengh) + 1) / 10, SpriteEffects.None, (float)(0.11 + ((double)EnemyObjects.IndexOf(EO) / EnemyObjects.Count) / 10)); | |
foreach(GameObjects PO in PlayerObjects) { | |
float PO_Strengh = PO.Strengh; | |
SB.Draw(PlayerTexture, PO.Location, null, new Color((float)(PO_Strengh - 0.3), 0, 0) * PO_Strengh, PO.Rotate, new Vector2(PlayerTexture.Width / 2, PlayerTexture.Height / 2), (float)((2.5 * PO.Lifetime + 2) / 10), SpriteEffects.None, (float)(0.3 - ((double)PlayerObjects.IndexOf(PO) / PlayerObjects.Count) / 10)); | |
if(PO_Strengh > 0.6) SB.Draw(PlayerTexture, PO.Location, null, Color.Yellow * (float)(PO_Strengh - 0.6), PO.Rotate, new Vector2(PlayerTexture.Width / 2, PlayerTexture.Height / 2), (float)((1.25 * PO.Lifetime + 1) / 10), SpriteEffects.None, (float)(0.4 - ((double)PlayerObjects.IndexOf(PO) / PlayerObjects.Count) / 10)); | |
} | |
foreach(FloatText FT in FloatTexts) SB.DrawString(Font2, FT.T, FT.Locate, Color.White * FT.Alpha, 0, Vector2.Zero, 1, SpriteEffects.None, 0.91F); | |
SB.End(); | |
Texture2D O1 = (Texture2D)RT; | |
if(showDesc || isPaused) { | |
GraphicsDevice.SetRenderTarget(RT_combine); | |
GraphicsDevice.Clear(Color.Black); | |
SB.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); | |
GBlur.Parameters["offsets"].SetValue(HA); | |
GBlur.Parameters["colorMapTexture"].SetValue(O1); | |
GBlur.Parameters["weights"].SetValue(this.K); | |
GBlur.CurrentTechnique.Passes[0].Apply(); | |
SB.Draw(O1, Vector2.Zero, Color.White); | |
SB.End(); | |
O1 = (Texture2D)RT_combine; | |
GraphicsDevice.SetRenderTarget(RT_combine2); | |
GraphicsDevice.Clear(Color.Black); | |
SB.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); | |
GBlur.Parameters["offsets"].SetValue(VA); | |
GBlur.Parameters["colorMapTexture"].SetValue(O1); | |
GBlur.CurrentTechnique.Passes[0].Apply(); | |
SB.Draw(O1, Vector2.Zero, Color.White); | |
SB.End(); | |
O1 = (Texture2D)RT_combine2; | |
} | |
if (RT_BackBuffer != null && KinectColorMap != null && RT_BackBuffer2 != null && KinectColorMap2 != null) { | |
GraphicsDevice.SetRenderTarget(RT_BackBuffer2); | |
GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 0, 0); | |
SB.Begin(SpriteSortMode.Immediate, null, null, null, null, KinectEffect2); | |
SB.Draw(KinectColorMap2, Vector2.Zero, Color.White); | |
SB.End(); | |
GraphicsDevice.SetRenderTarget(RT_BackBuffer); | |
GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); | |
SB.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, KinectEffect); | |
KinectEffect.CurrentTechnique.Passes[0].Apply(); | |
SB.Draw(KinectColorMap, Vector2.Zero, Color.White); | |
SB.End(); | |
GraphicsDevice.SetRenderTarget(RT_BackBuffer3); | |
GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0, 0); | |
SB.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, KinectEffect); | |
KinectEffect.Parameters["offsets"].SetValue(HA); | |
KinectEffect.Parameters["colorMapTexture"].SetValue(RT_BackBuffer); | |
KinectEffect.Parameters["weights"].SetValue(this.K); | |
KinectEffect.CurrentTechnique.Passes[1].Apply(); | |
SB.Draw(RT_BackBuffer, Vector2.Zero, Color.White); | |
SB.End(); | |
} | |
GraphicsDevice.SetRenderTarget(null); | |
GraphicsDevice.Clear(Color.Black); | |
SB.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); | |
SB.Draw(O1, new Rectangle(0, 0, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.0F); | |
Vector2 P = Font1.MeasureString("x" + totalPorks); | |
if(life <= 0) { | |
if(showDesc) { | |
SB.Draw(titleTexture, new Rectangle(0, 0, G.PreferredBackBufferWidth, G.PreferredBackBufferHeight), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.9F); | |
} else { | |
SB.DrawString(Font2, "Max Combos: " + maxCombos, new Vector2(P.X + 50, G.PreferredBackBufferHeight - 72), Color.Gold, 0, Vector2.Zero, 1, SpriteEffects.None, 0.95F); | |
SB.DrawString(Font1, StatusText, new Vector2(G.PreferredBackBufferWidth - 80 - Font1.MeasureString(StatusText).X, G.PreferredBackBufferHeight - 26), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0.99F); | |
} | |
} else { | |
SB.Draw(HPBarTexture, new Rectangle(10, (int)(G.PreferredBackBufferHeight - 20), (int)(HPBarValue / 200 * (G.PreferredBackBufferWidth - 20) - 10), 10), null, new Color((float)(Math.Max(Math.Min(1 - life / 100, 0.5), 0) * 2), (float)(Math.Max(Math.Min(life / 100, 0.5), 0) * 2), 0), 0, Vector2.Zero, SpriteEffects.None, 0.99F); | |
SB.Draw(HPBarTexture, new Rectangle((int)(G.PreferredBackBufferWidth - ChargeBarValue / 2 * (G.PreferredBackBufferWidth - 20) - 10), G.PreferredBackBufferHeight - 20, (int)(ChargeBarValue / 2 * (G.PreferredBackBufferWidth - 20)), 10), null, (BoostAmount >= 1 ? Color.White : Color.Violet), 0, Vector2.Zero, SpriteEffects.None, 0.99F); | |
SB.DrawString(Font1, Math.Ceiling(life) + "%", new Vector2(10, G.PreferredBackBufferHeight - 46), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1); | |
SB.DrawString(Font1, StatusText, new Vector2(G.PreferredBackBufferWidth - 10 - Font1.MeasureString(StatusText).X, G.PreferredBackBufferHeight - 46), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0.991F); | |
} | |
if(!showDesc) { | |
SB.Draw(EnemyTexture, new Rectangle(10, G.PreferredBackBufferHeight - 72, 32, 32), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.99F); | |
SB.DrawString(Font1, "x" + totalPorks, new Vector2(44, G.PreferredBackBufferHeight - 72), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0.991F); | |
if(allPorks > 0 && totalPorks != allPorks) SB.DrawString(Font2, Math.Round((1 - (double)totalPorks / (double)allPorks) * 100).ToString() + "% LOSS", new Vector2(P.X + 50, G.PreferredBackBufferHeight - 60), Color.Red, 0, Vector2.Zero, 1, SpriteEffects.None, 0.991F); | |
} | |
if(RT_BackBuffer2 != null) | |
SB.Draw(RT_BackBuffer2, new Rectangle(G.PreferredBackBufferWidth / 4 * 3 - 10, G.PreferredBackBufferHeight / 4 * 3 - 10, G.PreferredBackBufferWidth / 4, G.PreferredBackBufferHeight / 4), null, new Color(1, 1, 1, 0.5F), 0, Vector2.Zero, SpriteEffects.None, 0.98F); | |
if(RT_BackBuffer3 != null) | |
SB.Draw(RT_BackBuffer3, new Rectangle(G.PreferredBackBufferWidth / 4 * 3 - 10, G.PreferredBackBufferHeight / 4 * 3 - 10, G.PreferredBackBufferWidth / 4, G.PreferredBackBufferHeight / 4), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0.981F); | |
if(GT.ElapsedGameTime > TimeSpan.Zero) SB.DrawString(Font2, Math.Round(1000 / GT.ElapsedGameTime.TotalMilliseconds) + " FPS", new Vector2(4, 0), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0.991F); | |
MouseState M = Mouse.GetState(); | |
if(life <= 0) | |
SB.Draw(CursorTexture, new Rectangle(M.X + 20, M.Y + 23, 48, 48), null, Color.White, (M.LeftButton == ButtonState.Pressed ? -0.2F : M.RightButton == ButtonState.Pressed ? 0.2F : 0), new Vector2(256, 256), SpriteEffects.None, 1); | |
SB.End(); | |
base.Draw(GT); | |
} | |
private void AddEnermy(double TimeMultiplier, double DifficultMultiplier) { | |
if(Rnd.NextDouble() <= nextFire / 10000 / Math.Max(1, EnemyObjects.Count / DifficultMultiplier)) { | |
Double R = Rnd.NextDouble(); | |
if(R > 0.4) EnemyObjects.Add(new GameObjects(new Vector2((float)(Rnd.NextDouble() * G.PreferredBackBufferWidth), (float)(-G.PreferredBackBufferHeight / 20)), (float)((80 + Rnd.NextDouble() * 20) / 180 * Math.PI), (float)(Rnd.NextDouble() * DifficultMultiplier), 1, (float)(Rnd.NextDouble() * Math.PI * 4 - 2), 0)); | |
else if(R > 0.2) EnemyObjects.Add(new GameObjects(new Vector2(-10, (float)(Rnd.NextDouble() * G.PreferredBackBufferHeight / 4)), (float)((60 + Rnd.NextDouble() * 20) / 180 * Math.PI), (float)(Rnd.NextDouble() * DifficultMultiplier), 1, (float)(Rnd.NextDouble() * Math.PI * 4 - 2), 0)); | |
else EnemyObjects.Add(new GameObjects(new Vector2((float)(G.PreferredBackBufferWidth + 10), (float)(Rnd.NextDouble() * G.PreferredBackBufferHeight / 4)), (float)((110 + Rnd.NextDouble() * 20) / 180 * Math.PI), (float)(Rnd.NextDouble() * DifficultMultiplier), 1, (float)(Rnd.NextDouble() * Math.PI * 4 - 2), 0)); | |
nextFire = 0; | |
} else nextFire += TimeMultiplier; | |
} | |
private bool isPointInScreen(float X, float Y) { | |
if(X < -G.PreferredBackBufferWidth / 10) return false; | |
if(Y < -G.PreferredBackBufferHeight / 10) return false; | |
if(X > G.PreferredBackBufferWidth * 1.1) return false; | |
if(Y > G.PreferredBackBufferHeight * 1.2) return false; | |
return true; | |
} | |
private bool isClick(Rectangle Region, MouseState M) { | |
return MouseState.SetValue(M.LeftButton == ButtonState.Pressed) && MouseState.Value && isHOver(Region, M); | |
} | |
private bool isHOver(Rectangle Region, MouseState M) { | |
return M.X > Region.Left && M.X < Region.Right && M.Y > Region.Top && M.Y < Region.Bottom; | |
} | |
private void startGame() { | |
ClickSound.Play(); | |
playerLocate = new Vector2(G.PreferredBackBufferWidth / 2, G.PreferredBackBufferHeight); | |
PlayLoop(BGM1Path); | |
RGameTime = TimeSpan.Zero; | |
score = 0; | |
nextFire = 0; | |
life = 100; | |
BoostAmount = 0; | |
totalPorks = 0; | |
combos = 0; | |
maxCombos = 0; | |
allPorks = 0; | |
Rnd = new Random(); | |
PlayerObjects.Clear(); | |
EnemyObjects.Clear(); | |
} | |
#region Kinect(tm) Functions | |
private void KinectStatusChanged(object s, StatusChangedEventArgs e) { | |
if(e.Status != KinectStatus.Connected) | |
e.Sensor.Stop(); | |
KStatus = e.Status; | |
} | |
private void DiscoverSeneor() { | |
Sensor = KinectSensor.KinectSensors.FirstOrDefault(); | |
if(Sensor != null) { | |
KStatus = Sensor.Status; | |
if(KStatus == KinectStatus.Connected){ | |
try { | |
Sensor.SkeletonStream.Enable(); | |
Sensor.ColorStream.Enable(); | |
Sensor.DepthStream.Enable(); | |
Sensor.Start(); | |
} catch (IOException) { | |
Sensor = null; | |
} catch (InvalidOperationException) { | |
Sensor = null; | |
} | |
} | |
} else { | |
KStatus = KinectStatus.Disconnected; | |
} | |
switch (KStatus) { | |
case KinectStatus.DeviceNotGenuine: | |
throw new InvalidOperationException("您正在使用非正式的 Kinect。"); | |
case KinectStatus.DeviceNotSupported: | |
throw new InvalidOperationException("您正在使用的裝置不被支援。"); | |
case KinectStatus.Error: | |
throw new InvalidOperationException("發生不知名錯誤了。"); | |
case KinectStatus.InsufficientBandwidth: | |
throw new InvalidOperationException("USB 不給力,無法使用 Kinect。"); | |
case KinectStatus.NotPowered: | |
throw new InvalidOperationException("看來您忘了把 Kinect 連接電源。"); | |
case KinectStatus.NotReady: | |
throw new InvalidOperationException("看來您的 Kinect 被其他程式搶了來使用。"); | |
case KinectStatus.Disconnected: | |
throw new InvalidOperationException("看來您忘了把 Kinect 連接。"); | |
} | |
} | |
private Vector2 SkeletonToColorMap(SkeletonPoint point) { | |
if(null != Sensor && null != Sensor.DepthStream) { | |
DepthImagePoint colorPt = Sensor.CoordinateMapper.MapSkeletonPointToDepthPoint(point, Sensor.DepthStream.Format); | |
return new Vector2(colorPt.X, colorPt.Y); | |
} | |
return Vector2.Zero; | |
} | |
private float GetHandAngle(bool lefthand) { | |
JointCollection Joints = getActiveJoints(); | |
if(Joints == null) | |
return -99; | |
Vector2 P1 = SkeletonToColorMap(Joints[lefthand ? JointType.ShoulderLeft : JointType.ShoulderRight].Position); | |
Vector2 P2 = SkeletonToColorMap(Joints[lefthand ? JointType.HandLeft : JointType.HandRight].Position); | |
Vector2 D = P2 - P1; | |
float angle = (float)Math.Atan2(D.Y, D.X); | |
return angle; | |
} | |
private float getPlayerPosition() { | |
JointCollection Joints = getActiveJoints(); | |
if(Joints == null) | |
return -1; | |
return SkeletonToColorMap(Joints[JointType.ShoulderRight].Position).X / Sensor.DepthStream.FrameWidth; | |
} | |
private JointCollection getActiveJoints() { | |
if(skeletons == null || skeletons.Length <= 0) | |
return null; | |
trkID = TrackClosestSkeleton(); | |
if(trkID != -1) | |
foreach(Skeleton S in skeletons) | |
if(S.TrackingId == trkID) { | |
if(S.TrackingState == SkeletonTrackingState.NotTracked) { | |
trkID = -1; | |
break; | |
} else | |
return S.Joints; | |
} | |
return null; | |
} | |
private int TrackClosestSkeleton() { | |
if (Sensor != null && Sensor.SkeletonStream != null) { | |
if (!Sensor.SkeletonStream.AppChoosesSkeletons) | |
Sensor.SkeletonStream.AppChoosesSkeletons = true; | |
float closestDistance = 10000f; // Start with a far enough distance | |
int closestID = 0; | |
foreach (Skeleton skeleton in skeletons.Where(s => s.TrackingState != SkeletonTrackingState.NotTracked)) | |
if (skeleton.Position.Z < closestDistance) { | |
closestID = skeleton.TrackingId; | |
closestDistance = skeleton.Position.Z; | |
} | |
if (closestID > 0) | |
Sensor.SkeletonStream.ChooseSkeletons(closestID); | |
return closestID; | |
} | |
return -1; | |
} | |
private void updateSkeleton() { | |
if(Sensor == null) | |
return; | |
using(SkeletonFrame SF = Sensor.SkeletonStream.OpenNextFrame(0)) { | |
if(SF == null) | |
return; | |
if(skeletons == null || skeletons.Length != SF.SkeletonArrayLength) | |
skeletons = new Skeleton[SF.SkeletonArrayLength]; | |
SF.CopySkeletonDataTo(skeletons); | |
} | |
} | |
private void updateKinectImage() { | |
if(Sensor == null) | |
return; | |
using (DepthImageFrame DF = Sensor.DepthStream.OpenNextFrame(0)) { | |
if (DF != null) { | |
if (KinectColorData == null || KinectColorData.Length != DF.PixelDataLength) { | |
KinectColorData = new short[DF.PixelDataLength]; | |
KinectColorMap = new Texture2D(GraphicsDevice, DF.Width, DF.Height, false, SurfaceFormat.Bgra4444); | |
RT_BackBuffer = new RenderTarget2D(GraphicsDevice, DF.Width, DF.Height, false, SurfaceFormat.Color, DepthFormat.None, GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.PreserveContents); | |
RT_BackBuffer3 = new RenderTarget2D(GraphicsDevice, DF.Width, DF.Height, false, SurfaceFormat.Color, DepthFormat.None, GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.PreserveContents); | |
} | |
DF.CopyPixelDataTo(KinectColorData); | |
KinectColorMap.SetData<short>(KinectColorData); | |
} | |
} | |
using (ColorImageFrame CF = Sensor.ColorStream.OpenNextFrame(0)) { | |
if (CF == null) | |
return; | |
if (KinectColorData2 == null || KinectColorData2.Length != CF.PixelDataLength) { | |
KinectColorData2 = new byte[CF.PixelDataLength]; | |
KinectColorMap2 = new Texture2D(GraphicsDevice, CF.Width, CF.Height, false, SurfaceFormat.Color); | |
RT_BackBuffer2 = new RenderTarget2D(GraphicsDevice, CF.Width, CF.Height, false, SurfaceFormat.Color, DepthFormat.None, GraphicsDevice.PresentationParameters.MultiSampleCount, RenderTargetUsage.PreserveContents); | |
} | |
CF.CopyPixelDataTo(KinectColorData2); | |
KinectColorMap2.SetData<byte>(KinectColorData2); | |
} | |
} | |
#endregion | |
#region Functions for Background Music | |
private void PlayLoop(string FileName) { | |
TStreamInfo TSNFO = new TStreamInfo(); | |
TStreamTime ZeroTime = new TStreamTime(); | |
TStreamTime T2 = new TStreamTime(); | |
byte[] FileContent = C.LoadBytes(FileName); | |
ZeroTime.ms = 0; | |
ZeroTime.sec = 0; | |
ZeroTime.samples = 0; | |
ZeroTime.hms.hour = 0; | |
ZeroTime.hms.minute = 0; | |
ZeroTime.hms.second = 0; | |
ZeroTime.hms.millisecond = 0; | |
T2.sec = 1; | |
Z.StopPlayback(); | |
Z.OpenStream(true, false, ref FileContent, (uint)FileContent.Length, TStreamFormat.sfOgg); | |
Z.GetStreamInfo(ref TSNFO); | |
TSNFO.Length.ms -= (uint)Z.GetSettings(TSettingID.sidWaveBufferSize); | |
Z.SetPlayerVolume(0, 0); | |
Z.PlayLoop(TTimeFormat.tfMillisecond, ref ZeroTime, TTimeFormat.tfMillisecond, ref TSNFO.Length, uint.MaxValue, true); | |
Z.SlideVolume(TTimeFormat.tfSecond, ref ZeroTime, 0, 0, TTimeFormat.tfSecond, ref T2, 100, 100); | |
} | |
private void fadeOut() { | |
TStreamTime T1 = new TStreamTime(); | |
TStreamTime T2 = new TStreamTime(); | |
T1.sec = 0; | |
T2.ms = 250; | |
Z.SlideVolume(TTimeFormat.tfSecond, ref T1, 100, 100, TTimeFormat.tfMillisecond, ref T2, 0, 0); | |
} | |
#endregion | |
#region Functions for Shaders | |
public float[] ComputeKernel(int blurRadius, float blurAmount) { | |
int radius = blurRadius; | |
float amount = blurAmount; | |
float[] kernel = new float[radius * 2 + 1]; | |
float sigma = radius / amount; | |
float twoSigmaSquare = 2.0f * sigma * sigma; | |
float sigmaRoot = (float)Math.Sqrt(twoSigmaSquare * Math.PI); | |
float total = 0.0f; | |
float distance = 0.0f; | |
int index = 0; | |
for(int i = -radius; i <= radius; ++i) { | |
distance = i * i; | |
index = i + radius; | |
kernel[index] = (float)Math.Exp(-distance / twoSigmaSquare) / sigmaRoot; | |
total += kernel[index]; | |
} | |
for(int i = 0; i < kernel.Length; ++i) kernel[i] /= total; | |
return kernel; | |
} | |
public Vector2[] ComputeOffsets(float textureWidth, int radius, bool isVertical) { | |
Vector2[] offs = new Vector2[radius * 2 + 1]; | |
int index = 0; | |
float xOffset = 1.0f / textureWidth; | |
for(int i = -radius; i <= radius; ++i) { | |
index = i + radius; | |
offs[index] = isVertical ? new Vector2(0.0f, i * xOffset) : new Vector2(i * xOffset, 0.0f); | |
} | |
return offs; | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment