Quantcast
Channel: MSDN Blogs
Viewing all articles
Browse latest Browse all 29128

VB Guru - How to Create Video Games in VB.Net (Windows Forms)

$
0
0

Congratulations to our VB Guru winner for May 2013! To find all the competitors for May (and more information about this monthly contest), see the Wiki article: TechNet Guru Awards, May 2013.

Here are our three winners:

Visual Basic Technical Guru - May 2013

Gold Award Winner

 

Reed
Kimble
How to Create Video Games in VB.Net (Windows Forms)
  • "This article starts out super well."
  • "The how to create a video game article was a subject that is often asked about in places like the forums. It addressed the subject with well written text and code examples to match."
  • "It was pitched at just the right level for hobbyist/early learners that are often the ones trying to achieve this."
  • "It covers very well the concept of a game loop and how to make one somewhat performant (best made-up word ever)."

 

Silver Award Winner

 

Paul
Ishak
How to convert a 32bit integer into a color
  • "I like how this article walked me through each aspect of the code, showing snippets of each section. It felt more professional." 
  • "It does address an important item about breaking values into their constituent byte values. The code examples are simple and straightforward and easy to understand without even a need to have VB running."
  • "Well-written; it explains another concept that mature developers might take for granted."

Bronze Award Winner

 

Paul
Ishak
Virtual memory in Visual Basic.Net
  • "Nice code sample."
  • "Was actually the most informative in some ways, particularly for the professional developer."

 

Here are excerpts from the article:

 

How to Create Video Games in VB.Net (Windows Forms)

I realize that this is a very popular subject, especially amongst budding developers. The drive to create games may be the reason you started working with Visual Basic in the first place. After stepping through a few samples and getting the hang of working with user controls on a form, it may be very tempting to start to throw some PictureBoxes and a Timer on a Form and start to implement some game logic. Seems easy enough, right?

To some extent, this is a true statement. You could start to do this and it would be easy enough… at first. But when you begin to try to calculate collision and animate or rotate your “sprites”, you may start to run into some difficulty. And attempts to circumvent the problems often lead to even worse issues. This can cause an endless spiral of misery which could leave you thinking VB just isn’t meant to make games! ;)

The initial problem that most people face is the desire to use a PictureBox (or any other control) as the logical “Sprite” container for the elements in the game. It makes sense since the control appears to provide a lot of the required functionality already and it’s easy to extend it with more properties as needed.

... 

Here is an example from a thread on the MSDN forums. This very simple example
uses a Timer component as the “game engine” and the Form serves as the “render
canvas”.

OptionStrict On
 
PublicClassForm1
    'One timer controls the entire game
loop
    PrivateWithEventsTimer1 AsNewTimer
 
    'A list of the game tile objects used by the
game
    Private_GameTiles AsNewList(Of GameTile)
    'An instance of GameTime to track running game
time
    Private_GameTime AsNewGameTime
 
    'Two bitmaps and a boolean used to buffer drawing and
rendering
    Private_Buffer1 AsNewBitmap(ClientSize.width,
ClientSize.height)
    Private_Buffer2 AsNewBitmap(_Buffer1.Width,
_Buffer1.Height)
    Private_BufferFlag AsBoolean
 
    PrivateSubForm1_Load(sender AsSystem.Object, e AsSystem.EventArgs) HandlesMyBase.Load
        'setup the form
        Me.DoubleBuffered = True
        Me.FormBorderStyle =
Windows.Forms.FormBorderStyle.Fixed3D
        'load some image assets to use for frames of
animation
        DimimageList AsNewList(Of Image)
        imageList.Add(SystemIcons.Application.ToBitmap)
        imageList.Add(SystemIcons.Error.ToBitmap)
        imageList.Add(SystemIcons.Exclamation.ToBitmap)
        imageList.Add(SystemIcons.Information.ToBitmap)
        imageList.Add(SystemIcons.Question.ToBitmap)
        'create a grid of tiles
        Fory AsInteger= 0 To7
            Forx AsInteger= 0 To7
                Dimtile AsNewGameTile
                tile.FrameImages.AddRange(imageList)
                tile.Location = NewPoint(12 + (x * tile.Bounds.Width), 12 + (y *
tile.Bounds.Height))
                _GameTiles.Add(tile)
            Next
        Next
        'set the game time to 30 fps (1000ms /
30frames)
        Timer1.Interval = 33
        'start the game loop
        Timer1.Start()
    EndSub
 
    'Use a stopwatch to track the execution
time
    Private_ElapsedTime AsNewStopwatch
    PrivateSubTimer1_Tick(sender AsObject, e AsSystem.EventArgs) HandlesTimer1.Tick
        _ElapsedTime.Stop()
        'Record they time since the last loop
iteration
        _GameTime.Elapse(_ElapsedTime.ElapsedMilliseconds)
        'Reset the stopwatch to 0 and start tracking
again
        _ElapsedTime.Restart()
        'Run a loop to check input for each
item.
        ForEachtile In_GameTiles
            IfMouseButtons = Windows.Forms.MouseButtons.Left
Then
                Iftile.Bounds.Contains(PointToClient(MousePosition))
Then
                    tile.OnInput(_GameTime)
                EndIf
            EndIf
        Next
        'Run a loop to draw each item after determining
which
        'buffer to draw on this frame
        Dimgfx AsGraphics
        If_BufferFlag Then
            gfx =
Graphics.FromImage(_Buffer1)
        Else
            gfx =
Graphics.FromImage(_Buffer2)
        EndIf
        gfx.Clear(BackColor)
        ForEachtile In_GameTiles
            tile.OnDraw(_GameTime, gfx)
        Next
        'Cleanup and swap buffers
        gfx.Dispose()
        _BufferFlag = Not_BufferFlag
        'Show the drawn scene
        Invalidate()
    EndSub
 
    ProtectedOverridesSubOnPaint(e AsSystem.Windows.Forms.PaintEventArgs)
        MyBase.OnPaint(e)
        'Draw the approprite render
buffer
        If_BufferFlag Then
            e.Graphics.DrawImageUnscaled(_Buffer2,
Point.Empty)
        Else
            e.Graphics.DrawImageUnscaled(_Buffer1,
Point.Empty)
        EndIf
    EndSub
EndClass
 
PublicClassGameTile
    PublicPropertyLocation AsPoint
    PublicPropertyFrameImages AsNewList(Of Image)
    'this is the images per second of the
animation
    PublicPropertyFrameRate AsDouble= 8.0
    'this is the total time to animate after recieving a
click
    Private_AnimationTime AsDouble
 
    PublicReadOnlyPropertyBounds AsRectangle
        Get
            ReturnNewRectangle(Location,
FrameImages(CurrentFrameIndex).Size)
        EndGet
    EndProperty
 
    Private_FrameIndex AsDouble
    PublicReadOnlyPropertyCurrentFrameIndex AsInteger
        Get
            ReturnCInt(Math.Floor(_FrameIndex))
        EndGet
    EndProperty
 
    PublicSubOnInput(gameTime AsGameTime)
        'set the remaining animation time to 3 seconds when
clicked
        _AnimationTime = 3.0
    EndSub
 
    PublicSubOnDraw(gameTime AsGameTime, gfx AsGraphics)
        'draw the current frame at its current
location
        gfx.DrawImageUnscaled(FrameImages(CurrentFrameIndex),
Location)
        'if there is remaining animation time, then
animate
        If_AnimationTime > 0 Then
            _FrameIndex += gameTime.LastFrame *
FrameRate
            IfCurrentFrameIndex = FrameImages.Count Then_FrameIndex = 0.0
            _AnimationTime -=
gameTime.LastFrame
        Else
            _FrameIndex = 0.0
        EndIf
    EndSub
EndClass
 
'GameTime can be a simple structure or class which just
tracks executed
'game
time based on what the game loop tells it
PublicStructureGameTime
    PublicElapsedTime AsTimeSpan
    PublicLastFrame AsDouble
 
    PublicSubElapse(milliseconds AsLong)
        ElapsedTime +=
TimeSpan.FromMilliseconds(milliseconds)
        LastFrame = milliseconds /
1000
    EndSub
EndStructure

 

...

GdiGaming API

Finally, if you still have your heart set on making a quick little game directly in VB.Net (and why shouldn’t you?! They do make such fun projects!), then you may wish to check out the GdiGaming API over on CodePlex

 

 

Read the entire article here:

How to Create Video Games in VB.Net (Windows Forms)

 

Thanks again to Reed for a great contribution!

   - User Ed
.


Viewing all articles
Browse latest Browse all 29128

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>