Kid's Programming Language: Pong!
- Posted: Nov 02, 2006 at 9:54PM
- 4,894 views
|This article is first in series of KPL articles.It presents the KPL code that implements the game shown below—Pong!|
Time Required: Less than 1 hour
Software: Kid's Programming Language
Welcome to the first article in a series of fun coding projects built using KPL—the Kid's Programming Language! As you'll see, KPL is not just for kids—it's for anyone who wants to code fun stuff fast. This article will present the KPL code that implements the game shown below—Pong! We thought that recreating the first video game ever invented was a good place to begin our series of KPL examples.
Here are some fun historical links about Pong:
The original Pong console launched the video game revolution—with home consoles and arcade machines—and all it did was let you bounce a very pixilated white ball around your black TV screen! At Christmas time in 1975, people lined up outside Sears, waiting to buy one! Contrast that with what you'll bring home when you hunt-and-gather your Xbox 360 next month—a lot has happened in 30 years, eh?
Recreating the game that started it all took, in my version, 180 lines of KPL code, and just a few hours. And ya know what? It's still fun! Oh, if you checked out Oilzine's article above, you know that the other pillar that began the video game industry was Asteroids. Guess what classic video game our next article will recreate?
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:
Before we begin, the article will make the most sense if you have installed KPL, and have opened the KPL program Kplong.kpl, which you will find in the KPL Programs > Games folder in KPL's File Explorer. The ideal way to start, of course, is to load Kplong.kpl in the KPL IDE, click "Run the program," and play it a few times before examining the code.
If you are using a version of KPL from before October 10th, it may not include Kplong.kpl—for Kplong and lots of other cool new content, it's worth installing the latest version. KPL is available as a freeware download from: http://www.kidsprogramminglanguage.com/download.htm. KPL does have a dependency on the .NET Framework 1.1, and the KPL install will automagically download and install the Framework if it is not already installed on your machine.
// Left player's paddle
LeftPlayerY = 225
LoadSprite( "LEFT", "PADDLE.GIF" )
MoveSpriteToPoint( "LEFT", 30, LeftPlayerY )
ShowSprite( "LEFT" )
The LoadSprite() system method takes as parameters the name by which you will refer to the sprite (in this case, "LEFT"), and the file name from which to load the image for the sprite.
The MoveSpriteToPoint() system method takes the name of a Sprite, and the X and Y coordinate at which to place the Sprite. (0, 0) is the upper left corner of the window. This call moves the Sprite to the specified location, but does not yet display it.
The call to ShowSprite() actually causes the named Sprite to be displayed.
Other Sprite-manipulating methods used in Kplong.kpl are:
UnloadSprite() takes the name of the sprite which is to be unloaded when it is no longer needed:
ClearSprites() simply unloads all Sprites at once, effectively clearing the screen:
GetSpriteHeight() returns the height in pixels of the named sprite:
SpritesIntersect() takes the name of two sprites, and returns true only if they intersect or overlap on the screen:
If SpritesIntersect( "BALL", "LEFT" ) Then
That's all the Sprite code you need to know to implement Pong in 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. A KPL game can be implemented in the fraction of the number of lines of code required to implement the game in another language. Hopefully KPL Pong in 180 lines of code proves that point?
This KPL program uses custom images for the ball, the paddle, and for the digits 0 through 9 as used for scoring. Using digit graphics isn't necessary, but was actually easy to code, and also allows a custom Pong-inspired digital font to be used for scoring.
The graphics used in Kplong were created using Paint, which is available as part of all versions of Windows. You can launch paint from Start Menu > All Programs > Accessories > Paint, or by running mspaint.exe from the Run… dialog.
I won't attempt to teach use of Paint in this article, but I will mention that the View > Zoom > Large Size menu option is extremely useful for allowing pixel-level manipulation of an image. The Windows help available within Paint is excellent and very detailed. Any other programs which can produce an image file are also usable, of course.
KPL currently supports .GIF, .JPG, .TIF, .BMP and .PNG file formats. Kplong does not make use of animated GIFs, but KPL does support their use for animating Sprites.
KPL will automatically find an image by file name if the image is in the Media \ Images folder under the KPL install. 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.
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 Kplong's Method Main() which shows how this loop is the basis of the processing for this KPL program:
Define CurrentTime As Decimal
Define TimeLastChecked As Decimal
Alert("Left player uses W and Z keys, Right player uses Up and
Down arrows.", "Get ready!")
While GameOver = False
CurrentTime = TickCount()
// If 25 milliseconds have not passed since the last
// time we checked, we don't do anything yet.
If CurrentTime - TimeLastChecked > 25 Then
// Every 25 milliseconds (that's 40 times a
// second!) we fall into this block. First
// we process Key events to move the paddles
// Then we MoveTheBall. During the Move, we
// also know whether anyone scored a point, and
// if they scored their 10th point, the game is
// We reset the timer each time, so that we
// wait another 25 milliseconds before moving
TimeLastChecked = CurrentTime
The actual processing of key events is done in the ProcessKeyEvents() method, using the IsKeyDown() function:
// Up arrow key moves right player paddle upward
If IsKeyDown("Up") And RightPlayerY > 1 Then
RightPlayerY = RightPlayerY - 10
The key processing code checks for all keys that are relevant to paddle movement, and will handle any and all of them that are down. It also uses logic as shown above so that keys which would cause paddles to move above or below the viewable screen are ignored.
The whole point of Pong, of course, is smacking the bouncing ball back and forth with your paddles. Technically, this is a matter of watching for the ball and paddle sprites to "intersect," and when they do, react by bouncing the ball off of the paddle. As with everything else, KPL makes this ridiculously easy to do—6 lines of KPL code! Here is trimmed code from Method MoveTheBall() which implements this logic:
// If the ball is intersecting either paddle
If SpritesIntersect( "BALL", "LEFT" ) Or SpritesIntersect( "BALL", "RIGHT" ) Then
PlaySound( "Bounce.wav" )
// Since we're processing a paddle hit, the ball bounces by
// changing direction along the X axis
MoveX = MoveX * -1
// Since this was a bounce, we should go ahead and move the
// ball to its new bounced location, heading back the other
// way. This is actually important to keep the ball from
// getting "stuck" in the paddle. Try removing or commenting
// out these two lines and play a few rounds until you see
// the "intercept bounce bug" that will happen without it:
BallX = BallX + MoveX
BallY = BallY + MoveY
MoveSpriteToPoint( "BALL", BallX, BallY )
There are two bits of Kplong logic worth explaining, and worth tinkering with if you are interested. First, the game uses a bit of random "English" to adjust the trajectory of the ball on each bounce. Here's the single line of code that accomplishes this, from Method MoveTheBall():
// We add -1, 0 or 1 to the move along the Y axis, to keep things
MoveY = MoveY - 1 + Random(0, 2)
The trajectory of the ball is a combination of its move along the X axis, and its move along the Y axis. The code above tweaks the Y axis move, and in doing so makes the game at least a little unpredictable. Note that the Random() function does what you would expect—it returns a random value from 0 to 2, inclusive. You can change the parameters on this Random() call to make the English stronger and the game more unpredictable.
You could even program this logic to make the English on the bounce be based upon the movement of the paddle at the time the ball was struck—which would of course be more realistic, and would add a higher level of user control to playing the game, just as English does in real ping pong.
Another important reason to use this line of code is to avoid the "horizontal bounce bug." Consider what would happen if two paddles positioned opposite each other managed to begin a volley with the MoveY equal to 0—the ball would simply bounce back and forth between them and never alter its course. This line of code prevents that from occurring.
A second important bit of logic that keeps things interesting is that Kplong keeps tracks of "volleys" back and forth, and steadily increases the speed of the bouncing ball as volleys progress. KPL gets very interesting as the ball speeds up—and of course this also prevents rounds from lasting a long and boring amount of time. When you play the game, note how engaging and intense this kind of progression is for you as a player—this is a good and a simple technique to keep in mind for other games you develop. The trimmed code which implements this, also in Method MoveTheBall(), is:
// Increment the volley counter
VolleyCount = VolleyCount + 1
// If it's not the first bounce and the ball is moving to the right
If VolleyCount > 1 And MoveX > 0 Then
// Clear the VolleyCount to start counting again
VolleyCount = 0
// And increment the speed of the ball in the X direction
// to speed it up. This steadily increases the speed to keep
// rounds from lasting too long.
MoveX = MoveX + 1
You can, of course, easily tinker with this code by manipulating the If…Then logic, or by changing the MoveX increment to be higher than 1.
Prepare to be humbled by one line of code!
The last fun detail from Kplong that I'd like to show you is how easy a computer opponent can be to implement, for a program like this one. Here's the full logic, from Method MoveTheBall(), that controls your unbeatable computer opponent:
If ComputerPlayer Then
LeftPlayerY = BallY - GetSpriteHeight( "Left" ) / 2
That's right, one line of code will kick your butt. Kplong is, by default, a two-player game—but you can engage the computer opponent by pressing and holding the 'C' key until you see the left paddle begin to move on its own initiative.
An unbeatable computer component isn't fun for long, of course—so let's tinker with this code to give us a chance to win. Here's an algorithm which limits how fast the computer player is able to move the paddle toward the ball—just replace the code above with:
If ComputerPlayer Then
// The paddle is 50 pixels high, so + 25 attempts to keep the
// center of the paddle on the ball.
If BallY < LeftPlayerY + 25 Then
LeftPlayerY = LeftPlayerY - 5
If BallY > LeftPlayerY + 25 Then
LeftPlayerY = LeftPlayerY + 5
This kind of tinkering with the game code is a great example of how KPL can make gaming more fun, too. It's easy to adjust the skill of the computer player to be a very close match to a player's skill.
That's all the Kplong logic I wanted to specifically explain. The full code is there for you in KPL, of course—have fun tinkering with it! Our best hope is that some of you will take this code, modify it in interesting and creative ways, and send it back to us to share with others. Or take some of this logic and apply it to a completely different KPL game! A four-paddle pong version as well as a 3D pong version—yep, 3D—have been written in KPL since this initial Kplong game. Lots of other games have been contributed to the community as well, including Billiards, Yahtzee, Checkers, Simon and some very cool original games. Asteroids, Pinball and lots of others are in the works. Watch for more articles here on Coding4Fun!
Moral of the story? Coding doesn't get more fun than this.