Click here to Skip to main content
15,890,186 members
Articles / Programming Languages / Visual Basic
Article

How to build a breakout style game with animation and sound.

Rate me:
Please Sign up or sign in to vote.
2.31/5 (15 votes)
9 Jan 20042 min read 68.1K   1.3K   15   12
Summery of the project.

Sample Image - breakout_picture.png

Introduction

Welcome to another installment of, "Boy this guy really has nothing better to do". :-) My latest creation is called Tiny Breakout. I 100% GDI+ code that runs really smooth after I stumbled across some new features. I am not going to give out the source on this for a few reasons. One I might want to release this as shareware and two because there are a few sloppy spots that I need to clean up. But, I will outline some of the new stuff I used in the creation of the animation effects and also show you how I incorporated sound without resorting to DirectX.

The Blocks

I used the basic structure I have been using now in my demos for the past few days. All the different elements (ex. ball, paddle and blocks) reside in there own class structure with the basic methods of New, Draw and Move. Some of them has special attributes such as isImpact and changeDirection.. But probably most importantly they all have a Public Location as rectangle in them to let me know where the objects are on the screen.

For instance say I needed a block for the board of the game. To create the block I simply call its new function.

VB.NET
'
' destPoint is a point structure of where you want to place the block
' 5 is the point value of the block
' Brushes.Blue is the color to make the block
'

Blocks(thisBlock) = New cBlocks(destpoint, 5, Brushes.Blue)

As you see I have an array of blocks and each one gets created sepritly.

The Paddle

The paddle is constructed much in the same way as the blocks (call the new procedure and it builds the paddle etc.). However, unlike the blocks the paddle needs to move.This was done with the basic mouse event.

VB.NET
Private Sub game_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles game.MouseMove
    Paddle.Location.X = e.X - (Paddle.Location.Width / 2)
End Sub

As you can see I don't redisplay the paddle, that's the job of the paint event. I tried something new when working with the paint event today, I started invalidating (repainting) regions of the screen instead of the whole screen like this.

VB.NET
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Dim PaddleInvalidate As Rectangle = New Rectangle(0, Paddle.Location.Y, game.ClientSize.Width, Paddle.Location.Y + 10)

I set a rectangle equal to the entire segment where the paddle could be.

VB.NET
    game.Invalidate(PaddleInvalidate)
    game.Update()
End Sub

Then I tell it I want to redraw that segment of the screen and it needs to do it now. The paint event is then called and it executes paddle.draw(e.graphics) creating a seemless animation.

The sound

Here i a copy of the class I built based on a few usenet postings.

VB.NET
Imports System.Runtime.InteropServices

Public Class cSound
    Private Const SND_SYNC As Int32 = &H0
    Private Const SND_ASYNC As Int32 = &H1
    Private Const SND_FILENAME As Int32 = &H20000

    ' Import the Windows PlaySound() function.
    <DllImport("winmm.dll", EntryPoint:="PlaySound", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Private Shared Function WinPlaySound(ByVal pszSound As String, _
                                         ByVal hmod As Int32, _
                                         ByVal fdwSound As Int32) As Boolean
    End Function

    Public Sub playSound(ByVal filename As String)
        Dim path As String = Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\"))
        If IO.File.Exists(path & "\" & filename) Then
            WinPlaySound(path & "\" & filename, 0, SND_FILENAME Or SND_ASYNC)
        End If
    End Sub

End Class

when I want to play a wav file all I have to do is:

VB.NET
Public sound As New cSound
sound.playSound("click.wav")

The status bar at the top of the screen

The status bar is actually a border less form. I created a 300x20 pixel form, set the opacity to 65% and positioned on the top of the game board for tracking Lives, Score and Level information.

The rest

The balls class i'm going to keep under wraps for a while but I will give you a hint on the animation side. When the timer ticks I just game.invalidate(ball.lastPos) and game.invalidate(bball.newPos).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I started programming for fun when I was about 10 on an Franklin Ace 1000.

I still do it just for fun but it has gotten me a few jobs over the years. More then I can say for my Microsoft Certifications. Smile | :)

The way I learned was by example, now its time to give back to the next generation of coders.



Comments and Discussions

 
GeneralMy vote of 5 Pin
Global Analyser3-Nov-10 6:59
Global Analyser3-Nov-10 6:59 
GeneralGreat Job Pin
Anonymous8-Apr-04 18:49
Anonymous8-Apr-04 18:49 
GeneralDon't take this the wrong way but... Pin
Paul Ingles11-Jan-04 4:03
Paul Ingles11-Jan-04 4:03 
GeneralWell said Pin
dog_spawn11-Jan-04 5:53
dog_spawn11-Jan-04 5:53 
GeneralRe: Well said Pin
Matthew Hazlett11-Jan-04 7:35
Matthew Hazlett11-Jan-04 7:35 
GeneralRe: Well said Pin
Paul Ingles11-Jan-04 8:25
Paul Ingles11-Jan-04 8:25 
Naming conventions are a personal matter, but for .NET there is a fairly comprehensive article in the MSDN documentation about what Microsoft use, and what other library developers have attempted to follow. As you say, once people get into something it's difficult to change -- I often find I'm tempted to use hungarian notation in whatever I'm doing, but following guidelines such as the ones in MSDN adds to the professional image of code.

Invalidating and updating is covered in numerous other articles. Besides, you just mention that you invalidate and update, rather than explaining more on the matter. Honestly, you do not further the updating and invalidating concepts here.

How to build sound into your application. Again, I'm sure there are countless other articles that talk about this. Why haven't you covered anything about having to Platform Invoke the support? Is there anything in the framework as-is that lets you play media? Etc. etc. By merely mentioning wrapping stuff using the Win32 API to get sound it's not helping anyone. If the only thing offered in articles is a 'code-by-numbers' approach whereby people just copy code, there's no opportunity for learning!

As for suggestions, here's stuff taken from the article submission page:
1) What does the code do?
2) How do I integrate it with my existing code or how do I use it?
3) If there is a similar article on CodeProject already, then how does this one differ? Why would someone want to use your version?
4) Is there some aspect of the code that is of particular interest that perhaps should be covered in the article?
5) Are there any particulat environments the code is restricted to? (Windows 2000 or above, .NET SP1 etc)

My own suggestions would be take a look at the extremely well rated articles, such as pretty much everything by Michael Dunn, James Johnson, Chris Maunder, Paul Watson, and numerous others. It's pretty easy to see the difference!

I always try and take a top-down approach to whatever I write (whether it be for this site or during my work etc). Describe the current situation, why your solution is needed, what things would address the current situation to improve matters, and how your solution approaches it. Then go through your code (with code snippets) explaining what aspect of the solution they deal with, and how the fit in as a whole.

Again, I apologise if you feel I'm being overly harsh, but this criticism applies to so many other articles on here... but as I said, you really don't discuss much.

How to build a breakout style game. Your article doesn't come close.

Firstly, you don't discuss the basic principles surrounding the various classes. If you do indeed discuss them in other articles you've written (sorry, but after reading the first few sentences I had no intention of reading anything else), then link to them so people can easily catch up. Even better would be a summary of what each class is responsible for, providing links to articles that discuss in more depth how the classes were designed, how you figured out what interfaces they should provide etc. At present I can guess what each thing does, but have no idea why you chose one approach over another. Did you use an event-driven approach where each object listens for events from a central game controller? Why not? etc. etc.

You then mention using invalidation. How? Again, my guess is this is covered in so many other articles here, but you give absolutely no useful code in there, other than showing how the Invalidate method is called. Great, I've been able to clarify one further method signature.

Sound, you mention you copied a Usenet article. Do you know why you had to use interop services? What's the impact about P/Invoking native code? How can the code you've got be applied to other things people are working on. Again, you've covered something that will have been written about before, so sorry, but you've not really got anything new to say on the matter. Or have you? Without you putting more in we'd never know.

The balls class. Great, it's being kept under wraps. Sorry if you think I'm bordering on becoming aggressive in my writing, but this is just plain worthless. Anybody who reads down here is doing well to be honest, but this is a final "I don't really have an article to write, but what the hell".

So, I feel I've given you enough to go on. I'd say the best thing to do would be to look through other articles here that you're going to be doing the same thing on, i.e. anything on GDI+ and sound. Figure out why you're article is going to be doing something different and will have your own added value. Otherwise, its a repeat and worthless.

As mentioned by someone else, game articles are always intriguing since for hobbyist coders, they offer something better than a boring app to try and build. In which case, you want to focus on how you designed the game, what things you had to solve (i.e. collision detection, scoring, level design).

However, since you've mentioned in a couple of places that you don't intend to show any significant part of the code, keeping the Ball handling 'under wraps' and that you might release it as shareware (not sure it'd make a great deal of money, these kind of games can be found on Flash sites for free), it's a fair assumption that you don't really have any intention of writing something that's actually going to provide something new to this site.

Please, please, write something better. Ignore the commercial implications, I was close to extending the code I had written in mine to sell, but I was always going to keep the code I had up free since I knew I could make things have better features, and provide support etc. Saying you're keeping the code close to your chest so you can release it as shareware is pretty silly. Especially since anyone with half a brain can read through the ILDASM output of the project and figure out how it works. Besides, I honestly don't think you would get that many sales, requiring customers to download the .NET framework just to play break-out for starters would limit your audience significantly!

I've given some constructive criticism, and feel that I have been quite harsh in places, but there are far too many other articles like this on the site. Hence the introduction of the Purgatory article bin.

--
Paul
"Put the key of despair into the lock of apathy. Turn the knob of mediocrity slowly and open the gates of despondency - welcome to a day in the average office."
- David Brent, from "The Office"

MS Messenger: paul@oobaloo.co.uk
Download my PGP public key

GeneralRe: Well said Pin
Matthew Hazlett11-Jan-04 9:06
Matthew Hazlett11-Jan-04 9:06 
GeneralRe: Well said Pin
Anonymous11-Jan-04 11:13
Anonymous11-Jan-04 11:13 
GeneralRe: Well said Pin
dog_spawn11-Jan-04 8:46
dog_spawn11-Jan-04 8:46 
GeneralRe: Well said Pin
Matthew Hazlett11-Jan-04 9:08
Matthew Hazlett11-Jan-04 9:08 
GeneralPointless even trying Pin
dog_spawn11-Jan-04 14:15
dog_spawn11-Jan-04 14:15 
GeneralRe: Don't take this the wrong way but... Pin
NetDevKing24-May-04 7:15
NetDevKing24-May-04 7:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.