Contact

 
Google
Web www.alanphipps.com

 
   
 
   
www.alanphipps.com

.: Adding Microsoft.XNA.Framework.Game

 
 

In the last tutorial, I said that I would work on how to implement the content pipeline, which would then be explained in this tutorial, however, after much research, I decided that this tutorial would be on how to add the Microsoft.XNA.Framework.Game component. You see, the content pipeline is normally implemented using the Game component and hence some creative code is required to use it without Game. So, although it is possible to use the pipeline without it, we are going to implement the Game component first, doing so will give us the use of a lot of other stuff and it means we don't have to write creative code every time we ant to use a component that needs game.

So, source code, last tutorial, and we will begin. First I will explain the problem:

In order that our game uses the Game component, we would normally add the line, Inherits Game, under the class declaration, however, because we have used a windows form we get an error saying that Game and System.Windows.Forms.Form are incompatible, this means that our game cannot inherit Game the way it is, so what do we do?. Basically we have to get rid of our windows form, and here's how we do that.

 

 

First, start a new VB.NET project and call it XNAGame. Next delete the form, usually called Form1. Next, add the XNA references as shown here. Next, add a new Class called XNAGame and add the following code:

Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework.Input

'All game components will be held inside the XNA NameSpace
Namespace XNA
'The main game component will be called XNA GAme
Public Class XNAGame
'Which includes the Microsoft.Xna.Framework.game Template
Inherits Game

'Objects and Variables
Private XNAGraphics As GraphicsDeviceManager

' When an instance of the XNAGame class is created using the New keyword, this Sub runs.
Public Sub New()
XNAGraphics = New GraphicsDeviceManager(Me)
End Sub

'Initializes the XNAGame class instance, runs once when game starts
Protected Overrides Sub Initialize()
MyBase.Initialize()
End Sub

'Updates all game components, runs before every Draw Loop
Protected Overrides Sub Update(ByVal gameTime As GameTime)
Dim GetKeys As KeyboardState = Keyboard.GetState

If GetKeys.IsKeyDown(Keys.Escape) Then
MyBase.Exit()
End If

'Edit Game Window Title
Me.Window.Title = "XNAGame"

'Add you Update Code Here

MyBase.Update(gameTime)
Application.DoEvents()
End Sub

'Renders any Backbuffer draw data to the screen
Protected Overrides Sub Draw(ByVal gameTime As GameTime)
XNAGraphics.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1.0F, 0)

'Add you Draw Code here

MyBase.Draw(gameTime)
End Sub

End Class

Module modMain
'An instance of the XNAGame Class
Public Game1 As XNAGame

'The starting point of the game is Main() because it is not a windows form
Public Sub Main(ByVal args As String())
Game1 = New XNAGame
Game1.Run()
End Sub

End Module

End Namespace

Lastly, open the project properties, go to Application and uncheck the "Enable Application framework" checkbox, and change the startup Object to Sub Main. This is the process required to create a new blank XNA project. I will explain the differences at the end of the tutorial, but first I will explain how to convert our game to the new standard.

First, copy the Audio and Images folders from the last tutorial folder to the new tutorial folder, you don't have to add them to the project just make sure that they are in the XNAGame folder. Next, copy the following vb code files from the last tutorial folder to the new one, Ball.vb, FontModule.vb, Framerate.vb, GraphicsModule.vb, Particle.vb, Sound.vb, remember that when you add sound, you will have to add the Microsoft.DirectX.AudioVideoPlayback reference in your project properties, your new project folder should now look like this:

XNA in VB.NET - New Project Folder

Now, from VB.NET Express add the new vb files to your project. Once they have been added, open them and add the following line of code above the class or module declaration:

Namespace XNA

Also add End NameSpace at the bottom of the page. This will include all the new files into the project namespace. There are very few changes to the old files, most changes occur within the XNAGame Class:

I wont explain every change that has been made, but I will explain the main one. Basically, now that our XNAGame class inherits the XNA GAme component, our project will use Game's methods instead of our own, example:

Render has become Draw,

OnPaint and Form1_KeyDown has become Update,

Form1_Closing has become XNAGame_Exiting,

InitializeGraphics has become New and

Form1_Load becomes Initialize.

As you will see most of these Subs are declared as Protected Overrides, this means, for example that there is a Draw Sub in the Game component and we want to use it but to change its contents by adding our own code, hence overriding the original sub.

So basically its now a matter of taking the code from the old project and adding it to the correct places in the new project, as shown below:


Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework.Input
Imports System.IO

'All game components will be held inside the XNA NameSpace
Namespace XNA
'The main game component will be called XNA GAme
Public Class XNAGame
'Which includes the Microsoft.Xna.Framework.game Template
Inherits Game

'Objects and variables
Private MakeWriteTextOnlyRunOnTheFirstRenderLoop As Integer = 0 'Used to make sure that the WriteText Sub runs once during Game load - Render Loop
Private MakeLoadLevelOnlyRunOnTheFirstRenderLoop As Integer = 0 ' USed to make sure that LoadLevel only runs once per loop

' When an instance of the XNAGame class is created using the New keyword, this Sub runs.
Public Sub New()
XNAGraphics = New GraphicsDeviceManager(Me)
End Sub

'Initializes the XNAGame class innstance, runs once when game starts
Protected Overrides Sub Initialize()
DefineObjectDetails()
Sound.InitializeEngine()

'Setup the Text bitmaps that are static and wont chnage during the game
WriteText("Loading", "Mirror", 26, FontStyle.Bold, Brushes.Black, _
320, 300, LoadingTexture, LoadingVector)

'Get High Score from High Score File
If My.Computer.FileSystem.FileExists(Application.StartupPath & "\HighScore.txt") = True Then
Try
Using sr As StreamReader = New StreamReader(Application.StartupPath & "\HighScore.txt")
Dim x As String = sr.ReadToEnd
sr.Close()
If IsNumeric(x) = True Then
HighScore = CInt(x)
End If
End Using
Catch ex As Exception

End Try
End If

'Play Background Music
SelectMusic()

MyBase.Initialize()
End Sub

'Updates all game components, runs before every Draw Loop
Protected Overrides Sub Update(ByVal gameTime As GameTime)
Dim GetKeys As KeyboardState = Keyboard.GetState

If GetKeys.IsKeyDown(Keys.Escape) Then
MyBase.Exit()
ElseIf GetKeys.IsKeyDown(Keys.Right) Then
If GameState = "Playing" Then ' If a game is in progress
If ArrowSBRotate >= MathHelper.ToRadians(85) Then
ArrowSBRotate = MathHelper.ToRadians(85)
Exit Sub
End If
ArrowSBRotate = ArrowSBRotate + MathHelper.ToRadians(1)
End If
ElseIf GetKeys.IsKeyDown(Keys.Left) Then
If GameState = "Playing" Then ' If a game is in progress
If ArrowSBRotate <= MathHelper.ToRadians(-85) Then
ArrowSBRotate = MathHelper.ToRadians(-85)
Exit Sub
End If
ArrowSBRotate = ArrowSBRotate - MathHelper.ToRadians(1)
End If
ElseIf GetKeys.IsKeyDown(Keys.Enter) Then
If DirectXAudio.Playing = True Then
DirectXAudio.Pause()
ElseIf DirectXAudio.Paused = True Then
DirectXAudio.Play()
End If
ElseIf GetKeys.IsKeyDown(Keys.Space) Then

If GameState = "WaitingToStart" Then ' Game has not started yet
CurrentScore = 0 'Reset Current Score
GameStopWatch.Reset() 'Reset the Stopwatch
GameStopWatch.Start() ' Start the stopwatch
PlayAreaRect.Y = 62
PlayAreaRect.Height = 456
PlayAreaRect.Width = 380
PlayAreaTex = Texture2D.FromFile(XNAGraphics.GraphicsDevice, "../../images/380x480AlphaChannelOnly.png", NonBallTexCreationParams)
GameState = "Loading" 'Load a Level

ElseIf GameState = "Playing" Then ' If a game is in progress

If ABallHasBeenLaunched = False Then ' If a ball is not already moving
If ABallNeedsPositionedCorrectly = False Then
For Each SingleBall As Ball In BallsArray ' Check every ball in the array
If SingleBall.IsDeleted = False Then
If SingleBall.BallRect = BallLauncherRect7 Then ' If ball is in the launch position
If SingleBall.IsMoving = False Then
GetBallVectorFromArrow() ' Get direction of arrow
End If
BallLauncherRect7IsEmpty = True
ANewBallIsNeeded = True
SingleBall.IsMoving = True
SingleBall.IsInLauncher = False
ABallHasBeenLaunched = True
Exit For ' because only one ball will be in the launch position we can safely exit the
'for loop after we have found it

End If
End If
Next
End If
End If
End If
ElseIf GetKeys.IsKeyDown(Keys.P) Then
If GameState = "Playing" Then ' If a game is in progress
GameState = "Paused"
'Check if Audio is playing
If DirectXAudio.Playing = True Then
DirectXAudio.Pause()
End If
GameStopWatch.Reset()
GameStopWatch.Start()
ElseIf GameState = "Paused" Then ' If a game is in Paused
GameState = "Playing"
'Check if Audio is playing
If DirectXAudio.Paused = True Then
DirectXAudio.Play()
End If
GameStopWatch.Reset()
GameStopWatch.Start()
End If
End If

'Diaplay framerate on window title bar
Me.Window.Title = "XNA Space Ballz - Level " & CurrentLevel

MyBase.Update(gameTime)
Application.DoEvents()
End Sub

'Renders any Backbuffer draw data to the screen
Protected Overrides Sub Draw(ByVal gameTime As GameTime)

If XNAGraphics.GraphicsDevice.GraphicsDeviceStatus = GraphicsDeviceStatus.Normal Then
XNAGraphics.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1.0F, 0)

'Draw all Non Ball Textures
MainSB.Begin(SpriteBlendMode.AlphaBlend)
Select Case GameState

'--------------------------------------------------------------------------------
' GameState Change
'--------------------------------------------------------------------------------

Case Is = "WaitingToStart"

MainSB.Draw(BackgroundTex, BackgroundRect, Color.White)
MainSB.Draw(PlayAreaTex, PlayAreaRect, Color.White)

If CurrentScore > TempScore Or MakeWriteTextOnlyRunOnTheFirstRenderLoop = 0 Then
MakeWriteTextOnlyRunOnTheFirstRenderLoop += 1
WriteText("High Score" & vbCrLf & HighScore, "Mirror", 16, FontStyle.Bold, Brushes.Silver, _
630, PlayAreaRect.Y - 8, ScoreTexture, ScoreVector)
End If

MainSB.Draw(ScoreTexture, ScoreVector, Color.White)

'--------------------------------------------------------------------------------
' GameState Change
'--------------------------------------------------------------------------------

Case Is = "Loading"

If MakeLoadLevelOnlyRunOnTheFirstRenderLoop = 0 Then
'Delete all balls and particles
For Each TempBall As Ball In BallsArray
TempBall.IsDeleted = True
Next
RedimBallArray()
For Each Part As Particle In ParticlesArray
Part.IsDeleted = True
Next
CheckParticlesArray()
SelectTheme() ' Choose Theme Textures

SetBallLauncherBalls()
CheckParticlesArray()
IndexOfMovingBall = 0 'Reset Variable
ArrowSBRotate = 0 'Point arraow straight up
PlayAreaRect.Y = 60
RoofRect.Y = PlayAreaRect.Y - 480
DefineColoursArrayList() 'Redefine ColorsArrayList so that all colours of ball are included in the game
LoadLevel() ' Load a random level
CurrentLevel += 1 ' Increment Level Number
MakeLoadLevelOnlyRunOnTheFirstRenderLoop += 1
End If

'Draw PlayAreaRect Background
MainSB.Draw(ThemeTex, ThemeRect, Color.White)
'Draw PlayAreaRect
MainSB.Draw(PlayAreaTex, PlayAreaRect, Color.White)
'Draw Ball
If UBound(BallsArray) > 0 Then
For Each SingleBall As Ball In BallsArray ' Check every ball in array
If SingleBall.IsDeleted = False Then
MainSB.Draw(SingleBall.BallTex, SingleBall.BallRect, Color.White) 'Draw Each Ball
End If
Next
End If

MainSB.Draw(BallLauncherTex, BallLauncherRect, Color.White)
MainSB.Draw(BackgroundTex, BackgroundRect, Color.White)

'Draw Arrow - Arrow is drawn after ball so that it appears on top of ball.
'Anything drawn last will appear above anything drawn before

MainSB.Draw(ArrowTex, New Vector2(405, 485), Nothing, Color.White, ArrowSBRotate, _
New Vector2((ArrowTex.Width / 2), (ArrowTex.Height / 2)), 1.0F, SpriteEffects.None, 0.0F)

If CurrentScore <> TempScore Or MakeWriteTextOnlyRunOnTheFirstRenderLoop < 2 Then
MakeWriteTextOnlyRunOnTheFirstRenderLoop += 1
WriteText("High Score" & vbCrLf & HighScore & vbCrLf & vbCrLf & _
"Score" & vbCrLf & CurrentScore, "Mirror", 16, FontStyle.Bold, Brushes.Silver, _
630, PlayAreaRect.Y - 8, ScoreTexture, ScoreVector)
End If
'TempScore = CurrentScore 'hold score in a temporary variable to see if it changes on next loop

'Write Score on Screen
MainSB.Draw(ScoreTexture, ScoreVector, Color.White)

'Draw the loading Text
If GameStopWatch.ElapsedMilliseconds < 1000 Then
MainSB.Draw(LoadingTexture, LoadingVector, Color.White)
End If

'Set the Countdown Text
Select Case GameStopWatch.ElapsedMilliseconds
Case 1000 To 1999
MainSB.Draw(Number3Tex, CountDownRect, Color.White)
Case 2000 To 2999
MainSB.Draw(Number2Tex, CountDownRect, Color.White)
Case 3000 To 3999
MainSB.Draw(Number1Tex, CountDownRect, Color.White)
Case 4000 To 4999
MainSB.Draw(LetsGoTex, LetsGoRect, Color.White)
Case Is > 5000
GameState = "Playing" 'Change GameState to Playing
MakeLoadLevelOnlyRunOnTheFirstRenderLoop = 0
GameStopWatch.Reset()
GameStopWatch.Start()
End Select

'--------------------------------------------------------------------------------
' GameState Change
'--------------------------------------------------------------------------------

Case Is = "Playing"

'If the number of balls = 7 then all balls have exploded or dropped and the game is won
Dim x As Integer = 0
For m As Integer = 0 To UBound(BallsArray) ' Search array for the ball that is moving
If ABallHasBeenLaunched = True Then ' A global variable used to tell the program when to start checking for
If UBound(BallsArray) > 1 Then ' collisions
If IndexOfMovingBallFound = False Then ' If the moving ball is unknown
If BallsArray(m).IsMoving = True Then ' When the moving ball is found
IndexOfMovingBall = m ' store the ball index in a variable and exit the for loop
IndexOfMovingBallFound = True
End If
End If
End If
End If
'Test for Game Won
If BallsArray(m).IsDeleted = False Then
If BallsArray(m).IsDropped = False Then
If BallsArray(m).IsInLauncher = False Then
x += 1
End If
End If
End If
'Check for GameLost - If a ball goes lower than BallLauncherRect7.Y
If UBound(BallsArray) > 7 Then
If BallsArray(m).IsDeleted = False Then
If BallsArray(m).IsDropped = False Then
If BallsArray(m).IsInLauncher = False Then
If BallsArray(m).IsMoving = False Then
If BallsArray(m).MarkedForDeletionDrop = False Then
If BallsArray(m).MarkedForDeletionExplode = False Then
If BallsArray(m).BallRect.Y > 430 Then
GameStopWatch.Reset()
GameStopWatch.Start()
GameState = "GameLost"
End If
End If
End If
End If
End If
End If
End If
End If
Next

'If There are no balls in play then Set GameWon
If x <= 0 Then
GameStopWatch.Reset()
GameStopWatch.Start()
GameState = "GameWon"
End If
x = Nothing

'Draw PlayAreaRect Background
MainSB.Draw(ThemeTex, ThemeRect, Color.White)
'Draw PlayAreaRect
MainSB.Draw(PlayAreaTex, PlayAreaRect, Color.White)

'Draw Ball
If UBound(BallsArray) > 0 Then
For Each SingleBall As Ball In BallsArray ' Check every ball in array
If SingleBall.IsDeleted = False Then
MainSB.Draw(SingleBall.BallTex, SingleBall.BallRect, Color.White) 'Draw Each Ball
End If
If SingleBall.IsMoving = True Then 'If a ball is set to move
SingleBall.MoveBall() 'Move the ball
End If
If BallLauncherRect7IsEmpty = True Then ' BallLauncherRect7IsEmpty is Set to True when a ball is launched
SingleBall.MoveBallLauncherBalls() ' Move the balls in the ball launcher
End If
If SingleBall.MarkedForDeletionDrop = True Then 'If a Ball is to be dropped
SingleBall.IsDropped = True 'Variable to exclude ball fromm Collison
SingleBall.BallRect.Y += SingleBall.BallXVel 'Move the ball down at speed BallXVel
SingleBall.BallXVel += 0.5 'increase BallXVel to give appearance of gravity
'Award points if PointsAwarded = False
If SingleBall.PointsAwarded = False Then
CurrentScore += 200
SingleBall.PointsAwarded = True
End If
'If it moves below the playarea then delete it
If SingleBall.BallRect.Y > PlayAreaRect.Bottom Then
SingleBall.IsDeleted = True
End If
End If
If ABallHasBeenLaunched = True Then ' A global variable used to tell the program when to start checking for
'Check for a collision
CheckForCollision(SingleBall)
End If
Next

'If a Ball needs to be positioned correctly
If ABallNeedsPositionedCorrectly = True Then
If UBound(BallsArray) > 1 Then
'Correctly Position Ball
PositionBallCorrectly() ' no For Loop
End If
End If

'Check for 3 touching Balls
If ShouldWeCheckFor3TouchingBalls = True Then
If CheckFor3TouchingBalls() = True Then
FindTheBallsToRemove()
End If
End If

'If BallsNeedRemoved = True then Run the RemoveBalls Sub
If BallsNeedRemoved = True Then
RedimBallArray() ' Remove those Balls that have IsDeleted = True from the Array
FindBallsToDrop() ' Find which Balls should fall out the game, as they are no longer connected to the top of the playarea
End If

'Animate Particles if there are any
If UBound(ParticlesArray) > 0 Then
For Each TempPart As Particle In ParticlesArray
MainSB.Draw(TempPart.ParticleTex, TempPart.ParticleRect, Color.White) 'Draw Each Particle
MoveParticle(TempPart) 'Move each particle
Next
End If

'Remove any Deleted Particles
If TheParticelArrayNeedsRedimmed = True AndAlso UBound(ParticlesArray) > 10 Then
CheckParticlesArray()
End If

End If

'Check for all the balls of a particlular colour being removed
If UBound(BallsArray) < 20 Then
RemoveAColourFromColoursArrayList()
End If

'Draw Roof and other Textures
MainSB.Draw(RoofTex, RoofRect, Color.White)

'lower roof and playarea and balls
If GameStopWatch.ElapsedMilliseconds > RoofLowerAfter Then
GameStopWatch.Reset()
GameStopWatch.Start()
RoofRect.Y += 5
PlayAreaRect.Y += 5
If UBound(BallsArray) > 6 Then
For Each TempBall As Ball In BallsArray
If TempBall.IsDeleted = False Then
If TempBall.IsDropped = False Then
If TempBall.IsInLauncher = False Then
If TempBall.MarkedForDeletionDrop = False Then
If TempBall.MarkedForDeletionExplode = False Then
TempBall.BallRect.Y += 5
End If
End If
End If
End If
End If
Next
End If
End If

MainSB.Draw(BallLauncherTex, BallLauncherRect, Color.White)
MainSB.Draw(BackgroundTex, BackgroundRect, Color.White)

'Draw Arrow - Arrow is drawn after ball so that it appears on top of ball.
'Anything drawn last will appear above anything drawn before

MainSB.Draw(ArrowTex, New Vector2(405, 485), Nothing, Color.White, ArrowSBRotate, _
New Vector2((ArrowTex.Width / 2), (ArrowTex.Height / 2)), 1.0F, SpriteEffects.None, 0.0F)

'Write Score on the Screen
If HighScore < CurrentScore Then
HighScore = CurrentScore
End If

'The WriteText sub uses about 30% CPU time, so this If statement tells it to run only if
'the score has changed.

If CurrentScore > TempScore Or MakeWriteTextOnlyRunOnTheFirstRenderLoop = 0 Then
MakeWriteTextOnlyRunOnTheFirstRenderLoop += 1
WriteText("High Score" & vbCrLf & HighScore & vbCrLf & vbCrLf & _
"Score" & vbCrLf & CurrentScore, "Mirror", 16, FontStyle.Bold, Brushes.Silver, _
630, 52, ScoreTexture, ScoreVector)
End If

TempScore = CurrentScore 'hold score in a temporary variable to see if it changes on next loop
MainSB.Draw(ScoreTexture, ScoreVector, Color.White)

'--------------------------------------------------------------------------------
' GameState Change
'--------------------------------------------------------------------------------

Case Is = "Paused"

'Draw PlayAreaRect Background
MainSB.Draw(ThemeTex, ThemeRect, Color.White)

'Draw Ball
If UBound(BallsArray) > 0 Then
For Each SingleBall As Ball In BallsArray ' Check every ball in array
If SingleBall.IsDeleted = False Then
MainSB.Draw(SingleBall.BallTex, SingleBall.BallRect, Color.White) 'Draw Each Ball
End If
Next
End If

'Animate Particles if there are any
If UBound(ParticlesArray) > 0 Then
For Each TempPart As Particle In ParticlesArray
MainSB.Draw(TempPart.ParticleTex, TempPart.ParticleRect, Color.White) 'Draw Each Particle
Next
End If

'Draw Roof and other Textures
MainSB.Draw(RoofTex, RoofRect, Color.White)
MainSB.Draw(BallLauncherTex, BallLauncherRect, Color.White)
MainSB.Draw(BackgroundTex, BackgroundRect, Color.White)
MainSB.Draw(PlayAreaTex, PlayAreaRect, Color.White)

'Draw Arrow - Arrow is drawn after ball so that it appears on top of ball.
'Anything drawn last will appear above anything drawn before

MainSB.Draw(ArrowTex, New Vector2(405, 485), Nothing, Color.White, ArrowSBRotate, _
New Vector2((ArrowTex.Width / 2), (ArrowTex.Height / 2)), 1.0F, SpriteEffects.None, 0.0F)

MainSB.Draw(ScoreTexture, ScoreVector, Color.White)

'Draw the Paused Text
If GameStopWatch.ElapsedMilliseconds < 500 Then
MainSB.Draw(PauseTex, PauseRect, Color.White)
ElseIf GameStopWatch.ElapsedMilliseconds > 1000 Then
GameStopWatch.Reset()
GameStopWatch.Start()
End If

'--------------------------------------------------------------------------------
' GameState Change
'--------------------------------------------------------------------------------

Case Is = "GameWon"

'Draw PlayAreaRect Background
MainSB.Draw(ThemeTex, ThemeRect, Color.White)

'Draw Ball
If UBound(BallsArray) > 0 Then
For Each SingleBall As Ball In BallsArray ' Check every ball in array
If SingleBall.IsDeleted = False Then
MainSB.Draw(SingleBall.BallTex, SingleBall.BallRect, Color.White) 'Draw Each Ball
If SingleBall.MarkedForDeletionDrop = True Then 'If a Ball is to be dropped
SingleBall.IsDropped = True 'Variable to exclude ball fromm Collison
SingleBall.BallRect.Y += SingleBall.BallXVel 'Move the ball down at speed BallXVel
SingleBall.BallXVel += 0.5 'increase BallXVel to give appearance of gravity
'If it moves below the playarea then delete it
If SingleBall.BallRect.Y > PlayAreaRect.Bottom Then
SingleBall.IsDeleted = True
End If
End If
End If
Next
End If

'Animate Particles if there are any
If UBound(ParticlesArray) > 0 Then
For Each TempPart As Particle In ParticlesArray
MainSB.Draw(TempPart.ParticleTex, TempPart.ParticleRect, Color.White) 'Draw Each Particle
MoveParticle(TempPart) 'Move each particle
Next
End If

MainSB.Draw(PlayAreaTex, PlayAreaRect, Color.White)
MainSB.Draw(BallLauncherTex, BallLauncherRect, Color.White)
MainSB.Draw(BackgroundTex, BackgroundRect, Color.White)
MainSB.Draw(ScoreTexture, ScoreVector, Color.White)

'Draw Arrow - Arrow is drawn after ball so that it appears on top of ball.
'Anything drawn last will appear above anything drawn before

MainSB.Draw(ArrowTex, New Vector2(405, 485), Nothing, Color.White, ArrowSBRotate, _
New Vector2((ArrowTex.Width / 2), (ArrowTex.Height / 2)), 1.0F, SpriteEffects.None, 0.0F)

MainSB.Draw(CongratTex, CongratRect, Color.White)

'Check for the passage of time
If GameStopWatch.ElapsedMilliseconds > 1500 Then
GameStopWatch.Reset()
GameStopWatch.Start()
GameState = "Loading"
RoofLowerAfter -= 250
If RoofLowerAfter < 2000 Then
RoofLowerAfter = 2000
End If
End If

'--------------------------------------------------------------------------------
' GameState Change
'--------------------------------------------------------------------------------

Case Is = "GameLost"
RoofLowerAfter = 4000
CurrentLevel = 0

'Set each ball to Explode
If UBound(BallsArray) > 0 Then
For Each TempBall As Ball In BallsArray
If TempBall.IsInLauncher = False Then
TempBall.MarkedForDeletionExplode = True
RemoveBalls(TempBall) ' Find those balls tha have MarkedForDeletionExplode = Fasle, then set IsDeleted = True
End If
If TempBall.IsDeleted = False Then
If TempBall.IsDropped = False Then
MainSB.Draw(TempBall.BallTex, TempBall.BallRect, Color.White) 'Draw Each Ball
End If
End If
Next
RedimBallArray() ' Remove those Balls that have IsDeleted = True from the Array
End If

'Draw PlayAreaRect
MainSB.Draw(PlayAreaTex, PlayAreaRect, Color.White)
'Draw PlayAreaRect Background
MainSB.Draw(ThemeTex, ThemeRect, Color.White)

'Animate Particles if there are any
If UBound(ParticlesArray) > 10 Then
For Each TempPart As Particle In ParticlesArray
MainSB.Draw(TempPart.ParticleTex, TempPart.ParticleRect, Color.White) 'Draw Each Particle
MoveParticle(TempPart) 'Move each particle
Next
End If

'Remove any Deleted Particles
If TheParticelArrayNeedsRedimmed = True AndAlso UBound(ParticlesArray) > 10 Then
CheckParticlesArray()
End If

'Draw Non ball stuff
MainSB.Draw(RoofTex, RoofRect, Color.White)
MainSB.Draw(BallLauncherTex, BallLauncherRect, Color.White)
MainSB.Draw(BackgroundTex, BackgroundRect, Color.White)
MainSB.Draw(GameOverTex, GameOverRect, Color.White)
MainSB.Draw(ScoreTexture, ScoreVector, Color.White)

'Draw Arrow - Arrow is drawn after ball so that it appears on top of ball.
'Anything drawn last will appear above anything drawn before

MainSB.Draw(ArrowTex, New Vector2(405, 485), Nothing, Color.White, ArrowSBRotate, _
New Vector2((ArrowTex.Width / 2), (ArrowTex.Height / 2)), 1.0F, SpriteEffects.None, 0.0F)

'go bak to start screem
If UBound(ParticlesArray) < 15 Then
PlayAreaRect.Height = 480
PlayAreaRect.Width = 379
PlayAreaRect.Y = 60
PlayAreaTex = Texture2D.FromFile(XNAGraphics.GraphicsDevice, "../../images/WaitingToStart.png", NonBallTexCreationParams)
GameState = "WaitingToStart"
End If

End Select

MainSB.End()

MyBase.Draw(gameTime)

Else
' OnDeviceReset(XNAGraphics.GraphicsDevice, Nothing)
End If

'Check if Audio is playing
If DirectXAudio.CurrentPosition >= DirectXAudio.Duration Then
SelectMusic()
End If

End Sub

'Stuff to do when the game Exits
Private Sub XNAGame_Exiting(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Exiting
'Write High Score to High Score File
If My.Computer.FileSystem.FileExists(Application.StartupPath & "\HighScore.txt") = True Then
Try
Using sr As StreamReader = New StreamReader(Application.StartupPath & "\HighScore.txt")
Dim x As String = sr.ReadToEnd
sr.Close()
If IsNumeric(x) = True Then
x = CInt(x)
If x < HighScore Then
Using sw As StreamWriter = New StreamWriter(Application.StartupPath & "\HighScore.txt", False)
sw.WriteLine(HighScore)
sw.Close()
End Using
End If
End If
End Using
Catch ex As Exception

End Try
Else
Try
Using sw As StreamWriter = New StreamWriter(Application.StartupPath & "\HighScore.txt", False)
sw.WriteLine(HighScore)
sw.Close()
End Using
Catch ex As Exception

End Try
End If

End Sub

End Class

'The starting point for th game
Module modMain
'An instance of the XNAGame Class
Public Game1 As XNAGame

'The starting point of the game is Main() because it is ot a windows form
Public Sub Main(ByVal args As String())
Game1 = New XNAGame
Game1.Run()
End Sub

End Module

End Namespace

You will notice a lot of recognizable code, which is to be expected because we haven't actually changed any of the game logic, all we have done is removed the mainform and added the game component which holds its own form. The other changes are that we no longer have to create a device object because game does it for us and hence Device becomes XNAGraphics.GraphicsDevice , which is part of the XNAGraphics object that was created in the New Sub. This means that all occurrences of Device must be changed to XNAGraphics.GraphicsDevice. There were a few other changes that were less important, some that affected game play and some that were required to display the textures.

Lastly, I'll give you a quick indication of how the game runs:

1 - Sub Main

2 - Sub New

3 - Sub Initialize

4 - Sub Update

5 - Sub Draw

6 - Update and Draw then Loop

So, now we have a project that includes the game component and hence, now I can work on the content pipeline, which,by the way, I will upload to the tutorial's page, when its done, Enjoy.

 

InheritsGame Source Code - 2,777Kb
Next Tutorial - The Content Pipline

 

 

     
 
 
     

 

Web site contents © Copyright Alan Phipps 2006, All rights reserved.
Website templates
   
 
 

 

__PayPal

PayPal - Any Amount is Welcome
 
Please Donate to the Nvidia Geforce Go 7950 GTX Fund, All donations welcome. Thanks.

 

XNA in C#

 
 

 

Games at Amazon