<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Niners/c4f.Jon-Schwartz/Posts/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9</title>
      <link>http://channel9.msdn.com/Niners/c4f.Jon-Schwartz/Posts</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Niners/c4f.Jon-Schwartz/Posts</link>
    <language>en</language>
    <pubDate>Wed, 19 Jun 2013 09:07:28 GMT</pubDate>
    <lastBuildDate>Wed, 19 Jun 2013 09:07:28 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>3</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Kid&#39;s Programming Language: Missile Command!</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">This article is the last of a series in which we are recreating classic video games in KPL code—in this article, Missile Command!</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">Jon Schwartz and Larry Serflaten</div>
<div class="entry_company"><a href="http://blogs.msdn.com/controlpanel/blogs/"></a></div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
1-3 hours</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://www.kidsprogramminglanguage.com/">Kid's Programming Language</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details">
<ul>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>Kid's Programming Language (KPL) is carefully designed to make it easy for beginners to learn to program, but all the things that make KPL easy for beginners also make it easy for
<i>anyone</i> who wants to code fun stuff fast. <b>Missile Command </b>is our loudest, most colorful, and most complex retro KPL example — and if you really need proof that KPL is a lot more than just a beginner language, playing this game will do it. Missile
 Command was coded in KPL by Larry Serflaten, a KPL MVP who has contributed a dozen open source games or programs to the community.</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/999953/kplmissilecom1.gif"></p>
<p>Here are some fun historical links about Missile Command, which Atari released in 1980:</p>
<a href="http://en.wikipedia.org/wiki/Missile_Command">http://en.wikipedia.org/wiki/Missile_Command</a>
<p><a href="http://www.klov.com/game_detail.php?letter=M&amp;game_id=8715">http://www.klov.com/game_detail.php?letter=M&amp;game_id=8715</a></p>
<p><a href="http://www.atariprotos.com/2600/software/missilecommand/missilecommand.htm">http://www.atariprotos.com/2600/software/missilecommand/missilecommand.htm</a>
</p>
<p>The Wikipedia link describes how a legendary high-score run of over six hours ended when the three players got bored and went to the pub! It also mentions that the chip running the 1980 game had a clock speed of 1 MHz — some of us are running chips with
 a clock speed over 3000 times as fast now! That's 12 doubles of clock speed in 26 years, which ironically is a little slow in Moore's Law terms.</p>
<h2>Just the Interesting Stuff, Please</h2>
<p>This article will assume some 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 games:
</p>
<ul>
<li>User-defined structures </li><li>Mouse handling </li><li>Proximity functions </li><li>Implementing smart AI </li><li>Cool end-of-round experience</li></ul>
<p>I will also not repeat topics covered in previous Coding4Fun articles, so if this is the first you have read about KPL and you'd like to catch up on them, they were published in this order:</p>
<a href="http://blogs.msdn.com/coding4fun/coolapplications/KPL/default.aspx">Kid's Programming Language</a>
<a href="http://blogs.msdn.com/coding4fun/gamedevelopment/KPL1/default.aspx">Kid's Programming Language: Pong!</a><a href="http://blogs.msdn.com/coding4fun/holiday/KPL-Xmas1/default.aspx">Kid's Programming Language: Christmas Tree Shooter</a><a href="http://blogs.msdn.com/coding4fun/gamedevelopment/kpl_asteroids/default.aspx">Kid's
 Programming Language: Asteroids!</a>
<p>This Missile Command article will make the most sense if you have installed KPL version 1.1, which includes MissileCommand.KPL in the Games folder. The ideal way to start, of course, is to load MissileCommand.kpl in the KPL IDE, click &quot;Run the program,&quot;
 and play it a few times before examining the code. Prepare to be impressed!</p>
<p>KPL 1.1 is available as a freeware download from <a href="http://www.k-p-l.org/download.htm">
http://www.k-p-l.org/download.htm</a>. 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. If you already have KPL installed and Missile
 Command is not in your games folder, this indicates you don't have the latest version of KPL. For Missile Command and other reasons, it's good to upgrade to 1.1.</p>
<h2>User-Defined Structures</h2>
<p>MissileCommand.kpl uses user-defined structures in a couple of ways. We'll use the
<a href="http://en.wikipedia.org/wiki/Onomatopoeia">http://en.wikipedia.org/wiki/Onomatopoeia</a>Kaboom structure as our example:</p>
<pre><code>Structure Kaboom<br>    Size As Decimal        // Current blast size<br>    Tick As Int            // Start time<br>    Busy As Bool        // Still exploding<br>    X As Int<br>    Y As Int<br>End Structure</code></pre>
<p>In the code below, from method <b>DoExplosions()</b>, <b><code>xpl</code></b> is an instance of the
<b><code>Kaboom</code></b> structure, and used to represent and animate an explosion. This code, processed in a polling loop as it is, causes the explosion to expand outward, and then collapse in size as it fades. As you can see, there's nothing unusual about
 referencing a structure or the fields within it:</p>
<pre><code>MoveTo(xpl.X, xpl.Y)<br>// Calculate size based on time from detonation<br>xpl.Size = Sin((Clock - xpl.tick) / 400.0) * kBlastSize<br>            <br>// Draw sky (to erase explosion)<br>If Clock - xpl.Tick &gt; 550 Then<br>    siz = Sin((Clock - xpl.Tick - 120) / 400.0) * kBlastSize<br>    Color(ColorScheme[kSky])<br>    Circle(siz, True)<br>    xpl.tick = xpl.Tick &#43; 25<br>End If<br><br>// Draw explosion<br>If Clock - xpl.Tick &lt;  1200 Then<br>    Color(BlastColors[Flash])<br>    Circle(xpl.Size , True)<br>End If<br>            <br>// Stop<br>If Clock - xpl.Tick &gt; 1300 Then<br>    xpl.Busy = False<br>End If</code></pre>
<p>&nbsp;</p>
<h2>Mouse Handling</h2>
<p>KPL 1 does support a simple event model for mouse handling:</p>
<pre><code>// MOUSE INPUT<br>Method MouseInput(Event As String, X As Int, Y As Int, Button As Int )<br>    If Event = &quot;ButtonDown&quot; Then<br>        If Y &gt; kOriginY And Y &lt; (kTargetY - (kBlastSize / 2)) Then<br>            ShotX = X<br>            ShotY = Y<br>        Else<br>            AddSound(8, 200, &quot;PowerDown.wav&quot;)<br>End If<br>    End If<br>End Method<br><br>Method MouseLock(Event As String, X As Int, Y As Int, Button As Int )<br>    // Used to refuse mouse input during scoring phase <br>End Method</code></pre>
<p>In <b>Method PlayLevel(),</b> these mouse event handlers are alternately set to enable and disable processing of the mouse clicks:</p>
<pre><code>SetMouseEvent(&quot;MouseInput&quot;)<br><br></code>
<p>. . .</p>


<br><br>// Mouse input locked out for score tally<br>SetMouseEvent(&quot;MouseLock&quot;)</pre>
<h2>Proximity Functions</h2>
<p>Proximity testing is an important enough technique that we thought we'd make an example of it here, particularly since this demonstrates a few other points worth noting in KPL:</p>
<pre><code>Function NearExplosion(X As Int, Y As Int) As Bool<br>Var rsl As Bool<br>Var idx As Int<br>Var len As Int = ArrayLength(Blast)<br>Var dx As Decimal<br>Var dy As Decimal<br>Var hyp As Decimal<br><br>    // Returns True if X, Y is near any explosion<br>    For idx = 1 To len<br>        If Blast[idx].Busy Then<br>            dx = Blast[idx].X - X<br>            dy = Blast[idx].Y - Y<br>            hyp = Sqrt(dx * dx &#43; dy * dy) * 2<br>            rsl = rsl Or (hyp &lt; Blast[idx].size)<br>        End If<br>    Next<br>    Return rsl<br>End Function</code></pre>
<p>First and most obvious is that proper functions are supported and useful in KPL in the usual way, as a method that returns a value. In this case we return a simple Boolean value of whether or not the (X,Y) location is within the blast radius of any of the
 explosions that are currently happening on the screen.</p>
<p>Note the use of <b>ArrayLength()</b>, itself a KPL system function which returns an integer value indicating the length of the specified array.
</p>
<p>The line below does a classic hypotenuse calculation to get the distance between the (X,Y) point and each explosion. Remember a<sup>2</sup> &#43; b<sup>2</sup> = c<sup>2</sup>?</p>
<pre><code>hyp = Sqrt(dx * dx &#43; dy * dy) * 2</code></pre>
<p><b>Sqrt()</b> is another KPL system function, of course, for calculating the square root of a specified value. The * 2 added to the equation allows the hypotenuse distance calculation (a radius measurement) to be compared correctly against the blast size
 (a diameter measurement). We could have used <code>(hyp &lt; (Blast[idx].size/2))</code> on the second line instead.</p>
<h2>Implementing Smart AI</h2>
<p>Here's a cool quote (and cool challenge!) from the original Missile Command developers:
</p>
<p>&quot;These little diamond-shape guys can evade your explosions. The only way you can kill them is if the explosion starts out right on top of them. Programming that was the hardest part. They had to be intelligent because the little guy had to look around on
 the screen to see what he had to avoid and he had to figure out the best path to go around what there was to avoid. Of course, if I made it too smart, then the player couldn't kill it and they'd be guaranteed instant death. So it had to be a fine line between
 smarter than the dumb missiles, yet not totally unkillable.&quot;</p>
<p><a href="http://blogs.msdn.com/ControlPanel/Blogs/%20http://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)">John McCarthy</a> coined the term
<a href="http://en.wikipedia.org/wiki/Artificial_intelligence">&quot;artificial intelligence&quot;</a> at a 1956 conference, the first ever devoted to the topic of machine intelligence. It's obviously a stretch to have one term span from our KPL code for incoming drones
 all the way to <a href="http://en.wikipedia.org/wiki/Deep_Blue">Deep Blue</a>, the IBM computer that beat a chess grand master. We'll stick to our guns, though, while acknowledging that some games require a lot more artificial intelligence than others!</p>
<p>Working on game AI is, for many programmers, one of the most fun challenges in game development: figuring out an algorithm that can reliably crush a human opponent. Muah ha ha! As the quote points out, though, it's also a critically important game design
 point not to overdo it if you actually want people to play your game! Proof of the point is how
<a href="http://www.chesscenter.com/twic/feng.html">Gary Kasparov avoided a rematch</a> after Deep Blue kicked his butt! Moral of the story: your game AI will require testing and adjustment — and you'll always want to aim for a playable point that's hard enough
 but not too hard.</p>
<p>The AI in Missile Command directs the &quot;drones,&quot; the small triangles which will intelligently pick and move toward the nearest live target, avoiding nuclear blasts that are in their path. The methods
<b>PickNearestTarget()</b> and <b>MoveAwayFromBlast()</b> are unsubtle mathematical algorithms with descriptive names (good programming practice, that), so the one we will instead examine is
<b>MoveTowardTarget()</b>:</p>
<pre><code>Method MoveTowardTarget(Drone As Ordinance)<br>Var trg As Int<br>Var mov As Decimal[3] = {-1.0 * kDroneSpeed * Speed, 0.0, 1.0 * <br>  kDroneSpeed * Speed}<br><br>    trg = kTargetsX[Drone.Index]<br>    Drone.DY = Speed * kDroneSpeed<br>    <br>    // Screen boundries<br>    If (Drone.PX &lt; 3) Then<br>        Drone.DX = mov[3]<br>    End If<br>    If (Drone.PX &gt; 697) Then<br>        Drone.DX = mov[1]<br>    End If<br>    <br>    // Very occasional directional change<br>    If Random(1, 50) = 21 Then <br>        Drone.DX = mov[Random(1, 3)]<br>    End If<br>    <br>    // Occasional direction change toward target<br>    If (Random(1, 10) = 7) Or (Drone.PY &gt; 380) Then     <br>        If Drone.PX &gt; (trg &#43; 5) Then<br>            Drone.DX = mov[1]<br>        End If<br>        If Drone.PX &lt; (trg - 5) Then<br>            Drone.DX = mov[3]<br>        End If<br>    End If<br>End Method</code></pre>
<p>Note how the unpredictability in the algorithm is based on x-axis movement, which can be a little to the left, no movement along that axis, or a little to the right. When the Drone has proceeded far enough down the screen to get close to its target —
<code>(Drone.PY &gt; 380)</code> — it will begin to move more directly toward the target. Until then, based on two uses of
<b>Random()</b>, the movement of the drone will have a considerable random element. Experimenting with those uses of
<b>Random()</b> specifically, and more broadly with this algorithm, will give you a sense of the playability impact of very subtle algorithmic changes. Keep that original quote in mind from the Missile Command developers 26 years ago: &quot;It had to be a fine line
 between smarter than the dumb missiles, yet not totally unkillable.&quot;</p>
<h2>End-of-round Scoring</h2>
<p>Missile Command was actually the first arcade game <i>ever</i> to use an end-of-round pause for scoring. If you have good speakers on your computer when you play it, you'll see that the KPL version does a loud and impactful recreation of the original end-of-round.
 Turn it up! <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-2.gif?v=c9' alt='Big Smile' /> </p>
<p>Consider the usefulness of the short break provided by an end-of-round experience. You give the player a short breather and you extend the length of time they play the game, while you keep their attention and interest. Heck, if you do that with as much impact
 and volume as Missile Command does, you are giving them a minor adrenalin jolt even while they're getting a break. End-of-round scoring isn't appropriate for all games, but it is for many.</p>
<p>Below is the <b>TallyScore()</b> method in MissileCommand.kpl. It's ideal to print this out and consider the code alongside the screen as the end-of-round is being processed.
<b>SetFont()</b> is worth noting, as is <b>AddSound()</b>, which is a user-defined method we will also show below:</p>
<pre><code>Function TallyScore() As Bool<br>Var s As Int <br>Var x As Int<br>Var more As Int <br>Var scr As Int <br><br>    SetFont(&quot;Arial&quot;, 18, True, False, False)<br>    Pen(False)<br>    <br>    // Tally missiles<br>    x = 200<br>    For s = 1 To 3<br>        While Silo[s] &gt; 0<br>            Silo[s] = Silo[s] - 1<br>            Score = Score &#43; (Bonus * 5)<br>            scr = scr &#43; (Bonus * 5)<br>            DrawSilo(s)<br>            DrawMissile(x, 160, True)<br>            DrawScore(True)<br>            ScreenPrint(150, 150, scr)<br>            AddSound(10, 0, &quot;mortar1.wav&quot;)<br>            RefreshScreen()<br>            Delay(80)<br>            x = x &#43; 12<br>        End While<br>    Next<br><br>    // Tally cities<br>    x = 215<br>    LiveTargets[5] = False<br>    scr = 0<br>    For s = 2 To 8<br>        If LiveTargets[s] Then<br>            more = more &#43; 1<br>            scr = scr &#43; (100 * Bonus)<br>            Score = Score &#43; (100 * Bonus)<br>            EraseCity(s)<br>            DrawCity(x, 205)<br>            DrawScore(True)<br>            ScreenPrint(150, 200, scr)<br>            AddSound(10, 0, &quot;mortar2.wav&quot;)<br>            RefreshScreen()<br>            Delay(300)<br>            x = x &#43; 60<br>        End If<br>    Next<br>    <br>    // Add bonus cities<br>    scr = 0<br>    LiveTargets[5] = True<br>    While (City &lt;= Score) And (more &lt; 6)<br>    <br>        x = Random(2, 8)<br>        While LiveTargets[x] = True<br>            x = Random(2, 8)<br>        End While<br>        scr = scr &#43; 1<br>        more = more &#43; 1<br>        City = City &#43; kCityBonusTrigger<br>        LiveTargets[x] = True<br>        EraseCity(x)<br>        DrawCity(kTargetsX[x], 436)<br>    End While<br>    <br>    // Print ADDED message<br>    If scr &gt; 0 Then<br>        AddSound(10, 1, &quot;MessageBeep.wav&quot;)<br>        Color(ColorScheme[kMissile])<br>        If scr = 1 Then<br>            MoveTo(265, 300)<br>            Print(scr &#43; &quot; CITY ADDED&quot;)<br>        Else<br>            MoveTo(250, 300)<br>            Print(scr &#43; &quot; CITIES ADDED&quot;)<br>        End If<br>    End If<br>    <br>    // Let player see it a while<br>    Delay(2000)<br><br>    Return (more = 0)<br>End Function</code></pre>
<p><b>AddSound()</b> is a method worth noting because it is easily reusable for other games. It allows sounds to be prioritized as they are played, and it allows sounds to be played for a specific duration before they are replaced with another sound:</p>
<pre><code>Method AddSound(Layer As Int, Duration As Int, File As String)<br>// Plays sound based on priority, and lets them last for some duration<br>    If (Layer &gt;= Priority) Or (Clock &gt; Hold) Then<br>        PlaySound(File)<br>        Priority = Layer<br>        If Duration &gt; 0 Then <br>            Hold = Clock &#43; Duration<br>        Else<br>            Hold = -1<br>        End If<br>    End If<br>End Method</code></pre>
<h2>What's next?</h2>
<p>You know by now I like teasers, right? How does 35 KPL-simple instructions sound, to fly a 3D spaceship model through an interstellar skyscape? KPL version 2, which is now in beta, lets you do exactly that, and a whole lot more. Check it out:</p>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/999953/kplmissilecom2.gif"></p>
<p>And the code:</p>
<pre><code>SwitchTo3D()<br>        <br>Define cam As Camera<br>Define frameTime As Decimal = 0.0<br>        <br>Define sky As Skybox3D<br>sky.LoadMesh( &quot;cell.x&quot; )<br>sky.Scale( 5, 5, 5 )<br>        <br>Define ship As Model3D<br>ship.LoadMesh( &quot;Fighter.x&quot; )<br>ship.MoveTo( 10, 10, 10 )<br>        <br>While Not IsKeyDown( Escape )<br>        <br>    Define startTime As Decimal = TickCount()<br>    Define moveAmount As Decimal = 5 * frameTime<br>            <br>    If IsKeyDown( Left ) Then<br>        ship.TurnLeft( moveAmount )<br>    End If<br>            <br>    If IsKeyDown( Right ) Then<br>        ship.TurnRight( moveAmount )<br>    End If<br>            <br>    If IsKeyDown( Up ) Then<br>        Ship.TiltUP( moveAmount )<br>    End If<br>            <br>    If IsKeyDown( Down ) Then<br>        Ship.TiltDown( moveAmount )<br>    End If<br>            <br>    Ship.Forward( MoveAmount * 5 )<br>            <br>    cam.PointAtModel( Ship )<br>            <br>    RenderFrame()<br>            <br>frameTime = Math.Min( 0.01, (TickCount()-startTime)*0.001 )<br><br>End While</code></pre>
<p>How's that for Coding4Fun? <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-2.gif?v=c9' alt='Big Smile' /> If you would like to know about our future plans for KPL, send e-mail to
<a href="mailto:%20jon@kidsprogramminglanguage.com">mailto:%20jon@kidsprogramminglanguage.com</a>. Thanks to Coding4Fun for this chance to publish a fun series! And thanks to all of you for reading, blogging, and spreading the word!
</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Jon-Schwartz/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:79d06083a75a4c57b8409e7600d910dd">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Missile-Command</comments>
      <itunes:summary>



&amp;nbsp;
This article is the last of a series in which we are recreating classic video games in KPL code—in this article, Missile Command!



Jon Schwartz and Larry Serflaten


Difficulty: Easy
Time Required: 
1-3 hours
Cost: Free
Software: Kid&#39;s Programming Language
Hardware: 









Kid&#39;s Programming Language (KPL) is carefully designed to make it easy for beginners to learn to program, but all the things that make KPL easy for beginners also make it easy for
anyone who wants to code fun stuff fast. Missile Command is our loudest, most colorful, and most complex retro KPL example — and if you really need proof that KPL is a lot more than just a beginner language, playing this game will do it. Missile
 Command was coded in KPL by Larry Serflaten, a KPL MVP who has contributed a dozen open source games or programs to the community. 
 
Here are some fun historical links about Missile Command, which Atari released in 1980: 
http://en.wikipedia.org/wiki/Missile_Command
http://www.klov.com/game_detail.php?letter=M&amp;amp;game_id=8715 
http://www.atariprotos.com/2600/software/missilecommand/missilecommand.htm
 
The Wikipedia link describes how a legendary high-score run of over six hours ended when the three players got bored and went to the pub! It also mentions that the chip running the 1980 game had a clock speed of 1 MHz — some of us are running chips with
 a clock speed over 3000 times as fast now! That&#39;s 12 doubles of clock speed in 26 years, which ironically is a little slow in Moore&#39;s Law terms. 
Just the Interesting Stuff, Please
This article will assume some 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 games:
 

User-defined structures Mouse handling Proximity functions Implementing smart AI Cool end-of-round experience
I will also not repeat topics covered in previous Coding4Fun articles, so if this is the first you have read about K</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Missile-Command</link>
      <pubDate>Mon, 06 Nov 2006 11:52:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Missile-Command</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/999953_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/999953_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Jon Schwartz</dc:creator>
      <itunes:author>Jon Schwartz</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Missile-Command/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Kid&#39;s Programming Language: Asteroids!</title>
      <description><![CDATA[<span id="c4fmetadata">
<table border="0" cellspacing="0" cellpadding="1" width="100%">
<tbody>
<tr class="entry_overview">
<td width="50">&nbsp;</td>
<td><span class="entry_description">This article is the second of a series in which we are recreating classic video games in KPL code—in this article, Asteroids!</span></td>
</tr>
<tr>
<td colspan="2">
<div class="entry_author">Jon Schwartz</div>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
Less than 1 hour</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://www.kidsprogramminglanguage.com/">Kid's Programming Language</a></span></div>
<div class="entry_details"><b>Hardware: </b><span class="entry_details_input"></span></div>
<div class="entry_details"><b>Download: </b><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/KPLAsteroids.msi">Download</a>
<ul>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</span>
<p>Have you seen the previous articles here at Coding4Fun about KPL, the <a href="http://www.kidsprogramminglanguage.com/">
Kid's Programming Language</a>? The overview is <a href="http://blogs.msdn.com/coding4fun/archive/2006/10/31/912456.aspx">
here</a>, and the article on KPL Pong is <a href="http://blogs.msdn.com/coding4fun/archive/2006/11/03/940215.aspx">
here</a>. KPL is not just for kids; it's for anyone who wants to code fun stuff fast. Proving the point, this is the second of a series in which we are recreating classic video games in KPL code—in this article,
<b>Asteroids</b>! Asteroids is a big step up from our Pong example—a lot more code here. Next in the series, by the way?
<b>Missile Command</b>—just like the old days!</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_1.gif" target="_Top"><img title="Click here for larger image" border="0" alt="Click here for larger image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_1_thumb.gif" width="485"></a></p>
<p><b>(Click image to zoom)</b></p>
<p>Here are some fun historical links about Asteroids, which Atari released in 1979:</p>
<p><a href="http://en.wikipedia.org/wiki/Asteroids">http://en.wikipedia.org/wiki/Asteroids</a><u>
</u></p>
<p><a href="http://www.klov.com/game_detail.php?letter=A&amp;game_id=6939">http://www.klov.com/game_detail.php?letter=A&amp;game_id=6939</a><u>
</u></p>
<p><a href="http://www.oilzine.com/features/features_details.asp?ID=49">http://www.oilzine.com/features/features_details.asp?ID=49</a><u>
</u></p>
<p>KLOV.com is, of course, the Killer List of Videogames. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-2.gif?v=c9' alt='Big Smile' /> Check out this historical highlight from the Wiki:</p>
<p>&quot;In March 2004, Portland, Oregon resident <b>Bill Carlton</b> attempted to break the world record for playing an arcade version of
<i>Asteroids</i>, playing over 27 hours before his machine malfunctioned, ending his record run. He scored 12.7 million points, putting him in 5th place in the all-time
<i>Asteroids</i> rankings. In November 1982 <b>Scott Safran</b> set the still unbroken record of 41 million points.&quot;</p>
<p>Oilzine's article entertainingly describes how, in 1961, MIT's Tech Model Railroad Club got their hands on a DEC PDP-1 &quot;minicomputer&quot;—famously small because it was only the size of a large car! —and used it to invent Space War, the first precursor to Asteroids.
 One of them also invented the first joystick just so they could play this game! Talk about Coding4Fun!</p>
<p>Besides Asteroids, Atari also released <a href="http://en.wikipedia.org/wiki/BASIC_Programming">
Basic Programming</a> in 1979—a fun predecessor to KPL. On the one hand, this description of graphical programming support back then makes KPL look pretty good:
</p>
<p>&quot;Graphics&quot; - contains two colored squares that can be manipulated by your program.
</p>
<p>On the other hand, this makes one think: we could program Atari consoles in 1979?! 27 years later, and now no one can program their consoles? Run my own KPL games on my Xbox or Xbox 360 or PS2 or PSP or Nintendo? And in February, when KPL v 2 lets me do
 easy 3D game programming, and use game controllers? I guess if we can't program our consoles now, it's because no one really wanted to do that, right? <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-2.gif?v=c9' alt='Big Smile' /></p>
<p>Sorry, back to Asteroids now. Asteroids.kpl is a lot larger than Pong was, with over 1000 lines in the KPL file, but many of those are white space or comments. As with all KPL games and programs, it's open source, and available for download
</p>
<h2>Just the interesting stuff, please</h2>
<p>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:
</p>
<ul>
<li>Creating new animated sprites<br>
<br>
</li><li>&quot;Stamping&quot; a starfield as a background<br>
<br>
</li><li>Calculating directional vectors<br>
<br>
</li><li>Adjusting game speed based on frame rate<br>
<br>
</li><li>Finding a safe hyperjump spot<br>
<br>
</li><li>Controlling game playability </li></ul>
<p>I will also not repeat topics covered in previous articles, so if this is the first you have read about KPL and would like to catch up on them, they were published in this order:</p>
<p><a href="http://blogs.msdn.com/coding4fun/coolapplications/KPL/default.aspx">Kid's Programming Language</a></p>
<p><a href="http://blogs.msdn.com/coding4fun/gamedevelopment/KPL1/default.aspx">Kid's Programming Language: Pong!</a></p>
<p><a href="http://blogs.msdn.com/coding4fun/holiday/KPL-Xmas1/default.aspx">Kid's Programming Language: Christmas Tree Shooter</a></p>
<p>This Asteroids article will make the most sense if you have installed KPL, and downloaded and unzipped the Asteroids program underneath your KPL install folder. The ideal way to start, of course, is to load Asteroids.kpl in the KPL IDE, click &quot;Run the program,&quot;
 and play it a few times before examining the code. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-1.gif?v=c9' alt='Smiley' /></p>
<p>KPL itself and Asteroids.kpl are available as freeware downloads from: <a href="http://www.kidsprogramminglanguage.com/download.htm">
http://www.kidsprogramminglanguage.com/download.htm</a>. KPL does have a dependency on the .NET Framework 1.1, and the KPL install will &quot;automagically&quot; download and install the Framework if it is not already installed on your machine.
</p>
<h2>Creating New Animated Sprites</h2>
<p>Graphical sprites are easily animated in KPL by using animated GIF files. An animated GIF is a GIF file with multiple &quot;frames&quot; in it, plus supporting data about whether to loop the animation, and how long to display each frame before switching to the next.
 KPL allows programmatic control of those behaviors, giving you a lot more flexibility than &quot;hard-coding&quot; this in the image file, but for a GIF which you want to animate for use on a web page, for instance, you need that control to be explicitly included in
 the GIF itself. </p>
<p>There are various shareware and freeware animated GIF editors available, so I won't recommend just one. The basic process is the same for each: when you create a new animated GIF, you add &quot;frames&quot; to it, and you load in the image file to use for each frame.
 You also tell it how long to display each frame. The animated image we used for Asteroids was of the ship itself—we wanted to give it a minor &quot;pulsing&quot; effect to help it stand out better against the classic Asteroids black-and-white screen. Here are each of
 the frames used, as well as the final animated GIF. We started with the image used for Frame 1 as the base image, and used MSPaint.EXE to modify it slightly to create the images for Frames 2 and 4. Frame 3 is the same image as Frame 1.</p>
<table border="1" rules="all" width="484" frame="box" height="47" cols="5">
<tbody>
<tr valign="top">
<td width="20%"><b>Frame 1</b></td>
<td width="20%"><b>Frame 2</b></td>
<td width="19%"><b>Frame 3</b></td>
<td width="20%"><b>Frame 4</b></td>
<td width="21%"><b>Animated GIF</b></td>
</tr>
<tr valign="top">
<td width="20%"><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_2.gif"></td>
<td width="20%"><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_3.gif"></td>
<td width="19%"><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_2.gif"></td>
<td width="20%"><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_4.gif"></td>
<td width="21%"><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_5.gif"></td>
</tr>
</tbody>
</table>
<br>
<p>Here's the KPL code which loads and controls the timing of the pulsing ship image:</p>
<pre><code>    LoadSprite( &quot;Ship&quot;, &quot;AnimatedShip.gif&quot; )<br>        <br>    Define Timeline As Int[4]<br>    Timeline[1] = 100 // 100 milliseconds is 1/10 of a second<br>    Timeline[2] = 100<br>    Timeline[3] = 100<br>    Timeline[4] = 100<br>        <br>    // Tell KPL to automate it for us, using the timeline <br>    // we created above. True tells KPL to loop the animation.<br>    SetSpriteAnimationTimeline( &quot;Ship&quot;, True, Timeline )</code></pre>
<h2>&quot;Stamping&quot; a Starfield as a Game Background</h2>
<p>Lots of games are set against a starfield, so here's the KPL code from <b>Method DrawStars()</b> that randomly creates and &quot;stamps&quot; a starfield as the background for Asteroids:</p>
<pre><code>    Define I As Int<br>    Define Scale As Decimal<br>        <br>    Clear( Black )<br>    ClearSprites()<br><br>    LoadSprite( &quot;Star&quot;, &quot;Star.gif&quot; )<br>    ShowSprite( &quot;Star&quot; )<br>        <br>    For I = 1 To (ScreenWidth()/4)<br>        MoveSpriteToPoint( &quot;Star&quot;, Random( 1, ScreenWidth()), Random( 1, ScreenHeight()) )<br>        Scale = Random( 1, 100 )<br>        Scale = Scale / 100.0 - 0.1<br>        ScaleSprite( &quot;Star&quot;, Scale )<br>        StampSprite( &quot;Star&quot; )<br>    Next<br>        <br>    UnloadSprite( &quot;Star&quot; )</code></pre>
<p>The code randomly moves the sprite &quot;Star&quot; around the screen, randomly resizing it each time using
<b>ScaleSprite(). </b>At each location, it uses <b>StampSprite()</b> to make it a permanent part of the screen background. This is much more efficient than actually creating and maintaining 500 separate Star sprites, and enables KPL to redraw the background
 automatically as well.</p>
<p>Note the use of <b>ScreenHeight()</b> and <b>ScreenWidth()</b>. Since this game is best played &quot;Maximized,&quot;
<b>ScreenHeight()</b> and <b>ScreenWidth()</b> are system functions used throughout the program to make the display match the user's screen resolution. In this example, we even adjust the number of stars displayed based on the user's
<b>ScreenWidth()</b>, so the starfield density is similar across all screen resolutions.</p>
<h2>Calculating Directional Vectors</h2>
<p>Directional vectors are the basis for nearly all aspects of Asteroids gameplay, including the movement of the asteroids, the movement of the ship, and the path of fired missiles. A directional vector is easily represented as the combination of some amount
 of movement along the <i>x</i> axis and some amount of movement along the <i>y</i> axis—and so the Point structure is a good way to record and work with Vector data:</p>
<pre><code>    Structure Point<br>        X As Decimal <br>        Y As Decimal<br>    End Structure<br>    ...<br>    Define piOver180 As Decimal = (3.14159 / 180.0)<br>    ...<br>    Function CalculateVector( Heading As Decimal ) As Point<br>    <br>        Define Result As Point<br><br>        Heading = (Heading - 90)<br>    <br>        Define theta As Decimal = (Heading * piOver180) * -1<br>        Result.X = Cos( theta )<br>        Result.Y = Sin( theta ) * -1<br>        <br>        Return Result<br><br>    End Function </code></pre>
<p>This is getting into interesting trigonometry, because we must in order to handle directional vectors.
<b>piOver180</b> is a pre-calculated constant that defines &quot;radians per degree.&quot; The
<b>Heading</b> is in degrees, but the <b>Cos()</b> and <b>Sin()</b> functions take radians as a parameter, so
<code>(Heading * piOver180) </code>converts the <b>Heading</b> from degrees to radians for those calls.</p>
<p>Since the &quot;forward&quot; direction of our ship and missile sprites is actually straight up, we subtract 90 from our heading before we perform the vector calculation. And since computer coordinates'
<i>y</i> axis increases downward instead of upward, we also multiply by -1.</p>
<h2>Adjusting Game Speed Based on Frame Rate</h2>
<p>The range in the performance characteristics of computers capable of running KPL is pretty amazing: from eight-year-old machines with no graphics accelerator running Windows 98 to brand-new gaming-optimized 64-bit machines.
<a href="http://en.wikipedia.org/wiki/Moore%27s_law">Moore's Law</a> suggests that some computers running KPL will literally have fifty times as much performance as others. It's critical to accommodate a machine's performance characteristics in any game, or
 else the range of computers capable of playing it will be greatly limited, and the game will quickly become unplayable as new, faster computers become available.</p>
<p>Asteroids.kpl keeps track of a &quot;frame time&quot; and uses it to adjust the game speed as needed. This declaration at the top of the file defines the variable used for this adjustment:</p>
<pre><code>    // Tracks the amount of time it took to draw the last frame, <br>    // which is used in calculating how much to move every sprite<br>    // during each pass through the main game loop.<br>    Define secondsPerFrame As Decimal = 0.0</code></pre>
<p>Code in the main program loop in <b>Method Main()</b> constantly recalculates this value:</p>
<pre><code>    // Keep track of frame count and frame start time for animation<br>    // calculations<br>    startTime = TickCount()<br>    BeginFrame()<br>      <br>    ...<br><br>    // Keep track of the amount of time it took to draw this frame,<br>    // as this value is used to determine the amount of movement for<br>    // the various animation calculations.<br>    endTime = TickCount()<br>    secondsPerFrame = (endTime - startTime) * 0.001</code></pre>
<p>And here is the function that is used to adjust movement distance based on the
<b>secondsPerFrame</b> value. Note that the return value from <code>Min( 85, AmountPerSecond * secondsPerFrame )
</code>can never be more than 85, so that even on slow computers it is the maximum distance moved in pixels. This can result in choppy rather than smooth movement, but at least allows the game to be played:</p>
<pre><code>    // AdjustForFrameRate allows the game objects to move at roughly <br>    // the same speed on computers of any speed, although on slower <br>    // computers which take longer to draw individual frames the <br>    // amount of movement per frame will be higher, and the <br>    // animations will be a little choppier. This is why on very <br>    // slow computers it may look like the animation is &quot;dropping <br>    // frames&quot;, since the ship moves in bigger increments to     <br>    // compensate for the slow frame rate.<br>    Function AdjustForFrameRate( AmountPerSecond As Decimal ) As Decimal<br>        Return Min( 85, AmountPerSecond * secondsPerFrame )<br>    End Function</code></pre>
<h2>Finding a Safe Hyperjump Spot in Real Time</h2>
<p>The Hyperjump button, &quot;H&quot;, will instantly engage the Hyperjump computer, popping your ship momentarily out of spacetime while it computes a safe location to return to spacetime—and saving your butt from that incoming asteroid! When you, the human ship captain,
 fail to engage Hyperjump quickly enough to save your ship, the Hyperjump computer takes over for you, instantly engaging and saving the ship. Each time this happens, the ship and shields take a beating, though. More than a few times and you and your ship aren't
 going to make the jump in time, and the two of you will be a yucky splat on the windshield of some nameless asteroid spinning silently along its monotonous path through the cold vastness of space. Grim! That Hyperjump spot algorithm better be a good one!</p>
<p>The challenge for this one is implementing an algorithm that can do this in real-time, given that dozens of asteroids and dozens of fragments can be spinning and moving across nearby space. Not an easy problem. This is a great example of the difference between
 the way human brains work and computer brains work. It's fairly instantaneous to any of us when we look at an Asteroid field where the largest open space—and therefore the safest spot—is located. Computers can't do that nearly as easily as we can.</p>
<p>The first algorithm I thought about, with the priority being that I needed something to work in real time, was as follows: quickly calculate, for every asteroid displayed, how far it is from all other asteroids. Whichever asteroid is farthest from all other
 asteroids, hyperjump the ship to just &quot;behind&quot; that asteroid, based on the asteroid's trajectory. This was a pretty cool solution, and did indeed work in real time; but it ended up being much more complex code, and having some quirks that made me go with this
 simpler approach:</p>
<pre><code>Method JumpToSafeSpot()<br>    <br>    Define Safe As Bool = False<br>    Define I As Int<br>    Define Distance As Decimal<br>        <br>    While Not Safe<br>            <br>        // Pick a random screen location, not too close to the edge<br>        Ship.X = Random(100,ScreenWidth() - 100)<br>        Ship.Y = Random(75,ScreenHeight() - 75)<br><br>        // Update the status bar message to show why time (might) <br>        // be stopped<br>            Status(&quot;Timespace escape! Hyperjump computer seeking safe jump coordinates!&quot;)<br>            <br>            Safe = True<br>            I = 1<br>            // While the spot is still safe and we haven't <br>            // checked all asteroids<br>            While Safe And I &lt;= MaxAsteroids<br>                // Calculate the distance from this asteroid. <br>                // The &#43; 40 uses the centerpoint of the <br>                // asteroid for the calculation. Note there is<br>                // no SQUARE() function or ^2 operator in <br>                // KPL v 1 - there will be in KPL v 2 – so we<br>                // just multiply<br>                Distance = Sqrt(((Asteroids[I].X &#43; 40 - Ship.X) * (Asteroids[I].X &#43; 40 - Ship.X)) &#43; ((Asteroids[I].Y &#43; 40 - Ship.Y) * (Asteroids[I].Y &#43; 40 - <br><br>Ship.Y)))<br>                // If it's closer than 200 pixels, this is not <br>                // a safe spot<br>                If Distance &lt; 200 Then<br>                    Safe = False<br>                End If<br>                // Increment I to check the next Asteroid<br>                I = I &#43; 1<br>                // If the spot still seems safe, we'll <br>// check the next asteroid<br>            End While<br>            // Clear the status indicator - if we then try <br>            // another spot, this will cause a &quot;blink&quot; effect so <br>            // you, the ship captain, on hold outside of <br>            // normal spacetime, know the hyperjump computer <br>            // is still working on the problem...<br>            Status(&quot;&quot;)<br>        End While<br>        <br>        // We will not exit this method until the ship has been <br>        // placed at a safe location. My testing shows this is<br>        // rarely more than a blink, but since this is based on<br>        // Random(), and since the screen can get crowded, it can<br>        // take a second or more. This is not ideal, but it is <br>        // simple - and the &quot;escape from timespace into a <br>        // hyperjump&quot; story is a pretty good rationalization! :D<br>    End Method</code></pre>
<h2>Controlling game playability</h2>
<p>Playability obviously ought to be the point of any game. The more playable a game is, the more fun people have with it, the more times they play it, the more they tell the friends about it, the more magazines and websites tell people about it, the more famous
 you become as a game developer, the more money you make, the more bizarre obsessions and personality quirks you can indulge in, etc., etc. I'm not thinking of any specific examples when I say that. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-2.gif?v=c9' alt='Big Smile' /></p>
<p>These are some of the reasons why it's important to consider playability from the beginning, and to implement playability controls as &quot;parameters&quot; in the program so they can be easily adjusted by the programmer to make the game as playable as possible. The
 other advantage of doing this, as discussed in previous articles, is that parameters that are tweakable make it easy for
<b>players</b> to adjust gameplay <b>themselves</b>—if they have access to code, as they do with KPL programs. Some people like games faster, some slower. And since they'll be doing that in KPL code, they'll be polishing some programming skills along the way.</p>
<p>Asteroids.KPL does this with numerous gameplay parameters. Changing these values can pretty drastically change the way the game plays:</p>
<p><code>&nbsp;&nbsp;&nbsp; Define MaxHyperJumps As Int = 3 // initial jumps, you get more</code></p>
<pre><code>      // jumps as a bonus, see below<br>    Define ShipLives As Int = 3 // initial ships,  you get more ships<br>        // as a bonus, see below<br><br>    // Asteroid Settings<br>    Define MaxAsteroids As Int = 30 // max number of asteroids on the <br>      // screen at once<br>    Define AsteroidLoadSpeed As Int = 500 // wait time in <br>      // milliseconds for each set of <br>      // asteroids to be sent<br>    Define MaxAsteroidSpeed As Int = 10 // Max Start speed on <br>      // asteroids<br>    Define AsteroidLoadSpeedBonusUpdate As Int = 20 // when a bonus <br>      // is made the game sends more <br>      // asteroids faster<br>    Define MaxAsteroidSpeedBonusUpdate As Int = 1 // when a bonus is<br>      // made the game speeds up some <br>      // of the asteroids<br>    <br>    // Asteroid Fragment Settings<br>    Define MaxAsteroidFrags As Int = 20<br>    Define MinAsteroidFragmentsPerHit As Int = 1<br>    Define MaxAsteroidFragmentsPerHit As Int = 5<br>    Define MaxAsteroidFragSpeed As Int = 10<br>    <br>    // Score Keeping<br>    Define AsteroidsToEndOfGame As Int = 500 // if you hit this many <br>      // Asteroids the game will end <br>      // even if you have ships left<br>    Define LargeAsteroidHitScore As Int = 500 // number of point for<br>      // each asteroid hit<br>    Define SmallAsteroidHitScore As Int = 250 // number of point for <br>      // each Asteroid Fragment hit<br>    Define NewShipBonus As Int = 10000 // you get 1 new ship and 1 <br>      // hyperjump for every <br>      // NewShipBonus points</code></pre>
<p>Most of these are pretty obvious, but I want to mention one in particular, because of its importance to controlling the &quot;pace&quot; of the game. People have different preferences about game pace, but in general, a game should start a little slow and easy, and
 steadily become faster and/or more difficult over time. If that increase happens slowly enough, the user doesn't consciously notice it, but they certainly do get caught up by it and drawn into it. Done right, they're leaning back all comfortable and lazy at
 the start, and by the end of the game they're leaning forward in their chair and banging on the keyboard! Pace also, of course, determines how long a game actually lasts—the faster it gets, the harder it gets, the sooner it will end. One specific parameter
 which I would encourage you to play with in order to see playability difference based on pace is
<b>MaxAsteroidSpeedBonusUpdate</b>. The starting value of 1 cause some asteroid speeds to increase at a 1 pixel per move each time a bonus ship is awarded. This ends up making the game last a fairly long time, and only very incrementally increases the pace
 of the game. Try setting that value to 5, running the game again, and seeing how much difference it makes!</p>
<h2>What's next?</h2>
<p>Your mission, should you choose to accept it, is twofold. </p>
<h3>First, the UFO: </h3>
<p><img border="0" alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_6.gif">
</p>
<p>This sneaky, evil, small and tough-to-shoot alien spaceship was an unpredictable, difficult, and big-bonus-point part of the original asteroids—assuming you managed to kill him before he killed you, of course—and we have not yet put it into this KPL version
 of Asteroids. Right-click, Save Image As... will let you drop the UFO image from this page right into the Asteroids folder.</p>
<h3>Second, the safe spot:</h3>
<p>Can you come up with a really cool real-time algorithm that works better than our
<b>JumpToSafeSpot() </b>code?</p>
<p>Should you take on the KPL code for either of these, and send them back to me, we will be most happy to publish your code, give you lots of kudos, and tell people by the thousands how good of a game developer you are, etc. See above for where that could
 take you. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-2.gif?v=c9' alt='Big Smile' /> Mail me at <a href="mailto:jon@kidsprogramminglanguage.com">jon@kidsprogramminglanguage.com</a> if you come up with code for these—or any other cool KPL code, for that matter!</p>
<p>Moral of the story? Coding4Fun isn't just a name—it's the point!</p>
<p>Ah, a teaser: anyone remember <b>Missile Command</b>? Check it out below. Yes, that's KPL, and yes, the game rocks! Watch for the article here next month!
</p>
<p><img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940231/kpl_asteroids_7.gif" width="485"></p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Jon-Schwartz/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:c680c7d689a642d4afa99e7600d97f72">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Asteroids</comments>
      <itunes:summary>



&amp;nbsp;
This article is the second of a series in which we are recreating classic video games in KPL code—in this article, Asteroids!



Jon Schwartz
Difficulty: Easy
Time Required: 
Less than 1 hour
Cost: Free
Software: Kid&#39;s Programming Language
Hardware: 
Download: Download








Have you seen the previous articles here at Coding4Fun about KPL, the 
Kid&#39;s Programming Language? The overview is 
here, and the article on KPL Pong is 
here. KPL is not just for kids; it&#39;s for anyone who wants to code fun stuff fast. Proving the point, this is the second of a series in which we are recreating classic video games in KPL code—in this article,
Asteroids! Asteroids is a big step up from our Pong example—a lot more code here. Next in the series, by the way?
Missile Command—just like the old days! 
 
(Click image to zoom) 
Here are some fun historical links about Asteroids, which Atari released in 1979: 
http://en.wikipedia.org/wiki/Asteroids
 
http://www.klov.com/game_detail.php?letter=A&amp;amp;game_id=6939
 
http://www.oilzine.com/features/features_details.asp?ID=49
 
KLOV.com is, of course, the Killer List of Videogames.  Check out this historical highlight from the Wiki: 
&amp;quot;In March 2004, Portland, Oregon resident Bill Carlton attempted to break the world record for playing an arcade version of
Asteroids, playing over 27 hours before his machine malfunctioned, ending his record run. He scored 12.7 million points, putting him in 5th place in the all-time
Asteroids rankings. In November 1982 Scott Safran set the still unbroken record of 41 million points.&amp;quot; 
Oilzine&#39;s article entertainingly describes how, in 1961, MIT&#39;s Tech Model Railroad Club got their hands on a DEC PDP-1 &amp;quot;minicomputer&amp;quot;—famously small because it was only the size of a large car! —and used it to invent Space War, the first precursor to Asteroids.
 One of them also invented the first joystick just so they could play this game! Talk about Coding4Fun! 
Besides Asteroids, Atari also relea</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Asteroids</link>
      <pubDate>Fri, 03 Nov 2006 05:57:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Asteroids</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/940231_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/940231_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Jon Schwartz</dc:creator>
      <itunes:author>Jon Schwartz</itunes:author>
      <slash:comments>2</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Asteroids/RSS</wfw:commentRss>
    </item>
  <item>
      <title>Kid&#39;s Programming Language: Pong!</title>
      <description><![CDATA[<span id="c4fmetadata">
<table class="" cellspacing="0" cellpadding="1" width="100%" border="0">
<tbody>
<tr class="entry_overview">
<td class="" width="50">&nbsp;</td>
<td class=""><span class="entry_description">This article is first in series of KPL articles.It presents the KPL code that implements the game shown below—Pong!</span></td>
</tr>
<tr>
<td class="" colspan="2">
<div class="entry_author">Jon Schwartz</div>
<br>
<div class="entry_details"><b>Difficulty: </b><span class="entry_details_input">Easy</span></div>
<div class="entry_details"><b>Time Required:</b> <span class="entry_details_input">
Less than 1 hour</span></div>
<div class="entry_details"><b>Cost: </b><span class="entry_details_input">Free</span></div>
<div class="entry_details"><b>Software: </b><span class="entry_details_input"><a href="http://www.kidsprogramminglanguage.com/">Kid's Programming Language</a></span></div>

</td>
</tr>
</tbody>
</table>
</span>
<p>Welcome to the first article in a series of fun coding projects built using KPL—the
<a href="http://www.kidsprogramminglanguage.com/">Kid's Programming Language</a>! 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—<b>Pong!</b>
 We thought that recreating the first video game ever invented was a good place to begin our series of KPL examples.
</p>
<p><img alt="" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/940215/kpl1_1.gif" border="0"></p>
<p>Here are some fun historical links about Pong:</p>
<p><a href="http://en.wikipedia.org/wiki/PONG">http://en.wikipedia.org/wiki/PONG</a></p>
<p><a href="http://www.pong-story.com/">http://www.pong-story.com/</a></p>
<p><a href="http://www.oilzine.com/features/features_details.asp?ID=49">http://www.oilzine.com/features/features_details.asp?ID=49</a></p>
<p>The original Pong console launched the video game revolution—with home consoles
<i>and</i> 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
<i>lined up</i> 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?
</p>
<p>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? </p>
<h1>Just the interesting stuff, please</h1>
<p>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:
</p>
<ul>
<li>Using Sprites in KPL<br>
<br>
</li><li>Preparing and using custom images<br>
<br>
</li><li>Handling keyboard input<br>
<br>
</li><li>Sprite interaction<br>
<br>
</li><li>Details that keep things interesting<br>
<br>
</li><li>Implementing a computer opponent </li></ul>
<p>Before we begin, the article will make the most sense if you have installed KPL, and have opened the KPL program
<b>Kplong.kpl</b>, which you will find in the <b>KPL Programs &gt; Games</b> folder in KPL's File Explorer. The ideal way to start, of course, is to load Kplong.kpl in the KPL IDE, click &quot;Run the program,&quot; and play it a few times before examining the code. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-1.gif?v=c9' alt='Smiley' /></p>
<p>If you are using a version of KPL from before October 10<sup>th</sup>, 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:
<a href="http://www.kidsprogramminglanguage.com/download.htm">http://www.kidsprogramminglanguage.com/download.htm</a>. 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. </p>
<h1>Using Sprites in KPL</h1>
<pre><code>// Left player's paddle<br>LeftPlayerY = 225 <br>LoadSprite( &quot;LEFT&quot;, &quot;PADDLE.GIF&quot; ) <br>MoveSpriteToPoint( &quot;LEFT&quot;, 30, LeftPlayerY )<br>ShowSprite( &quot;LEFT&quot; )<br></code></pre>
<p>The <b>LoadSprite</b>() system method takes as parameters the name by which you will refer to the sprite (in this case, &quot;LEFT&quot;), and the file name from which to load the image for the sprite.</p>
<p>The <b>MoveSpriteToPoint()</b> 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.</p>
<p>The call to <b>ShowSprite()</b> actually causes the named Sprite to be displayed.</p>
<p>Other Sprite-manipulating methods used in Kplong.kpl are:</p>
<p><b>UnloadSprite()</b> takes the name of the sprite which is to be unloaded when it is no longer needed:</p>
<pre><code>UnloadSprite(&quot;BALL&quot;)<br></code></pre>
<p><b>ClearSprites()</b> simply unloads all Sprites at once, effectively clearing the screen:</p>
<pre><code>ClearSprites()<br></code></pre>
<p><b>GetSpriteHeight()</b> returns the height in pixels of the named sprite:</p>
<pre><code>GetSpriteHeight(&quot;RIGHT&quot;)<br></code></pre>
<p><b>SpritesIntersect()</b> takes the name of two sprites, and returns true only if they intersect or overlap on the screen:</p>
<pre><code>If SpritesIntersect( &quot;BALL&quot;, &quot;LEFT&quot; ) Then<br></code></pre>
<p>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?</p>
<h1>Preparing and using custom images</h1>
<p>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.</p>
<p>The graphics used in Kplong were created using Paint, which is available as part of all versions of Windows. You can launch paint from
<b>Start Menu &gt; All Programs &gt; Accessories &gt; Paint</b>, or by running <b>mspaint.exe</b> from the Run… dialog.</p>
<p>I won't attempt to teach use of Paint in this article, but I will mention that the
<b>View &gt; Zoom &gt; Large Size</b> 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. </p>
<p>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.</p>
<p>KPL will automatically find an image by file name if the image is in the <b>Media \ Images</b> 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.</p>
<h1>Handling keyboard input</h1>
<p>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
<b>Main()</b> which shows how this loop is the basis of the processing for this KPL program:</p>
<pre><code>Method Main()<br>    Define CurrentTime As Decimal <br>    Define TimeLastChecked As Decimal<br>    SetUpGameScreen()<br>Alert(&quot;Left player uses W and Z keys, Right player uses Up and <br>Down arrows.&quot;, &quot;Get ready!&quot;)<br>        <br>    ServeTheBall()<br>    While GameOver = False<br>        <br>        CurrentTime = TickCount()    <br>        <br>        // If 25 milliseconds have not passed since the last <br>        // time we checked, we don't do anything yet.<br>        If CurrentTime - TimeLastChecked &gt; 25 Then<br>            // Every 25 milliseconds (that's 40 times a <br>            // second!) we fall into this block. First<br>            // we process Key events to move the paddles<br>            ProcessKeyEvents()<br>            // Then we MoveTheBall. During the Move, we <br>            // also know whether anyone scored a point, and<br>            // if they scored their 10th point, the game is<br>            // over!<br>            MoveTheBall()<br>                <br>            // We reset the timer each time, so that we <br>            // wait another 25 milliseconds before moving<br>            // again.<br>            TimeLastChecked = CurrentTime<br>        End If<br>            <br>    End While<br>        <br>    ShowWinner()<br>    <br>End Method<br></code></pre>
<p>The actual processing of key events is done in the <b>ProcessKeyEvents()</b> method, using the
<b>IsKeyDown()</b> function:</p>
<pre><code>// Up arrow key moves right player paddle upward<br>If IsKeyDown(&quot;Up&quot;) And RightPlayerY &gt; 1 Then <br>    RightPlayerY = RightPlayerY - 10    <br>End If<br></code></pre>
<p>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.</p>
<h1>Sprite interaction</h1>
<p>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 &quot;intersect,&quot; 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
<b>MoveTheBall()</b> which implements this logic:</p>
<pre><code>// If the ball is intersecting either paddle<br>If SpritesIntersect( &quot;BALL&quot;, &quot;LEFT&quot; ) Or SpritesIntersect( &quot;BALL&quot;, &quot;RIGHT&quot; ) Then<br>    PlaySound( &quot;Bounce.wav&quot; )<br>    // Since we're processing a paddle hit, the ball bounces by <br>    // changing direction along the X axis<br>    MoveX = MoveX * -1 <br>    // Since this was a bounce, we should go ahead and move the <br>    // ball to its new bounced location, heading back the other <br>    // way. This is actually important to keep the ball from <br>    // getting &quot;stuck&quot; in the paddle. Try removing or commenting<br>    // out these two lines and play a few rounds until you see <br>    // the &quot;intercept bounce bug&quot; that will happen without it:<br>    BallX = BallX &#43; MoveX <br>    BallY = BallY &#43; MoveY <br>    MoveSpriteToPoint( &quot;BALL&quot;, BallX, BallY )<br>End If<br></code></pre>
<h1>Details that keep things interesting</h1>
<p>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 &quot;English&quot; to adjust the trajectory of the ball on each bounce. Here's the single line of code that accomplishes this,
 from Method <b>MoveTheBall()</b>:</p>
<pre><code>// We add -1, 0 or 1 to the move along the Y axis, to keep things <br>// interesting<br>MoveY = MoveY - 1 &#43; Random(0, 2)<br></code></pre>
<p>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
<b>Random()</b> function does what you would expect—it returns a random value from 0 to 2, inclusive. You can change the parameters on this
<b>Random()</b> call to make the English stronger and the game more unpredictable.
</p>
<p>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.</p>
<p>Another important reason to use this line of code is to avoid the &quot;horizontal bounce bug.&quot; 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.</p>
<p>A second important bit of logic that keeps things interesting is that Kplong keeps tracks of &quot;volleys&quot; 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<b> MoveTheBall()</b>, is:</p>
<pre><code>// Increment the volley counter<br>VolleyCount = VolleyCount &#43; 1 <br>// If it's not the first bounce and the ball is moving to the right<br>If VolleyCount &gt; 1 And MoveX &gt; 0 Then <br>    // Clear the VolleyCount to start counting again<br>    VolleyCount = 0 <br>    // And increment the speed of the ball in the X direction <br>    // to speed it up. This steadily increases the speed to keep <br>    // rounds from lasting too long.<br>    MoveX = MoveX &#43; 1 <br>End If<br></code></pre>
<p>You can, of course, easily tinker with this code by manipulating the <b>If…Then</b> logic, or by changing the MoveX increment to be higher than 1.</p>
<p>Prepare to be humbled by one line of code!</p>
<p>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<b> MoveTheBall()</b>, that controls your unbeatable computer opponent:</p>
<pre><code>If ComputerPlayer Then <br>    LeftPlayerY = BallY - GetSpriteHeight( &quot;Left&quot; ) / 2<br>End If<br></code></pre>
<p>That's right, one line of code will kick your butt. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-1.gif?v=c9' alt='Smiley' /> 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.</p>
<p>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:</p>
<pre><code>If ComputerPlayer Then <br>    // The paddle is 50 pixels high, so &#43; 25 attempts to keep the <br>    // center of the paddle on the ball.<br>    If BallY &lt; LeftPlayerY &#43; 25 Then<br>        LeftPlayerY = LeftPlayerY - 5<br>    Else<br>        If BallY &gt; LeftPlayerY &#43; 25 Then<br>            LeftPlayerY = LeftPlayerY &#43; 5<br>        End If<br>    End If<br>End If<br></code></pre>
<p>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.</p>
<h1>What's next?</h1>
<p>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
<a href="http://www.ms-inc.net/ViewThread.aspx?ThreadID=353">3D pong version</a>—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!
</p>
<p>Moral of the story? Coding doesn't get more fun than this. <img src='http://ecn.channel9.msdn.com/o9/content/images/emoticons/emotion-1.gif?v=c9' alt='Smiley' /></p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Jon-Schwartz/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:1afc891e0ca741038d0e9e7600d99274">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Pong</comments>
      <itunes:summary>



&amp;nbsp;
This article is first in series of KPL articles.It presents the KPL code that implements the game shown below—Pong!



Jon Schwartz

Difficulty: Easy
Time Required: 
Less than 1 hour
Cost: Free
Software: Kid&#39;s Programming Language






Welcome to the first article in a series of fun coding projects built using KPL—the
Kid&#39;s Programming Language! As you&#39;ll see, KPL is not just for kids—it&#39;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: 
http://en.wikipedia.org/wiki/PONG 
http://www.pong-story.com/ 
http://www.oilzine.com/features/features_details.asp?ID=49 
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&#39;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&#39;s still fun! Oh, if you checked out Oilzine&#39;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?  
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:
 

Using Sprites in KPL

Preparing and using custom images

Handling keyboard input

Sprite interaction

Details that keep things interesting

Implementing a computer opponent 
Before we b</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Pong</link>
      <pubDate>Fri, 03 Nov 2006 05:54:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Pong</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/940215_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/940215_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Jon Schwartz</dc:creator>
      <itunes:author>Jon Schwartz</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Kids-Programming-Language-Pong/RSS</wfw:commentRss>
    </item>    
</channel>
</rss>