Kid’s Programming Language: Christmas Tree Shooter

Sign in to queue


  This article lights on a language called Kids Programming Language (KPL). This is a very easy language and especially made for people which are not the memeber of programers team. It mainly deals with games.

Difficulty: Intermediate
Time Required: 1-3 hours
Cost: Free
Software: Phrogram
Download: Download

Ho Ho Ho! Merry Christmas! Happy Holidays! Ho Ho Ho! Naughty or nice? We don't really want to know! Ho Ho Ho!

Have you seen the previous articles here at Coding4Fun about KPL, the Kid's Programming Language? The overview and the article on KPL Pong. KPL is not just for kids; it's for anyone who wants to code fun stuff fast. Proving the point, we're working on a couple of Holiday-themed KPL games and articles—like this one, ChristmasTreeShooter.kpl! We have a fun and easy suggestion for how you and family or friends can modify the game yourself, too.

Generic Episode Image

For some unknown reason, your Christmas tree is bobbing and weaving unpredictably before your eyes. It just won't hold still! And you have the rest of these ornaments that you have to hang on the tree, or you can forget about opening that green box. You suspect it's got an Xbox 360 in it, and going with that theory, you're not shaking it like the others. Just in case. Anyway, you do your best with the ornaments, and Santa rates your performance at the end. Not a guy you want to disappoint, coming down to that Christmas Eve wire...

This KPL game was implemented in 161 KPL instructions, and will be simple code for an experienced or hobbyist programmer to follow. It uses sprites for graphics and uses custom sound clips, which we're going to show you how to replace with your own voice-overs. What are friends or family going to say when it's you who rates their performance? Are you going to be deadpan and droll? Acerbic and insulting? Will you do a Santa voice, a Mrs. Claus voice or an Elf voice? However you record it, you know it'll be fun!

Chances are, if you're here at Coding4Fun, you're more than just a beginning programmer—but I bet you can think of some friends or family who might like to be a beginning programmer? Well, we made KPL for them—and you helping them learn with KPL should make it fun and easy for both of you. This game ought to catch their interest, but if they're a novice perhaps you can help them through the Beginning Programming with KPL Tutorial before you work with them on this or other KPL game code.

Just the interesting stuff, please

This article will assume some basic programming skill, and rather than explaining every line of code in the KPL program, will focus on key techniques or algorithms which will be useful as you develop your own KPL games:

  • Finding free images online

  • Using Sprites in KPL

  • Recording and using custom sounds

  • Using Arrays

  • Handling keyboard input

  • Sprite interaction

  • Allowing user customization of game behavior

Before we begin, the article will make the most sense if you have installed KPL, and downloaded and unzipped the Christmas Tree Shooter program underneath your KPL install folder. The ideal way to start, of course, is to load ChristmasTreeShooter.kpl in the KPL IDE, click "Run the program," and play it a few times before examining the code. Smiley

KPL and this program are both available as freeware downloads from: KPL does have a dependency on the .NET Framework 1.1, and the KPL install will "auto-magically" download and install the Framework if it is not already installed on your machine.

Finding Free Images Online

There are many many places online that offer free images that you can reuse in your own KPL programs. An MSN Search for "Christmas Tree Clipart" returned 589,677 search results when I ran it. Here's the page where we found our Xmas tree:

That particular page is of interest because it's been viewed over 200,000 times—who'd have thought?!? And because it is the only web page I can think of using a background WAV file that I actually liked hearing!

KPL supports images in all standard file formats, including GIF, JPG, PNG, TIF and BMP. KPL does support animated GIFs, but those are not used in our Christmas Tree Shooter. If you're using Internet Explorer, saving an image you find on the Web for reuse is easy: right-click the image, and select "Save Picture As...". KPL will automatically find an image by file name if the image is in the Media\Images folder under the KPL installation folder; if you expect to use an image from more than one KPL program, this is the right place to put it. If an image is specific to the program you are working on, you can leave the image in the same folder as the .kpl program itself. KPL will find it in the local folder, looking there first before checking the Images folder.

Of course, the caveat about finding images online is making sure the site allows you to reuse the image. Image reuse happens all the time on the Web, but of course, if you find an image with a copyright or other usage limitation stated on the page, you will want to comply. There are many many freely usable images out there, so it's safest and simplest to keep looking until you find one with no strings attached.

Using Sprites in KPL

Here's a single method we coded that wraps the basic KPL sprite commands into one:

Method LoadSizePlaceSprite(name As String, file As String, 
scale As Decimal, x As Int, y As Int)
LoadSprite( name, file )
ScaleSprite( name, scale )
MoveSpriteToPoint( name, x, y )
ShowSprite( name )

End Method

This allows a single call to load, place and display a sprite:

LoadSizePlaceSprite("TREE", "Christmas Tree3.png", 1.50, 
TreeX, TreeY )

The name parameter gives the sprite a name which you will use to refer to it when you manipulate the sprite.

The file parameter is the filename to the image file which will be used to represent the sprite on-screen. No path is required to the filename, but the file must be in the local folder with the .kpl program, or in KPL's Media\Images folder.

The scale parameter is a size multiplier for displaying the sprite. 1.0 is no size change, 0.5 is half size, etc…

The x and y parameters specify the screen location where the sprite will be displayed, in pixels, with the default being that the upper left corner of the window is location (0, 0).

KPL defaults all sprites to the same ZIndex of 0—all sprites are drawn or rendered on the same layer, so the last one drawn always appears "on top." SetSpriteZIndex(name, ZIndex) can be used to specify the ZIndex to control this. Sprites with a higher ZIndex will always be drawn on top of sprites with a lower ZIndex.

SetSpriteZIndex("Ball" + BallCount, 10)

Other Sprite-manipulating methods used in ChristmasTreeShooter.kpl are:

HideSprite() takes the name of the sprite which is to be hidden when it is no longer needed:


GetSpriteHeight() and GetSpriteWidth() return a height or width in pixels of the sprite:

GetSpriteHeight( "CrossH" )

SpritesIntersect() takes the name of two sprites, and returns true only if they intersect or overlap on the screen:

If SpritesIntersect("TREE", "Ball" + OrnamentCount) Then

That's all the Sprite code used in ChristmasTreeShooter.kpl. We have designed KPL to be as simple and as highly leveraged as possible, and this is particularly visible in KPL support for Sprites.

Recording and using custom sounds

This KPL program uses custom sounds for Santa's rating of your performance at the end of the game. As with images, sound files can be placed in the same folder as the program if they are used only for the program. If you'd like to share the sounds across more than one program, they can be placed into the Media\Sounds folder underneath KPL's install folder.

The sounds used for the game were recorded using the Sound Recorder, which is available as part of all versions of Windows. You can launch it from Start Menu > All Programs > Accessories > Entertainment > Sound Recorder, or by running sndrec32.exe from the Start > Run... dialog. If you've been a geek long enough, that file name will remind you of the good (?!?) old days. Not only of 32-bit Windows, but of 8-character MSDOS file names. Amazing thing is, that really wasn't very long ago. Smiley

The File menu and the tape-deck style button bar are all of the Sound Recorder that you'll need to use. KPL currently supports .WAV file formats. We're adding support for more sound formats—as well as the ability to play multiple, layered sounds—to KPL v 2, which is targeted for a January 2006 release. Any other program which allows recording or editing supported sound files can be used instead of the Sound Recorder, or course.

So, here's a fun, easy customization: use Sound Recorder to record and save your own version of the following sound files in place of ours! Here are our sounds and their scripts:

HoHoILikeIt.wav: "Ho Ho Ho! I like it!"

HoHoTryAgain.wav: "Ho Ho Ho! Try again!"

You can, of course, say anything you like, and/or give your recordings a different name. If you do use a different name, you'll need to change the following lines of KPL code to match:

If HitCount = 5 Then
PlaySound( "HoHoILikeIt.wav" )
PlaySound( "HoHoTryAgain.wav" )

End If

Using Arrays in KPL

KPL does support the use of arrays, as well as user-defined structures. KPL v 2 will add support for user-defined classes—an ideal way to encapsulate logic such as the handling of our Christmas tree ornaments. Until then, we kept this simple by using arrays to handle the five of them:

Define BallX As Int[5]
Define BallY As Int[5]

Define BallOffset As Int[5]

And here is an example from the program showing the use of these arrays:

    BallOffset[OrnamentCount] = BallX[OrnamentCount] - TreeX 

Handling keyboard input

A simple model for coding a game in KPL is a large loop which, at a controlled interval, processes user input and game events. Here is our Method Main(), which shows how this loop is the basis of the processing for the program:

Method Main()

// Show Instructions
Alert("Use the Arrow keys to move the shooter and tap the
Space Bar to place an ornament. Placing an ornament
on another will break both!", "How to play!")

Define CurrentTime As Decimal
Define TimeLastChecked As Decimal

// Start the wait time for the Space Bar to prevent the Key
// Bounce effect
LastOrnamentFireTime = TickCount()

While GameOver = False

CurrentTime = TickCount()

// If 60 milliseconds have not passes since the last
// time we checked, we don't do anything yet.
If CurrentTime - TimeLastChecked > 60 Then
// Every 60 milliseconds (that's 17 times a
// second!) we fall into this block.
// First we process Key events to move the
// targeting circle
// Then we MoveTheTree.
// We reset the timer each time, so we wait
// another 60 milliseconds before moving again.
TimeLastChecked = CurrentTime
End If

End While


End Method

The actual processing of key events is done in the ProcessKeyEvents() method, using the IsKeyDown() function:

    If IsKeyDown( "Up" ) Then
If CrossHY > 10 Then
CrossHY = CrossHY - CrossHairSpeed
End If

End If

The key processing code checks for all keys that are relevant to targeting movement, and will handle any and all keys that are down. It also uses logic as shown above so that keys which would cause the targeting circle to move off the viewable screen are ignored.

One issue caused by processing keys in a loop this way results from the fact that the computer loop can be so much faster than our own fingers on the keyboard, which can result in processing the KeyDown more than once on a single tap of the Space Bar. When the single Space Bar keystroke is as important to the game as it is here, we must add a little extra code which makes sure we don't process that Space Bar keystroke more than once. The following code, at the bottom of the ProcessKeyEvents() method, does this using the global variable LastOrnamentFireTime:

// Process the wait time for the Space Key to reduce the Key 
// Bounce Effect. If it's been less than 200 milliseconds...
currentTime = TickCount()
If (currentTime - LastOrnamentFireTime) < PlayerOrnamentFireDelay Then
Return // Exit the method without processing
End If
If IsKeyDown( "Space" ) Then
LastOrnamentFireTime = currentTime

End If

Sprite interaction

What you are attempting to do with this game, of course, if place each of the five ornaments onto the bobbing and weaving Christmas tree, without breaking them. Since the tree and the ornaments are all implemented as sprites in this KPL program, this is as easy as checking to see whether the sprites "intersect" when you hit the spacebar to place an ornament. The code for this is in method ShootOrnament():

If SpritesIntersect("TREE", "Ball" + OrnamentCount) Then
PlaySound( HitSound )
// if we hit the tree count it and show it
HitCount = HitCount + 1
// calculate the ornament offset
BallOffset[OrnamentCount] = BallX[OrnamentCount] - TreeX
// if we miss the tree all together don't count or show ornament
PlaySound( BreakSound )
HideSprite("Ball" + OrnamentCount)

End If

Note that if we actually got the ornament on the tree, we figure out its Offset so we can later move it along with the tree. And if we miss the tree altogether, the bulb breaks and is not shown.

These ornaments are those fragile little glass balls—proof that guys have no business decorating Christmas trees, right?!? If we actually shoot one glass ball on top of another, well, they both break, Santa is less than pleased, and we might never get to open that green box! Here are the nested For...Next loops that check for this:

For Ornaments = 1 To OrnamentCount
If Ornaments < OrnamentCount Then
For OtherOrnaments = (Ornaments + 1) To OrnamentCount
// Process balls hitting balls, don't count them and
// don't show them
If SpritesIntersect("Ball" + Ornaments, "Ball" +
OtherOrnaments) Then
PlaySound( OrnamentHit )
HideSprite("Ball" + Ornaments)
HideSprite("Ball" + OtherOrnaments)
HitCount = HitCount - 2
End If
End If

Besides nested loops always being fun exercises of logic, this is interesting because it shows how easy it can be to use an automatic type conversion to build a string from a number. Our sprites are named Ball1 to Ball5, and when we need to process them in a loop this way, we can simply construct the name by concatenating "Ball" + Ornaments, where the latter is the integer loop index.

Allowing user customization of game behavior

Besides being educational, open-source KPL games have the advantage of allowing a user to change or customize the game behavior. The entire game and all its code is there for the user's modification, but it's also worth putting a little thought and effort into allowing easy customization of the behavior of your game. Our Christmas Tree Shooter does this with three global variables, defined, commented and changeable up at the top of the program file:

// Set these next 3 variables to affect game play
Define CrossHairSpeed As Int = 20
Define TreeSpeed As Int = 20
// how many times the tree will move before game is over

Define MoveCount As Int = 2 // = once to the right, once to the left

Good naming and comments make this pretty easy for users to find and change. The two speed variables can be tweaked to make the game easier or harder, depending on the user's reflexes. And the move count can be increased to lengthen the game and allow the user more time.

Building in game settings based on global variables like this just takes a little thought, and can allow a fun extra level of control for people playing your game.

What's next?

Two or three other Holiday-themed KPL games should also be up on the Coding4Fun site. Have fun with them, and Happy Holidays—no matter which particular Holiday you're celebrating at this time of year!

KPL Asteroids is also next in the series of retro games implemented with KPL—watch for that in the next couple of weeks!

There are now dozens of open source KPL games, and dozens more educational programs—either included in the base KPL install, or new and separately downloadable. Check them all out at

Moral of the story? Coding4Fun isn't just a name—it's the point!


events, Holiday

The Discussion

Add Your 2 Cents