<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nicollet.Net &#187; Tutorial</title>
	<atom:link href="http://www.nicollet.net/toroidal/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.nicollet.net</link>
	<description>Everyone Loves Me</description>
	<lastBuildDate>Mon, 23 Jan 2012 16:55:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>99 OCaml Problems</title>
		<link>http://www.nicollet.net/2011/04/99-ocaml-problems/</link>
		<comments>http://www.nicollet.net/2011/04/99-ocaml-problems/#comments</comments>
		<pubDate>Wed, 13 Apr 2011 09:05:21 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Objective Caml]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=2347</guid>
		<description><![CDATA[I find that when learning the basics of a new functional language, or introducing oneself to functional programming in general, the 99 Lisp Problems are a good start. You don&#8217;t have to run through all of them, but how fast you can solve them says a lot about your fluency in the language, and has [...]]]></description>
			<content:encoded><![CDATA[<p>I find that when learning the basics of a new functional language, or introducing oneself to functional programming in general, the <a href="http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html" target="_blank">99 Lisp Problems</a> are a <a href="http://blog.tbueno.com/2011/04/12/programming_problems_to_improve_your_language_skills.html" target="_blank">good start</a>. You don&#8217;t have to run through all of them, but how fast you can solve them says a lot about your fluency in the language, and has many things to teach even to otherwise experienced programmers.</p>
<p>I&#8217;ve started committing solutions to those 99 problems in the Objective Caml language to GitHub ; the repository is:</p>
<p style="padding-left: 30px;"><a href="https://github.com/VictorNicollet/99-Problems-OCaml" target="_blank">https://github.com/VictorNicollet/99-Problems-OCaml</a></p>
<p>If you&#8217;re interested in starting OCaml programming, have read the manual, and are looking for exercises to get up to speed, consider spending a little time trying to come up with the solutions on your own, using my solutions as a reference. And if you&#8217;re an OCaml expert, feel free to propose corrections and improvements : this is what GitHub is for.</p>
<p>Other solutions for OCaml do exist, for instance from <a href="http://www.christiankissig.de/cms/index.php/en/programming/28-ocaml/28-99-problems-in-ocaml" target="_blank">Christian Kissig</a>, which is currently more complete than mine. Note that we don&#8217;t share the same philosophy as far as writing the code goes, so you can probably look at both sides of the issues. For example, on the &#8220;find the last element of a list&#8221; problem, Christian throws an exception if no last element exists, while I return None, because <a href="http://www.nicollet.net/2011/02/exception-avoidance/" target="_blank">I hate exceptions</a>.</p>
<p>Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2011/04/99-ocaml-problems/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>It&#8217;s Payback Time</title>
		<link>http://www.nicollet.net/2011/03/its-payback-time/</link>
		<comments>http://www.nicollet.net/2011/03/its-payback-time/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 02:50:18 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Objective Caml]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=2316</guid>
		<description><![CDATA[I have another problem for you. The European Union has banknotes of values 500€, 200€, 100€, 50€, 20€, 10€ and 5€, and coins of values 2€, 1€, 0.5€, 0.2€, 0.1€, 0.05€, 0.02€ and 0.01€. As you might expect, when you need to pay a certain amount (say, 118€), you give the cashier a few bills [...]]]></description>
			<content:encoded><![CDATA[<p>I have another problem for you. The European Union has banknotes of values 500€, 200€, 100€, 50€, 20€, 10€ and 5€, and coins of values 2€, 1€, 0.5€, 0.2€, 0.1€, 0.05€, 0.02€ and 0.01€. As you might expect, when you need to pay a certain amount (say, 118€), you give the cashier a few bills and coins (1&times;100€ + 1&times;20€) and you get some change back (1&times;2€). For every amount, there exists a perfect transaction which minimizes the number of notes and coins that are exchanged. For 118€, that number is 3 (as shown above). For 5€, it&#8217;s 1 (give a single banknote). For 9€, it&#8217;s 2 (give a 10€, get 1€ back). </p>
<p>Here&#8217;s the question: what is the amount, smaller than 500€, which causes the highest number of notes and coins to be exchanged?</p>
<p>While this could be solved mathematically, I am going to go for a brute-force algorithm because it&#8217;s easier on the mind. The approach consists in exploring all possible transactions of size one (only one note or coin is exchanged) and remember what amounts were available, then construct all transactions of size two (by adding a coin or note to a transaction of size one), and so on until all new transactions end up being for amounts that have already been explored (there are 50001 possible amounts, so the algorithm will inevitably terminate, even if it takes a while). </p>
<p>First, I need a representation of all available coins and notes (in both positive and negative form, because in a transaction they can go either way). I will save some typing by writing some code that generates them:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> values =
  List.concat
    (List.map
       (<span style='color:#7f0055; font-weight:bold; '>fun</span> v -> [ 5*v ; 2*v ; v ; -v ; -2*v ; -5*v ])
       [ 100_00 ; 10_00 ; 1_00 ; 10 ; 1 ])</pre>
<p>This code turns every power of 10 between 10000 (100€) and 1 (0.01€) into a six-item list (for instance, 10 becomes 50, 20, 10, -10, -20, -50), then concatenates all these lists together. The resulting 30-element list contains all 15 notes and coins twice: once positive and once negative.</p>
<p>To represent a transaction (a <i>node</i> in my exploration algorithm) I will define a brand new type that contains the current total in the transaction, the change (a list of notes and coins), and the transaction size (this is actually equal to the length of the change list, but storing it is faster than having to compute it from scratch). The type looks like this:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>type</span> t = { total : <span style='color:#7f0055; font-weight:bold; '>int</span> ; change : <span style='color:#7f0055; font-weight:bold; '>int</span> <span style='color:#7f0055; font-weight:bold; '>list</span> ; count : <span style='color:#7f0055; font-weight:bold; '>int</span> }</pre>
<p>Before I continue, a quick word about complexity: in my algorithm, I expect to do a lot of &#8220;has this node already been explored&#8221; queries, because this is what determines whether I need to stop processing. I also expect the list of explored nodes to grow to a size of 50001, and if I have to run such a query for every single node, I am looking at a minimum of one billion comparisons. This is starting to get a bit too large for my tastes (probably several minutes worth of computations), so I will look into an alternative storage method: sets.</p>
<p>Sets are optimized for quick &#8220;add this element to the set&#8221; and &#8220;is this element in the set?&#8221; operations, running in logarithmic time rather than linear time. This makes the above queries several orders of magnitude faster (expect a 50000-element set to behave about as fast as a 50-element list). In Objective Caml, sets are available as part of the standard library, and can be used by defining a module containing the type you wish to store in the set, then call <code>Set.Make</code> to create a specialized set module dedicated to your type:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>module</span> Node = <span style='color:#7f0055; font-weight:bold; '>struct</span>
  <span style='color:#7f0055; font-weight:bold; '>type</span> t = { total : <span style='color:#7f0055; font-weight:bold; '>int</span> ; change : <span style='color:#7f0055; font-weight:bold; '>int</span> <span style='color:#7f0055; font-weight:bold; '>list</span> ; count : <span style='color:#7f0055; font-weight:bold; '>int</span> }
  <span style='color:#7f0055; font-weight:bold; '>let</span> compare node_1 node_2 = compare node_1.total node_2.total
<span style='color:#7f0055; font-weight:bold; '>end</span>

<span style='color:#7f0055; font-weight:bold; '>module</span> NodeSet = Set.Make(Node)</pre>
<p>Nothing very complex here: my module defines a type named <code>t</code> (as expected by the set module) and a <code>compare</code> function that relies on the built-in compare function to compare the totals (because my actual query is &#8220;was a node with this total explored?&#8221;) so that nodes with equal totals but different transactions are still considered the same.</p>
<p>While I&#8217;m doing this, I will also add two other functions to my node module: a function which adds a coin to a node (this changes the total, prepends the coin to the transaction list, and increments the count), and a function which returns whether the node is valid (its total is between 0€ and 500€). I will also add an empty node from which the exploration will start:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>module</span> Node = <span style='color:#7f0055; font-weight:bold; '>struct</span>

  <span style='color:#7f0055; font-weight:bold; '>type</span> t = { total : <span style='color:#7f0055; font-weight:bold; '>int</span> ; change : <span style='color:#7f0055; font-weight:bold; '>int</span> <span style='color:#7f0055; font-weight:bold; '>list</span> ; count : <span style='color:#7f0055; font-weight:bold; '>int</span> }

  <span style='color:#7f0055; font-weight:bold; '>let</span> compare node_1 node_2 = compare node_1.total node_2.total

  <span style='color:#7f0055; font-weight:bold; '>let</span> add node coin = {
    total  = node.total + coin ;
    change = coin :: node.change ;
    count  = node.count + 1
  }

  <span style='color:#7f0055; font-weight:bold; '>let</span> is_valid node = node.total >= 0 &amp;&amp; node.total &lt;= 500_00

  <span style='color:#7f0055; font-weight:bold; '>let</span> empty = { total = 0 ; change = [] ; count = 0 }

<span style='color:#7f0055; font-weight:bold; '>end</span></pre>
<p>Next, I use the set module to define a &#8220;node is not explored yet&#8221; function:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> is_unknown known node = <span style='color:#7f0055; font-weight:bold; '>not</span> (NodeSet.mem node known)</pre>
<p>Here <code>NodeSet.mem element set</code> is a function which returns true if the element is inside the set (&#8220;mem&#8221; means &#8220;member&#8221;). Based on this function, I can write the &#8220;explore one node&#8221; routine, which consists in adding all possible coin and note values to the node, eliminating any nodes that end up outside the 0€ &#8211; 500€ range and any nodes that have already been explored, and then returning those nodes. Elimination will use the built-in <code>List.filter predicate list</code> function, which keeps only the elements in the list for which the predicate function returns true. My predicates are &#8220;is not explored&#8221; and &#8220;is valid&#8221;:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> explore known node =
  <span style='color:#7f0055; font-weight:bold; '>let</span> reached    = List.map (Node.add node) values <span style='color:#7f0055; font-weight:bold; '>in</span>
  <span style='color:#7f0055; font-weight:bold; '>let</span> valid      = List.filter Node.is_valid reached <span style='color:#7f0055; font-weight:bold; '>in</span>
  <span style='color:#7f0055; font-weight:bold; '>let</span> unexplored = List.filter (is_unknown known) valid <span style='color:#7f0055; font-weight:bold; '>in</span>
  unexplored</pre>
<p>The exploration process is fairly similar to what happened in the previous installment. An unexplored list is kept, and one item is taken from it and explored, which creates new unexplored items. Any items added to the list of unexplored items is also added to the set of known items to avoid duplicates. When the unexplored list runs out (everything has been explored), the set of known items is returned, because it contains all reachable nodes including the largest transaction. In order to make sure the smallest transaction is kept for every amount, the algorithm processes shorter transactions before longer transactions (so that the first transaction for any given total is always the shortest transaction for that total). This is done by appending newly found unexplored elements at the <i>end</i> of the unexplored list. The complete code is:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> <span style='color:#7f0055; font-weight:bold; '>rec</span> process known unexplored =
  <span style='color:#7f0055; font-weight:bold; '>match</span> unexplored <span style='color:#7f0055; font-weight:bold; '>with</span>
    | [] -> explored
    | next :: rest ->
      <span style='color:#7f0055; font-weight:bold; '>let</span> found = explore known next <span style='color:#7f0055; font-weight:bold; '>in</span>
      <span style='color:#7f0055; font-weight:bold; '>let</span> known = List.fold_left (<span style='color:#7f0055; font-weight:bold; '>fun</span> known node -> NodeSet.add node known) known found <span style='color:#7f0055; font-weight:bold; '>in</span>
      process known (rest @ found)</pre>
<p>This is the hardest function of the bunch, and the most complex line is the one that uses <code>List.fold_left</code> to add several new nodes to the set of known nodes. As an interesting side note, the order of the parameters to <code>NodeSet.add</code> is not adapted to the <code>List.fold_left</code> function, which forces me to write an anonymous function that swaps the two arguments it receives. </p>
<p>Once this is written, it&#8217;s a simple matter of calling the function:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> explored = process NodeSet.empty [Node.empty]</pre>
<p>And extracting the maximum using <code>NodeSet.fold</code>, the set equivalent of <code>List.fold_left</code>: </p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> maximum =
  NodeSet.fold
    (<span style='color:#7f0055; font-weight:bold; '>fun</span> node best -> <span style='color:#7f0055; font-weight:bold; '>if</span> node.Node.count > best.Node.count <span style='color:#7f0055; font-weight:bold; '>then</span> node <span style='color:#7f0055; font-weight:bold; '>else</span> best)
    explored Node.empty</pre>
<p>Since the set is sorted in ascending order of node totals, I know that if several transactions have the maximum size, the one with the smallest total amount will be found first and kept as the best. And the result is <strong>333.33€</strong>, for which the optimal transaction consists in giving 500€ and receiving 100€, 50€, 10€, 5€, 1€, 0.5€, 0.1€, 0.05€ and 0.02€ back (<strong>a total of ten coins and banknotes</strong>). The computation, when compiled as an optimized executable, takes 58 seconds on a computer that was average by early 2008 standards.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2011/03/its-payback-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Initial Sequence</title>
		<link>http://www.nicollet.net/2011/03/initial-sequence/</link>
		<comments>http://www.nicollet.net/2011/03/initial-sequence/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 01:30:36 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Objective Caml]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=2312</guid>
		<description><![CDATA[Let&#8217;s play another little game. I&#8217;ll give you a few integers, for instance 225, 318, 529 and 713. I need you to compute all numbers that can be computed by adding those integers together any number of times (for instance, 450 = 225 + 255, 543 = 225 + 318 &#8230;). Of course, there&#8217;s an [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s play another little game. I&#8217;ll give you a few integers, for instance 225, 318, 529 and 713. I need you to compute all numbers that can be computed by adding those integers together any number of times (for instance, 450 = 225 + 255, 543 = 225 + 318 &#8230;). Of course, there&#8217;s an infinite number of them, so I just want you to be able to provide me with, say, the 1000 smallest ones.</p>
<p>How can one solve this? There&#8217;s no simple formula for determining what number comes next, so it boils down to computing enough numbers to be certain that the 1000 smallest values have all been computed, and then sort the result to extract the first 1000.</p>
<p>Finding these numbers looks a lot like exploring a map or maze. From every number, there are four paths one can follow, which consist in adding one of the four initial integers to the current number. So, the paths from 225 lead to 450, 543, 754 and 938. <i>Exploring a number</i> means to write down all four destinations on the map, to be explored later. By definition, all paths lead to higher numbers, which provides a helpful property: if the 1000 smallest integers on the map are all explored, then no path from an unexplored integer can lead to a number smaller than one of those already explored (because that unexplored integer is greater than those 1000 explored ones, and so the path would lead to an even greater integer).</p>
<p>So, the algorithm consists in keeping a list of unexplored numbers and then repeating the following process a thousand times: pick the smallest integer, explore it (adding new numbers to the list of unexplored numbers) and add it to the list of explored items. In the end, the explored list contains 1000 items, sorted from least to greatest, with the guarantee that no unexplored integers can lead to smaller ones.</p>
<p>You might recognize this as a variation on <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm"><b>Dijkstra&#8217;s Algorithm</b></a>.</p>
<p>Writing this down in Objective Caml requires a preliminary decision: how are we going to extract the smallest number from the unexplored list? One way is to keep the list sorted at all times&mdash;this makes extraction easy (pick the first element) but insertion hard (you have to keep the list sorted). Conversely, one may keep the list in random order&mdash;this makes insertion easy (just prepend) but extraction hard (you have to find and remove the minimum). Since the latter is marginally harder than the former, I&#8217;ll go with the first option. Inserting an element into a sorted list is a textbook example of recursive function:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> <span style='color:#7f0055; font-weight:bold; '>rec</span> insert sorted element =
  <span style='color:#7f0055; font-weight:bold; '>match</span> sorted <span style='color:#7f0055; font-weight:bold; '>with</span>
    | [] -> [element]
    | head :: tail -> <span style='color:#7f0055; font-weight:bold; '>if</span> element &lt; head <span style='color:#7f0055; font-weight:bold; '>then</span> element :: sorted
                      <span style='color:#7f0055; font-weight:bold; '>else</span> <span style='color:#7f0055; font-weight:bold; '>if</span> element = head <span style='color:#7f0055; font-weight:bold; '>then</span> sorted
                      <span style='color:#7f0055; font-weight:bold; '>else</span> head :: insert tail element</pre>
<p>The algorithm is fairly straightforward: if the list is empty, return a one-element list containing only the element ; if the first item in the list is greater than the element, then the element goes in first and the rest of the list follows ; if the element is equal to the first item in the list, then return the list as-is to avoid duplicated ; if the element is greater than the first item in the list, then insert recursively that element in the remainder of the list and prepend the original first element to the result.</p>
<p>Then, there&#8217;s the exploration function, which is recursive as well, and expects two arguments: the number of items left to explore, and the list of unexplored elements. The list of explored elements is returned. It is written as:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> values = [ 225; 318; 529; 713 ]

<span style='color:#7f0055; font-weight:bold; '>let</span> <span style='color:#7f0055; font-weight:bold; '>rec</span> explore n = <span style='color:#7f0055; font-weight:bold; '>function</span>
  | [] -> []
  | current :: unexplored ->
    <span style='color:#7f0055; font-weight:bold; '>if</span> n = 0 <span style='color:#7f0055; font-weight:bold; '>then</span> [] <span style='color:#7f0055; font-weight:bold; '>else</span>
      <span style='color:#7f0055; font-weight:bold; '>let</span> new_values = List.map ((+) current) values <span style='color:#7f0055; font-weight:bold; '>in</span>
      current :: explore (n-1) (List.fold_left insert unexplored new_values)</pre>
<p>The exploration function extracts the first element of the unexplored list (if that is empty for some reason, it returns no elements, because there&#8217;s nothing to explore) and computes <code>new_values</code> by adding all the original values to the explored element. This uses the built-in <code>List.map func list</code> which calls <code>func</code> on every item of the list and places it in a new list that is then returned. Here, the function is <code>(+) current</code>, which is a function that adds &#8220;current&#8221; to its argument. So, if the explored element was 225, the returned list would contain 450, 543, 754 and 938.</p>
<p>The code then inserts those four values into the unexplored list by using <code>List.fold_left</code> (which I have already covered yesterday), and recursively calls <code>explore</code> (asking for one less element). It then prepends the current element to the returned list (because it&#8217;s smaller than all the elements to be explored next) and returns everything.</p>
<p>That&#8217;s all! To find the 20 smallest values, one writes:</p>
<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>let</span> smallest_20 = explore 20 values</pre>
<p>These are:</p>
<pre>[225; 318; 450; 529; 543; 636; 675; 713; 754; 768; 847; 861; 900; 938; 954;
 979; 993; 1031; 1058; 1072]</pre>
<p>Any questions? Ask away in the comments section!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2011/03/initial-sequence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gifts</title>
		<link>http://www.nicollet.net/2010/12/gifts/</link>
		<comments>http://www.nicollet.net/2010/12/gifts/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 11:09:36 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Random]]></category>
		<category><![CDATA[Christmas]]></category>
		<category><![CDATA[Humor]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Useless]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=2189</guid>
		<description><![CDATA[Are you having trouble with the search for presents for everyone around you? Worry no longer : this one-page helpful guide will take you through the difficult steps of having a great idea, and provides helpful tips for escaping from the melee on the morning of December 25th. The font used for the headings is [...]]]></description>
			<content:encoded><![CDATA[<p>Are you having trouble with the search for presents for everyone around you? Worry no longer : this <a href="http://www.nicollet.net/wp-content/uploads/2010/12/gifts.png" target="_blank">one-page helpful guide</a> will take you through the difficult steps of having a great idea, and provides helpful tips for escaping from the melee on the morning of December 25th.</p>
<p><a href="http://www.nicollet.net/wp-content/uploads/2010/12/gifts.png"><img width="630" alt="" src="http://www.nicollet.net/wp-content/uploads/2010/12/gifts.png" title="gifts" class="aligncenter size-thumbnail wp-image-2190"/></a></p>
<p><a rel="license" href="http://creativecommons.org/licenses/by/3.0/"><img class="aligncenter" style="border-width: 0;" src="http://i.creativecommons.org/l/by/3.0/88x31.png" alt="Creative Commons License" /></a><br />
The font used for the headings is <a href="http://www.formfett.net/tusj-one-handwritten-font" target="_blank">Tusj</a>, and there&#8217;s a link to a downloadable and printable PDF file <a href="/files/gifts.pdf">here</a>. <strong>And don&#8217;t forget to support the Switzerland</strong>.</p>
<p style="text-align: center;">
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2010/12/gifts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HADOPI</title>
		<link>http://www.nicollet.net/2009/05/hadopi/</link>
		<comments>http://www.nicollet.net/2009/05/hadopi/#comments</comments>
		<pubDate>Wed, 20 May 2009 18:20:35 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Random]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Useless]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=965</guid>
		<description><![CDATA[The HADOPI law was recently adopted by the French parliament. I have an issue with this law: it deals with technical things that few people are knowledgeable in (including most members of parliament) such as the Internet Protocol and the use of IP addresses. So, I have made a small effort on this website to [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/HADOPI_law" target="_blank">HADOPI law</a> was recently adopted by the French parliament. I have an issue with this law: it deals with technical things that few people are knowledgeable in (including most members of parliament) such as the Internet Protocol and the use of IP addresses.</p>
<p>So, I have made a small effort on this website to explain <a href="/useless/hadopi">the basic technical principles underlying the HADOPI law</a> [fr].</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2009/05/hadopi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JITBrain</title>
		<link>http://www.nicollet.net/2009/04/jitbrain/</link>
		<comments>http://www.nicollet.net/2009/04/jitbrain/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 11:11:55 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[JITBrain]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=766</guid>
		<description><![CDATA[Some of you may have wondered, what is this secret project he is working on? The project is called JITBrain. In itself, it&#8217;s nothing quite groundbreaking, merely an issue tracking platform that services two categories of users: Individuals that have a lot to do but never seem to manage it. These are helped by features [...]]]></description>
			<content:encoded><![CDATA[<p>Some of you may have wondered, <em>what is this secret project he is working on</em>?</p>
<p>The project is called JITBrain. In itself, it&#8217;s nothing quite groundbreaking, merely an issue tracking platform that services two categories of users:</p>
<ul>
<li>Individuals that have a lot to do but never seem to manage it. These are helped by features such as extremely simple todo-list manipulation, a search engine for looking at previous tasks and retrieving important information, and helpful statistics.</li>
<li>Teams that must collaborate on projects. These are helped by features such as issue tracking, simple workflows, attached links and files, planning poker, reporting charts, and motivational gizmos.</li>
</ul>
<p>The unusual thing about the project is the development method: it builds upon my earlier ramblings on snippet-oriented development (developing quality software by actively thinking of the people who will read and reuse the code) to actually become an advanced tutorial in itself. This brings yet another benefit, since the code is not only designed in short bursts of concisely explained functionality, but a complete documentation and log is being written along with it.</p>
<p>As such, it has the additional purpose of serving as a simple reference for &#8220;classic mistakes&#8221; both in technical and functional areas in the development of a website.</p>
<p>The tutorial advances along with the development of the system, which means you can <a href="./jitbrain">see the tutorial</a> or <a href="http://jitbrain.nicollet.net" target="_blank">look at the website</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2009/04/jitbrain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The C++ hits you! You feel confused.</title>
		<link>http://www.nicollet.net/2009/04/cpp-confusion/</link>
		<comments>http://www.nicollet.net/2009/04/cpp-confusion/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 05:49:20 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Imperative]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.nicollet.net/?p=597</guid>
		<description><![CDATA[If you&#8217;re reading this post, you&#8217;re probably either a beginner intending to learn C++, a veteran keen on flaming my teaching philosophy, or someone searching for the origin of the &#8220;The foobar hits you! You feel confused.&#8221; Nethack quote. Either way, welcome. I intended this article as a short introductory meta-note about learning C++. It [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re reading this post, you&#8217;re probably either a beginner intending to learn C++, a veteran keen on flaming my teaching philosophy, or someone searching for the origin of the &#8220;The foobar hits you! You feel confused.&#8221; Nethack quote. Either way, welcome.</p>
<p>I intended this article as a short introductory meta-note about learning C++. It should give you some elements that can be helpful in understanding C++ books and tutorials. If you&#8217;re really keen on doing this, I suggest <a href="http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html" target="_blank">Thinking in C++</a> and the <a href="http://www.parashift.com/c++-faq-lite/" target="_blank">C++ FAQ Lite</a>, both of which are freely available online and are quality resources.</p>
<p>And stay away from any tutorials that <em>#include &lt;iostream.h&gt;</em> !</p>
<h3><span id="more-597"></span></h3>
<div style="float:right;border:1px dotted #FFCC88;padding:8px;margin:25px"><strong>Table of contents</strong><br />
- <a href="#benefits">The benefits</a><br />
- <a href="#downsides">The downsides</a><br />
- <a href="#compiling">The compiling process</a><br />
- <a href="#undef">Undefined behavior</a><br />
- <a href="#modern">Modern C++</a></div>
<h3><a name="benefits"></a>The benefits</h3>
<p>Why would someone use C++?</p>
<p><strong>As a project manager:</strong> you probably have existing code written in C++ that you can leverage for your project (or C code that you could interface with), costly tools related to C++ that you don&#8217;t want to buy again for another language, and you might already have a team of C++ programmers that can work on it—so why choose another language?</p>
<p><strong>As an individual programmer:</strong> you might want to be hired by an industry that uses C++ a lot (such as the games industry or front-office investment banking), or it might be the only language you have managed to learn—or the only one you like.</p>
<p>In both cases, you might be constrained to a platform that has no support for other languages you might prefer, or be shoehorned into using a specific language by the project requirements.</p>
<h3><a name="downsides"></a>The downsides</h3>
<p>Why would someone not use C++?</p>
<p><strong>It&#8217;s dangerous</strong>. C++ leaves a huge amount of things undefined, meaning that virtually every large project written in C++ will rely on some specific behavior that is not guaranteed by the language. This leads to unpredictable errors that happen only on certain computers and are extremely difficult to track.</p>
<p>Also, when a part of a C++ program fails, the entire program fails—therefore, if you wish to isolate your program from a subprogram written by someone else, you have to separate them and therefore spend a lot of time on working on communication between the two.</p>
<p>Last but not least, C++ relies on a &#8220;the programmer is always right&#8221; philosophy. If you cannot be up to the task of always being right, you might want to avoid using C++ on a large scale.</p>
<p><strong>It might be awkward for specific situations</strong>. C++ is a general-purpose compiled language, so it certainly does not excel at all tasks. This can be an issue for the programmer himself (text manipulation in C++ lacks all the amenities of PHP and Perl text manipulation), for the organization (the C++ compilation model does not lend itself to short modify-and-test cycles like Lua or Python would) or for the user (no user will install a C++ application to visit a website, but nearly all of them can run JavaScript or ActionScript in their browsers).</p>
<h3><a name="compiling"></a>How C++ code turns into executables</h3>
<p>As a programmer, you write source code. Source code is stored in plain text files—usually with the .cpp extension, to indicate that it&#8217;s C++ code. Text editors (including notepad) can open source code files, but people usually have dedicated source code editors that add many features (such as highlighting relevant parts of programs or smart search-and-replace tool). I use emacs on Linux and Visual C++ Express Edition on Windows—both are free and available online for download.</p>
<p>So, I would write this code (don&#8217;t try to understand the details just yet) :</p>
<pre style="padding-left: 30px;">void print(int x)
{
  ... explain how to show the integer x to the user ...
}

print(2 + 3);</pre>
<p>Then, I use a compiler to create the executable.</p>
<blockquote><p>The C++ compiler is a program that reads a C++ source file and turns it into a program.</p></blockquote>
<p>Well, that&#8217;s not entirely true. The problem is that the average program contains hundreds of thousands of lines of code, and many people work on such programs, which makes it necessary to separate the program into separate source files. What if, for instance, I wanted to let a co-worker use the <em>&#8216;print&#8217;</em> function I&#8217;ve defined above?</p>
<p>Besides, for performance purposes, it would be wise to avoid processing a file that has not changed since the last time it was processed. This has led to the creation of object files.</p>
<blockquote><p>The C++ compiler is a program that reads a C++ source file and turns it into an object file.</p>
<p>The C++ linker is a program that reads several object files and connects them together to form a program.</p></blockquote>
<p>The linking process mostly just sticks the object files together in an executable file. It sometimes performs two additional operations:</p>
<ul>
<li>If an object file uses something provided by another object file (that is, your code uses some code written by another programmer), it connects the two together. This leads to linker errors if a thing is defined  by two object files (which one should be used?) or if it&#8217;s defined by none (it&#8217;s required, but not provided).Here, it finds out that my object file needs &#8216;print&#8217;, and that an object file provided by someone else defines &#8216;print&#8217;, so it connects them.</li>
<li>If an object file provides something that nobody uses, it is often stripped from the resulting executable file to avoid wasting space.</li>
</ul>
<p>We&#8217;re getting close, but we&#8217;re not there yet. There is still one problem: how does the linker know what an object file uses? Using a piece of code usually involves the <em>name</em> of that piece, but a program may involve a lot of pieces with the same name, and therefore needs more information to select one. Therefore, C++ requires the programmer to declare in his code that he&#8217;s using a certain piece of code, along with all appropriate information about that piece.</p>
<p>In the &#8216;print&#8217; example above, you would have to specify a few more details in order to differentiate &#8216;print&#8217; that displays an integer from &#8216;print&#8217; that displays some text. The declaration of my &#8216;print&#8217; would look like this:</p>
<pre style="padding-left: 30px;">void print(int);

print(2 + 3);</pre>
<p>This also has a useful side-effect: since you&#8217;ve given a lot of information about that piece of code, the compiler can determine whether you&#8217;re using correctly or not based on that information. This means that you don&#8217;t have to wait until link-time to find out if you have errors, and the compiler can even give you the lines where the errors happen (the linker often does not have access to line numbers).</p>
<p>As a consequence, the C++ language requires you to <em>always </em>declare objects before you use them (and, of course, defining an object counts as declaring it).</p>
<p>However, all users of my code will have to declare the things that I provide. Wouldn&#8217;t it be easier if I provided them with a list of declarations that they can just copy-paste into their own code? In fact, wouldn&#8217;t it be even easier if the language provided a way of inserting a list of declarations in your source code?</p>
<p>This is precisely what the preprocessor does: it inserts lists of declarations (called header files, which use the .h or .hpp extension) into source files. For instance, I would write:</p>
<pre style="padding-left: 30px;"><span style="color: #ff6600;"><strong>-- myfile.cpp</strong> --</span>

void print(int x)
{
  ... explain how to print x ...
}

<span style="color: #ff6600;"><strong>-- myfile.hpp --</strong></span>

void print(int);

<span style="color: #ff6600;"><strong>-- yourfile.cpp --</strong></span> 

#include "myfile.hpp"
print(2 + 3);</pre>
<p>The &#8216;#include&#8217; tells the preprocessor that it should copy-paste the contents of the &#8216;myfile.hpp&#8217; file right there. This operation happens before the compiler manipulates the file, so that the compiler always sees the transformed file.</p>
<blockquote><p>The preprocessor reads each source file (.cpp) and inserts any header files (.hpp) that the source file includes. The result of preprocessing a source file is called a translation unit.</p>
<p>The compiler reads each translation unit and turns it into a lightweight, optimized representation that is quite close to machine language, and stores it in an object file (.o or .obj) for later reuse.</p>
<p>The linker reads all object files, connects them together to resolve pieces of code references between objects, and eliminates unused pieces. This results in an executable program.</p></blockquote>
<p>There are many variations on the above layout (such as precompiled headers, or libraries), but you don&#8217;t need to know about these yet. Besides, while knowledge of the above is useful to understand error messages and code layout, you don&#8217;t need to do that manually: most compilers actually the entire preprocess-compile-link sequence for you without needing human intervention in the simple cases.</p>
<h3><a name="undef"></a>Undefined Behavior</h3>
<p>Before you advance any further, you need to understand undefined behavior. The C++ language is defined by a standard: a complex document that describes in excruciating detail every single feature of the language and how it should behave. The philosophy of the C++ language is that compilers should have as much latitude as possible in order to generate high-performance executables.</p>
<p>This has led to three levels of description:</p>
<ul>
<li>Standard-defined details must be supported by every C++ compiler in the world. If you rely on these details, your program will work across all platforms that have a standard C++ compiler. For instance, that every opening brace &#8220;(&#8221; should be matched by a closing brace &#8220;)&#8221; is part of the standard.</li>
<li>Implementation-defined details are not specified by the standard, they are left for the compiler writers to determine. The only constraint is that compiler writers must make a decision and document that decision. So, you can rely on these details being defined and safe on every platform, although they will not be the same between platforms. For instance, an integer may require two, four or eight bytes depending on the platform being 16-bit, 32-bit or 64-bits.</li>
<li>Undefined behavior is just undefined. This lets the compiler writers do anything without telling the programmer what they are doing. This can be a compiler warning or error, doing &#8220;what the programmer expects&#8221;, crashing the program, randomly altering values in other parts of the program, and in some cases outright crashing the computer. The blue screen of death and Windows access violations are typical examples of what undefined behavior can lead to.</li>
</ul>
<p>The problem with undefined behavior is that it can indeed do &#8220;what the programmer expects&#8221; while you&#8217;re developing, and then suddenly stop working when you give the program to a friend, reboot your own computer, or are trying to do a demo in front of your investors.</p>
<p>This means that you should never write code unless you are absolutely certain that the standard or your implementation allows it. The natural consequence is that although C++ is an extremely complex and varied language, most expert C++ programmers will only ever use a small subset of C++ that they are intimately familiar with, because straying from these subsets in a safe fashion requires you to spend a lot of time reading the standard and the compiler documentation just to check that what you are doing can be done.</p>
<p>This is also the reason why C++ is not advised as a first language: it&#8217;s easy to write a C++ program that compiles and works on the first run but crashes and burns when you least expect it—writing reliable programs require the programmer maturity to always check with the standard whether the code is safe, and beginners seldom have the will or the ability to check the standard.</p>
<h3><a name="modern"></a>Modern C++</h3>
<p>There are different styles of writing C++. By styles, I do not mean how many spaces each tab contains, where you place your curly braces, how you name your variables or whether you prefix members with &#8220;m_&#8221;. Many people, including experienced programmers (<a href="http://www.nicollet.net/2008/08/cpp-warts/" target="_blank">and me, too</a>), tend to make a fuss about these typographical details, but what ultimately matters is that you should be able to write in whatever style your team needs you to write, to read whatever code your team needs you to read, and that you should choose for your own programs the style which requires the least brainpower on your part to read and write (this tends to be, for me, the default style enforced by my editor).</p>
<p>The style in which most experienced C++ users write is called Modern C++. It relies on a technique known as RAII to avoid forgetting &#8220;always do B after A&#8221; constraints such as &#8220;always release memory after you use it&#8221;, &#8220;always close files after you write them&#8221; and &#8220;always display a frame after rendering it&#8221;. In particular, Modern C++ code never uses the <em>delete</em> operator explicitly, and instead gives memory ownership to scoped objects that will delete it themselves when they go out of scope. By tying a necessary operation (delete memory) to an inevitable event (leave a certain scope), you ensure that the operation always happens.</p>
<p>By contrast, many inexperienced C++ programmers (whether they come from a C background or followed a C tutorial with some C++ details) write in a style known as &#8220;C with classes&#8221;. They take advantage of a small number of C++ features that do not exist in C, but otherwise use C approaches to problems. While this is not, in itself, a problem, it is essential to note that C with classes does not play well with several C++ features, such as exceptions or polymorphism.</p>
<p>Modern C++ adepts tend to find C-with-classes to be counter-productive. This is a subjective statement—someone who writes C-with-classes code can seldom be more productive, because this would require Modern C++ techniques, and learning these takes time. However, someone who masters Modern C++ has access to techniques that can shorten code by an order of magnitude while also keeping it safe and correct (and delegating such boring verification tasks to the computer), making them intrinsically more productive that C-with-classes authors.</p>
<p>Do not expect to &#8220;guess&#8221; Modern C++ on your own—beginners are inevitably drawn to C-with-classes. As you learn, you will inevitably meet Modern C++ programmers who will comment on your code and explain to you that some part is too long and could be shortened by correct application of modern techniques, or that another part is not exception-safe and should be rewritten using safe idioms that Modern C++ provides. Do <strong>not</strong> contradict them without giving their proposal some attention, for even if you do not ultimately listen to their advice, the mere act of trying out what they suggest makes you a better C++ programmer. Over the course of a few years, you will move from a C-with-classes programmer to a Modern C++ programmer, if you have enough Modern C++ programmers around to teach you (in my case, I spent 5 years as a C-with-classes programmer).</p>
<h3>Related Posts</h3>
<ul>
<li><a title="Permanent Link to &quot;An Introduction to C++ Pointers&quot;" rel="bookmark" href="http://www.nicollet.net/2008/09/introduction-to-cpp-pointers/">An Introduction to C++ Pointers</a> : one of the trickiest tricks in the C++ bag (see also <a title="Permanent Link to &quot;Array iterators&quot;" rel="bookmark" href="http://www.nicollet.net/2008/09/array-iterators/">Array iterators</a>)</li>
<li><a title="Permanent Link to &quot;Can references be null?&quot;" rel="bookmark" href="http://www.nicollet.net/2009/11/can-references-be-null/">Can references be null?</a> : the classic example of undefined behavior</li>
<li><a title="Permanent Link to &quot;Member and Non-Member Functions&quot;" rel="bookmark" href="http://www.nicollet.net/2008/12/cpp-functions/">Member and Non-Member Functions</a> : thorny first-class functions in C++</li>
</ul>
<p>Do you know of other benefits or downsides to C++? Do you think everyone should learn, if only for the learning experience? Do you have horror stories of undefined behavior rampaging through code bases? Please leave a comment below!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2009/04/cpp-confusion/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Game Development Tutorial</title>
		<link>http://www.nicollet.net/2008/12/game-development-tutorial/</link>
		<comments>http://www.nicollet.net/2008/12/game-development-tutorial/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 23:00:58 +0000</pubDate>
		<dc:creator>Victor Nicollet</dc:creator>
				<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://r17474.ovh.net/?p=150</guid>
		<description><![CDATA[Creating video games is not easy, but few things are easy: cooking for ten, writing a book or running ten miles are quite difficult as well. The difference is that with games, people don&#8217;t know how to start. To cook for ten people, you know it&#8217;s going to involve shopping for ingredients, using a kitchen [...]]]></description>
			<content:encoded><![CDATA[<p>Creating video games is not easy, but few things are easy: cooking for ten, writing a book or running ten miles are quite difficult as well. The difference is that with games, people don&#8217;t know how to start. To cook for ten people, you know it&#8217;s going to involve shopping for ingredients, using a kitchen to boil, simmer, roast and prepare them, and serve them. Writing a book involves typing on your keyboard until you&#8217;ve written all the hundreds of pages you wanted to write. Running ten miles involves getting your shoes on and going outside.</p>
<p>But how does one start creating a video game? How does the initial idea of a video game translate to an actual program you can run? This step isn&#8217;t the hardest of all steps in game development (far from it) but it deters a lot of otherwise well-motivated wannabes.</p>
<p>As a former game developer (I was the lead programmer for <a href="http://www.int13.net/darklaga.htm" target="_blank">Darklaga : Cannonball Symphony</a>) I will try to answer a few of these questions on the technical side. To this end, I have written a short video game which you can find <a href="http://nicollet.net/files/articles/tutorial/pong.html" target="_blank">here</a>, which happens to be a reimplementation of <a href="http://en.wikipedia.org/wiki/Pong" target="_blank">Pong</a> (one of the earliest video games). In this article, I will discuss video game development using that game as an illustration.</p>
<h2>How Game Development Works</h2>
<p>So, how does a video game get created? It usually follows the same set of steps:</p>
<ul>
<li>A team of designers has a basic idea for a game. it designs most of the high-level details of the game: the look and feel, the various elements and their behavior, win and loss conditions, player controls, and so on.</li>
<li>A team of artists creates the graphics and sounds for the game, using their favorite editors and tools and recording studios, according to the designer&#8217;s vision.</li>
<li>A team of programmers writes the program itself, describing how, where and when the graphics should appear and the sounds should be played, and how the player&#8217;s input affects this, according to the designer&#8217;s vision.</li>
<li>Testers play the game, provide input to the designers, who alter the design to please the testers. The cycle repeats until the testers are happy or money runs out.</li>
<li>A publisher takes the game, packages it, sends it to retail stores and advertises it.</li>
</ul>
<p>Of course, all of this could be done by a single person (Pong), or it could be done by an independent team of five (Darklaga), or it could be done by a professional experienced studio backed by a strong publisher (Red Alert 3).</p>
<p>In an ideal world, you would be able to pitch in an idea, and people would take that idea, create a game from it, publish it and give you a share of the money. This rarely happens in the real world, because games take time to be developed, there&#8217;s limited manpower to go around, and so those few idea-pitcher positions are already taken by people with vast amounts of experience and connections in the business. Tom Sloper has a few quite interesting articles about getting your game done, which you can read <a href="http://www.sloperama.com/advice/idea.htm" target="_blank">here</a>.</p>
<p>So, if you have a great game idea, but neither connections nor experience in the business, you&#8217;re basically stuck with either giving up or doing it yourself. This will involve either convincing a programmer to work for you, or doing the programming yourself. If you want to try programming, read on.</p>
<h2>Programming Games</h2>
<p>Video games are computer programs: contraptions designed and written by programmers to make the computer behave in a certain way. Since programmers tend not to be happy with available tools, they often invent new ways of programming computers, which means there are many ways of creating a video game. For instance, the Pong game I wrote for this article is written using a programming language called Javascript (or ECMAScript, depending on whom you ask). The part of the program responsible for making the ball bounce on the screen edges looks like this:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.y + ball.h &gt; field.h)
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vy = - ball.s } 

<span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.y - ball.h &lt; - field.h)
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vy = ball.s }</pre>
</blockquote>
<p>Different programming languages look different. Sometimes, differences are small, so an equivalent program in the C++ programming language would look like:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span> -&gt; ball.y + ball::h &gt; field::h)
  { <span style="color: #000084; font-weight: bold;">this</span> -&gt; ball.vy = - ball::s } 

<span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span> -&gt; ball.y - ball::h &lt; - field::h)
  { <span style="color: #000084; font-weight: bold;">this</span> -&gt; ball.vy = ball::s }</pre>
</blockquote>
<p>These two are fairly similar, because both C++ and Javascript belong to the same family of languages (called the C family) and therefore share a lot of features and constructs. By contrast, Objective Caml is a programming language of the ML family, and has a quite different take on things:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">method</span> verticalBounce =
  <span style="color: #000084; font-weight: bold;">if</span> y -. Const.ball_h &lt; -. Const.field_h <span style="color: #000084; font-weight: bold;">then</span>
    {&lt; vy = Const.ball_s &gt;}
  <span style="color: #000084; font-weight: bold;">else</span> <span style="color: #000084; font-weight: bold;">if</span> y + Const.ball_h &gt; Const.field_h <span style="color: #000084; font-weight: bold;">then</span>
    {&lt; vy = -. Const.ball_s &gt;}
  <span style="color: #000084; font-weight: bold;">else</span>
    self</pre>
</blockquote>
<p>Different languages have different capabilities. I chose Javascript because it allows running the game in a browser with no downloading or applets. One could choose the ActionScript language to run a video game in a Flash or Flex applet, or the Java language for running a video game in a Java applet, both within a browser. Developing for Windows or the XBox could involve using the C#, F# or VisualBasic.Net languages. Developing for the PC and most consoles can also happen in the C++ and C languages, as well as one of the many BASIC language variants and many others as well. Writing the central server program for multiplayer games could involve the ErLang or Stackless Python programming languages for performance reasons. Writing a video game for a pocket calculator would involve using the assembly language for that calculator. Every programmer know several languages, and chooses whichever best fits the problem he is solving.</p>
<div>
<blockquote><p><em>Code is written for humans to read and only incidentally. for computers to execute.</em><br />
- Donald Knuth</p></blockquote>
</div>
<p>All languages have a thing in common: they&#8217;re human-readable text which the computer does not understand, and as such they necessitate a translation phase where the program, written in a programming language, is transformed into a sequence of machine instructions that the computer can execute. This translation sometimes happens before running the program (done by another program called a <strong>compiler</strong>), and sometimes it happens while running the program (done by another program called an <strong>interpreter</strong>). Some languages, such as C++, tend to be always compiled, while other languages, such as JavaScript, tend to be always interpreted, and many programs are half-compiled and half-interpreted.</p>
<p>Almost everyone has a Javascript interpreter on their computer: Internet Explorer, Firefox and Safari all bundle one, because web pages tend to use Javascript to make their content dynamic and interact with the user. Because of this, all you need to start programming is a text editor (such as Notepad) to edit javascript files and a web browser (such as Internet Explorer) to view the result. I prefer to use improved tools (the <a href="http://www.crimsoneditor.com/" target="_blank">Crimson Editor</a>, <a href="http://www.mozilla.com/en-US/firefox/" target="_blank">Firefox</a> and the <a href="http://getfirebug.com/" target="_blank">Firebug</a> plug-in) because they help me write programs faster.</p>
<div>
<blockquote><p><em>If I have seen further it is only by standing on the shoulders of Giants.</em><br />
- Isaac Newton</p></blockquote>
</div>
<p>A very important aspect of programming (and computer usage in general) is the use of existing tools for accomplishing common tasks. Programmers who regularly solve the same problems eventually write down code to solve these problems, once and for all, and then store that code in code libraries. Sometimes, a library is useful enough that it deserves to be published and used by many other programmers worldwide. For instance, my Pong game needs to move green things around on the screen, which is a fairly common task that is already done by the <a href="http://jquery.com/" target="_blank">jQuery</a> Javascript library. In general, when a programmer has a difficult task to solve, he usually searches for an existing solution on the web before rolling out his own.</p>
<h2>A Programming Primer</h2>
<p>This article is not going to teach you how to program. That would require more space and time than I have here. What it can do, however, is teach a few basic elements of programming in Javascript, which you may also find useful in other languages.</p>
<p>The simplest way of executing Javascript is to write it as part of a web page. For instance:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #7f0055;">&lt;</span><span style="color: #000084; font-weight: bold;">html</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #000084; font-weight: bold;">head</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #000084; font-weight: bold;">title</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #000084; font-weight: bold;">title</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #000084; font-weight: bold;">script</span> type=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">text/javascript</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">&gt;</span>
<span style="color: #808080;">&lt;![CDATA[</span>
   { write your javascript code here }
<span style="color: #808080;">]]&gt;</span>
    <span style="color: #7f0055;">&lt;/</span><span style="color: #000084; font-weight: bold;">script</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;/</span><span style="color: #000084; font-weight: bold;">head</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #000084; font-weight: bold;">body</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #000084; font-weight: bold;">body</span><span style="color: #7f0055;">&gt;</span>
<span style="color: #7f0055;">&lt;/</span><span style="color: #000084; font-weight: bold;">html</span><span style="color: #7f0055;">&gt;</span></pre>
</blockquote>
<p>Save this text with the &#8220;html&#8221; file extension, and start writing Javascript. Open the file in a browser to test it (depending on your security settings, you might have to enable scripts for this to work). Again, I strongly advise you to use the CrimsonEditor/Firefox/Firebug triad for working with Javascript.</p>
<h3>Statements, Variables, Values</h3>
<p>Javascript is an imperative language: it describes sequences of operations to be performed by the computer. Individual operations are called <strong>statements</strong>. For instance, the sentence <span style="font-family: courier new,courier;">$(document).text(&#8220;Hello&#8221;)</span> is an operation which replaces the content of the document with the text &#8220;Hello&#8221;. You can chain several statements together by separating them with semicolons: the statements are then executed in order, left-to-right and top-to-bottom. One very useful statement is the &#8220;alert&#8221; statement, which creates a message box containing some text:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">alert(<span style="color: #0000ff;">"This is my message"</span>)</pre>
</blockquote>
<p>If you&#8217;re using Firebug, you have access to the superior &#8220;console.debug&#8221; option, which is not as nasty as a message box and allows you to output things more complex than text:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">console.debug(<span style="color: #0000ff;">"This is my message"</span>)</pre>
</blockquote>
<p>Programs manipulate values: these can be numbers, lists of other values, pieces of text, parts of a web page, or even parts of a program. The most elementary operation to be performed with a value is to store it in a <strong>variable</strong>: this is useful so that values are kept around when you&#8217;re not using them. A variable is just a name which is associated with a value: you can retrieve that value at any time by writing the variable&#8217;s name, and you can change the value of a variably any time you wish.</p>
<p>Creating a variable uses the &#8220;var&#8221; keyword, which is reserved for that purpose:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> zero = 0</pre>
</blockquote>
<p>This statement creates a variable, called zero, and associates it with the number 0. You can use a variable anywhere you would use its value:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> message = <span style="color: #0000ff;">"This is my message"</span> ;
alert(message)</pre>
</blockquote>
<p>This displays &#8220;This is my message&#8221; in a message box. You can also change the value of a variable after you&#8217;ve created it. That operation is called an assignment:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> message = <span style="color: #0000ff;">"This is my message"</span> ;
alert(message) ;
message = <span style="color: #0000ff;">"On second thought, it isn't"</span> ;
alert(message)</pre>
</blockquote>
<p>This displays &#8220;This is my message&#8221; followed by &#8220;On second thought, it isn&#8217;t&#8221;. The first value assigned to the variable is lost, replaced by the second value assigned to the variable.</p>
<p>You can manipulate values in many fashions. For instance, you can have arithmetic operations (+a, -a, a + b, a &#8211; b, a / b are fairly obvious, a * b is multiplication, and a % b is the remainder of dividing a by b), comparisons (a == b for equality, a != b for inequality, a &lt; b, a &gt; b, a &lt;= b and a &gt;= b), and logical connectors (a &amp;&amp; b : and, a || b: or, !a : not).</p>
<h3>Blocks, Functions</h3>
<p>I have mentioned earlier that you can manipulate parts of a program. The easiest way of doing so (although somewhat limited) is to use <strong>blocks</strong> and <strong>control structures</strong>. A block is zero, one or more statements between curly braces, for instance { a ; b }. A control structure is a special statement which is followed by a block, and executes that block under special circumstances. For example, a <strong>conditional statement</strong> only executes its associated block if a certain condition is true:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">if</span> (age &lt; 13)
{ alert(<span style="color: #0000ff;">"You are not allowed to view this website"</span>)  }</pre>
</blockquote>
<p>Control statements give you control over which statements are executed in certain situations. They are invaluable for expressing complex behavior in your programs. A typical extension of the conditional statement is to also specify something to be done when the condition is not verified:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">if</span> (name == <span style="color: #0000ff;">"John"</span>) { alert(<span style="color: #0000ff;">"Hello, John!"</span>) }
<span style="color: #000084; font-weight: bold;">else</span>                { alert(<span style="color: #0000ff;">"Who are you?"</span>) }</pre>
</blockquote>
<p>By now, you have probably noticed that I position my blocks and statements around randomly. This is indeed the case: Javascript doesn&#8217;t care about the position of your statements and blocks. Just like in English, you can write your sentences every way you wish as long as you don&#8217;t split or swap your words.</p>
<p>Another typical control statement is the <strong>loop</strong>. It executes its associated block repeatedly as long as its condition is true. So, displaying a countdown from 10 to 0 would look like this:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> i = 10 ;
<span style="color: #000084; font-weight: bold;">while</span> (i != 0)
{ alert(i) ; i = i - 1 }</pre>
</blockquote>
<p>The loop displays the number, then substracts one from it, until the number is no longer different from zero.</p>
<p>The improved version of a block is a <strong>function</strong>: a function is, for all purposes, a block that can be manipulated as a value. This means that you can assign it to variables, keep it around, and execute it when you want it to. You create a function from a block by using the &#8220;function()&#8221; keyword in front of that block. You then call functions (which executes the corresponding block) by appending two parentheses after the variable name:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> scare = <span style="color: #000084; font-weight: bold;">function</span>() { alert(<span style="color: #0000ff;">"Boo!"</span>) }; 

<span style="color: #000084; font-weight: bold;">if</span> (surprise)
{ scare() ; alert(<span style="color: #0000ff;">"Sorry for scaring you!"</span>) }
<span style="color: #000084; font-weight: bold;">else</span>
{ alert(<span style="color: #0000ff;">"I'm going to scare you!"</span>) ; scare() }</pre>
</blockquote>
<p>Functions serve several purposed in a program. Their primary purpose is to eliminate repeated code: if you have code which is repeated in several places, turn that code into a function and call the function wherever you need without having to rewrite the code. This even works if you have code that is not identical, but still similar enough:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> i = 1 ;
<span style="color: #000084; font-weight: bold;">var</span> total = 0 ;
<span style="color: #000084; font-weight: bold;">while</span> (i &lt;= 10) { total = total + i }
alert(total) ; 

i = 1 ;
total = 0;
<span style="color: #000084; font-weight: bold;">while</span> (i &lt;= 20) { total = total + i }
alert(total)</pre>
</blockquote>
<p>These two pieces of code compute the sum of numbers between 1 and 10, and between 1 and 20. The only difference here is the number 10 (or 20). It is then possible to make this number a <strong>parameter</strong> of a function: when a function has a parameter, a value for that parameter has to be provided when the function is called. The parameter then becomes a variable associated to that value. In this case:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> sum = <span style="color: #000084; font-weight: bold;">function</span>(max)
{ <span style="color: #000084; font-weight: bold;">var</span> i = 1 ;
  <span style="color: #000084; font-weight: bold;">var</span> total = 0 ;
  <span style="color: #000084; font-weight: bold;">while</span> (i &lt;= max) { total = total + i }
  alert(total) }; 

sum(10) ;
sum(20)</pre>
</blockquote>
<p>A function may have several parameters. If that is the case, then the parameter values must be provided in the same order. Parameters enhance the ability of functions to eliminate repetitive code.</p>
<p>The secondary use of functions is to serve in special situations where one needs to represent a block. For instance, the setTimeout() operation registers a function to be executed after a specified duration. So, for instance:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">alert(<span style="color: #0000ff;">"First message"</span>) ;
setTimeout(<span style="color: #000084; font-weight: bold;">function</span>(){ alert(<span style="color: #0000ff;">"Third message"</span>) }, 3000) ;
alert(<span style="color: #0000ff;">"Second message"</span>)</pre>
</blockquote>
<p>This displays &#8220;First message&#8221;. When that message box is closed, it registers &#8220;Third message&#8221; to be displayed after 3 seconds (3000 milliseconds) and immediately displays &#8220;Second message&#8221;. Another example is jQuery&#8217;s &#8220;when document is loaded&#8221; operation, $():</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">$(<span style="color: #000084; font-weight: bold;">function</span>(){ alert(<span style="color: #0000ff;">"Document has finished loading"</span>) });</pre>
</blockquote>
<p>Note that you can define functions and assign them to a new variable in a single action using an alternative simplified syntax:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">function</span> sum(max)
{ <span style="color: #000084; font-weight: bold;">var</span> i = 1 ;
  <span style="color: #000084; font-weight: bold;">var</span> total = 0 ;
  <span style="color: #000084; font-weight: bold;">while</span> (i &lt;= max) { total = total + i }
  alert(total) }</pre>
</blockquote>
<h3>Objects, Classes</h3>
<p>One other feature of Javascript is the ability to combine several values into one. For example, it&#8217;s interesting to store together in a single variable the horizontal and vertical positions of the ball in a Pong game, yet still be able to access them independently. In Javascript, an <strong>object</strong> is an aggregation of several values: these values are members of the object, and they are given names which allows the program to access them:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> obj = { x : 10, y : 20 } ;
alert (obj.x) ;
alert (obj.y) ;
obj.x = 30 ;
alert (obj.x)</pre>
</blockquote>
<p>This code creates an object with members x (equals 10) and y (equals 20). It then displays the value of member x, then the value of member y. Then, it changes the value of member x, and displays it again. The result is 10, 20, 30.</p>
<p>When it becomes useful to create many objects along the same pattern, as well as define functions which can operate on these objects, Javascript allows you to define classes of objects. A class is a template which allows the creation of objects which have function members that operate on the object. A <strong>class</strong> is a template used for the creation of objects. For instance:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">function</span> number(x)
{ <span style="color: #000084; font-weight: bold;">this</span>.x = x } 

number.<span style="color: #000084; font-weight: bold;">prototype</span>.increase = <span style="color: #000084; font-weight: bold;">function</span>() { <span style="color: #000084; font-weight: bold;">this</span>.x = <span style="color: #000084; font-weight: bold;">this</span>.x + 1 } ; 

number.<span style="color: #000084; font-weight: bold;">prototype</span>.show = <span style="color: #000084; font-weight: bold;">function</span>() { alert(<span style="color: #000084; font-weight: bold;">this</span>.x) } ; 

<span style="color: #000084; font-weight: bold;">var</span> n = <span style="color: #000084; font-weight: bold;">new</span> number(10) ;
n.show() ;
n.increase() ;
n.show()</pre>
</blockquote>
<p>This example introduces several new concepts, which are all necessary to understand classes:</p>
<ul>
<li>The &#8216;prototype&#8217; keyword indicates that the &#8216;number&#8217; function is in fact a class, and defines two functions, &#8216;increase&#8217; and &#8216;show&#8217;, as being members of all objects of class &#8216;number&#8217;.</li>
<li>The &#8216;new&#8217; keyword creates a new object of the &#8216;number&#8217; class. That is, it creates an empty object, then adds every function inside the class prototype to that object. Then, it calls the function &#8216;number&#8217; itself, with the provided parameter values.</li>
<li>The &#8216;this&#8217; keyword acts as a variable. Whenever a member of an object is called,&#8217;this&#8217; becomes equal to that object, so that any operations applied to &#8216;this&#8217; will be applied to the object. When the &#8216;number&#8217; function is called because of the &#8216;new&#8217; keyword, &#8216;this&#8217; becomes equal to the newly created object.</li>
</ul>
<p>In detail, what the example above does is:</p>
<ul>
<li>Define a function called &#8216;number&#8217;.</li>
<li>Decide that &#8216;number&#8217; is in fact a class, and define member functions &#8216;increase&#8217; and &#8216;show&#8217;.</li>
<li>Create a new instance of &#8216;number&#8217; : this creates an object, adds the &#8216;increase&#8217; and &#8216;show&#8217; functions to it, sets &#8216;this&#8217; to that object, and calls &#8216;number&#8217;.</li>
<li>When &#8216;number&#8217; is called, it creates a new member &#8216;x&#8217; and sets it to 10. So, the new object has a member &#8216;x&#8217; equal to 10.</li>
<li>The program calls the &#8216;show&#8217; function. This sets &#8216;this&#8217; to the object, and the function reads the &#8216;x&#8217; member of that object (which equals 10) and displays it.</li>
<li>The program calls the &#8216;increase&#8217; function. This sets &#8216;this&#8217; to the object, and the function adds one to the &#8216;x&#8217; member of that object (so it now equals 11).</li>
<li>The program calls the &#8216;show&#8217; function. This sets &#8216;this&#8217; to the object, and the function reads the &#8216;x&#8217; member of that object (which is now 11) and displays it.</li>
</ul>
<p>Note that the value of &#8216;this&#8217; is restored after a member function returns.</p>
<h3>But I Can&#8217;t Remember All This!</h3>
<p>Of course, you can&#8217;t. This kind of stuff takes time and patience to remember. So, take your time and read it a few times. If you don&#8217;t understand something, try it out to see for yourself what happens. If you really don&#8217;t get it, ask around. I&#8217;m willing to answer questions if you ask them in comments to this entry, and you can always ask questions around the good folks at <a href="http://www.gamedev.net/" target="_blank">gamedev.net</a> anytime. After a few weeks of practice, you&#8217;ll be able to do most of this on your own.</p>
<h2>Game Design</h2>
<p>Before you jump right into coding (and drawing your assets, if applicable) you need to have a fairly complete and detailed description of the game you intend to develop. Otherwise, like a mason without a plan, the house you build is unlikely to ever be finished, and will crash to the ground in strong wind if it is.</p>
<p>The basic requirements for a pong game are as follows:</p>
<ul>
<li>The Pong game contains a square ball and two rectangular paddles.</li>
</ul>
<ul>
<li>The ball moves at a certain speed along both horizontal and vertical axis.</li>
<li>When it hits the top or bottom of the screen, the vertical velocity is reversed.</li>
<li>When it hits the left or right edges of the screen, the horizontal velocity is reversed and the ball is moved to the center (horizontally). The player on the other side gains a point.</li>
<li>When it hits a paddle, the horizontal velocity is reversed.</li>
</ul>
<ul>
<li>Paddles are vertical, and there is one on each side of the screen.</li>
<li>They move up and down at a fixed speed.</li>
<li>When they hit the top or bottom edges of the screen, they stop moving.</li>
<li>They move slightly slower than the ball (so that &#8220;follow the ball&#8221; is not a winning strategy).</li>
<li>The player controls the left paddle, an AI controls the right paddle.</li>
</ul>
<h2>Writing the program</h2>
<p>The game is a large piece of functionality. However, programming only allows us to express small bits of functionality. So, we will have to split up the program in smaller pieces before we can create it.</p>
<p>One common way of splitting things is the MVC architecture. MVC stands for Model/View/Controller, which can be explained like this:</p>
<ul>
<li>The <strong>Model </strong>describes everything that happens behind the scenes. It doesn&#8217;t care about how the game will be displayed on the screen, or how the input from the player will be received. What it cares about is where the ball is, where the paddles are, how the ball should bounce when it hits something, and when scores should increase. This will be an entire object containing all the data required to describe the game, along with functions that compute the movement of the paddles and ball over time.</li>
<li>The <strong>View</strong> describes how the game should be displayed. It doesn&#8217;t really care why the ball and paddles move a certain way: all it cares about is where the ball and paddles are, and which way they are moving. It gets this information from the model, and displays it in one way or another.</li>
<li>The <strong>Controller </strong>is what makes the game interactive: it reads user input in one way or another, generates AI strategies, and enters all that data into the model. Once the model has computed the new positions and scores, it asks the view to draw it, then starts again.</li>
</ul>
<p>Applying MVC splits the program in three parts that are much cleaner and, therefore, potentially easier to create. It&#8217;s usually considered a good first step when designing a program.</p>
<h3>The Model</h3>
<p>Since the view depends on the model, and the controller depends on both the view and the model, the first thing to be implemented is usually the model: it&#8217;s independent of anything else, and so it can be written on its own.</p>
<p>First, there is data to be stored that will change a lot over time:</p>
<ul>
<li>The position of the ball, as the ball&#8217;s velocity.</li>
<li>The vertical position of each paddle, and its vertical velocity.</li>
<li>The score of each player.</li>
</ul>
<p>Then, there&#8217;s also data that will not change:</p>
<ul>
<li>The default horizontal and vertical speed of the ball.</li>
<li>The horizontal position and default vertical speed of the paddles.</li>
<li>The dimensions of the field, ball and paddles.</li>
</ul>
<p>We can store these constants in objects that will never be changed:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> field    = { w: 320, h: 240 };
<span style="color: #000084; font-weight: bold;">var</span> paddle   = { x: 300, w:   2, h:  30, s: 76 };
<span style="color: #000084; font-weight: bold;">var</span> ball     = { w:   5, h:   5, s: 120 };</pre>
</blockquote>
<p>The changing data itself should be stored in a model object, which should store the different categories of model data in sub-objects:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">function</span> model()
{ <span style="color: #000084; font-weight: bold;">var</span> s = ball.s;
  <span style="color: #000084; font-weight: bold;">this</span>.left   = {  pos: 0,   vel: 0 };
  <span style="color: #000084; font-weight: bold;">this</span>.right  = {  pos: 0,   vel: 0 };
  <span style="color: #000084; font-weight: bold;">this</span>.ball   = {    x: 0,     y: 0,
                    vx: s,    vy: s };
  <span style="color: #000084; font-weight: bold;">this</span>.scores = { left: 0, right: 0 }
}</pre>
</blockquote>
<p>Before going on, let&#8217;s discuss a bit all these definitions. Obviously, this code creates a model class with data for left and right paddles, a ball, and scores. Constants are also defined to describe the dimensions of the field, paddles and ball, as well as the default speeds of the ball and paddles. This can be inferred fairly easily from the code if you know JavaScript. The unanswered question is, what do those numbers represent?</p>
<ul>
<li>Since the play field is symmetric, I have chosen coordinates (0,0) to represent the center of the field. This way, the top and bottom edges are at -field.h and field.h respectively (which means the total height of the field is, in fact, 480 pixels and not 240 pixels), the left and right edges are at -field.w and field.w (total width of 640 pixels). In general, the width and height are actually half-widths and half-heights, and the position of an object is in fact the position of its center.</li>
<li>Speeds are expressed in pixels per second. This means that the ball traverses the field vertically in 2 seconds and horizontally in 2.6 seconds, and the paddles traverse the field vertically in a bit more than 3 seconds (all of this is computed without taking the dimensions of the elements into account).</li>
<li>The scores are points. You add one point to the winner&#8217;s score on each round.</li>
</ul>
<p>Initially, everything is centered, and the ball moves to the bottom-right (and since it moves faster than the AI&#8217;s paddle, the AI always loses the first round, but that&#8217;s not really a problem because it lets the player get his bearings for nearly two seconds).</p>
<p>The most elementary thing that can happen to the model is be controlled: this makes the paddles move by changing their velocity. So, when a player presses a key, the velocity changes, and when the key is released the velocity resets to zero. The model doesn&#8217;t care about keys (that is the job of the controller), only about directions, so the movement functions have a direction parameter:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">model.<span style="color: #000084; font-weight: bold;">prototype</span>.moveLeft = <span style="color: #000084; font-weight: bold;">function</span>(d)
{ <span style="color: #000084; font-weight: bold;">this</span>.left.vel  = d * paddle.s }; 

model.<span style="color: #000084; font-weight: bold;">prototype</span>.moveRight = <span style="color: #000084; font-weight: bold;">function</span>(d)
{ <span style="color: #000084; font-weight: bold;">this</span>.right.vel = d * paddle.s };</pre>
</blockquote>
<p>These functions are added to the model class and move the left and right paddle, at the appropriate speed, depending on the direction. Here, we assume that the direction parameter d will equal -1 for &#8220;up&#8221;, 0 for &#8220;don&#8217;t move&#8221; and 1 for &#8220;down&#8221;, and we&#8217;ll have to take care in the controller in order to guarantee that.</p>
<p>The other thing that the model does is make things move. In the computer world, movement is a quick succession of different images which give the illusion of movement (as with <a href="http://www.flipbook.info/" target="_blank">flipbooks</a>). So, instead of working in a continuous motion, the model should skip ahead of time by a certain duration (known as the time step). Here, I&#8217;m going to choose a reasonable timestep: 10 milliseconds (that&#8217;s 100 steps per second):</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> timestep = 0.01;</pre>
</blockquote>
<p>The update function is pretty heavy: it has to move the objects around (to match those 10 milliseconds) then determine if the ball should bounce, if the paddles should stop moving, and if the scores should increase. The entire function is:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">model.<span style="color: #000084; font-weight: bold;">prototype</span>.update = <span style="color: #000084; font-weight: bold;">function</span>()
{
  <span style="color: #000084; font-weight: bold;">var</span> t = timestep; 

  <span style="color: #000084; font-weight: bold;">this</span>.left.pos  += t * <span style="color: #000084; font-weight: bold;">this</span>.left.vel;
  <span style="color: #000084; font-weight: bold;">this</span>.right.pos += t * <span style="color: #000084; font-weight: bold;">this</span>.right.vel;
  <span style="color: #000084; font-weight: bold;">this</span>.ball.x    += t * <span style="color: #000084; font-weight: bold;">this</span>.ball.vx;
  <span style="color: #000084; font-weight: bold;">this</span>.ball.y    += t * <span style="color: #000084; font-weight: bold;">this</span>.ball.vy; 

  <span style="color: #000084; font-weight: bold;">var</span> clip = <span style="color: #000084; font-weight: bold;">function</span>(pad)
  { <span style="color: #000084; font-weight: bold;">var</span> pos = pad.pos;
    pos = Math.<span style="color: #000084; font-weight: bold;">min</span>(pos,field.h - paddle.h);
    pos = Math.<span style="color: #000084; font-weight: bold;">max</span>(pos,paddle.h - field.h);
    <span style="color: #000084; font-weight: bold;">if</span> (pos != pad.pos) pad.vel = 0;
    pad.pos = pos;
  }; 

  clip(<span style="color: #000084; font-weight: bold;">this</span>.left);
  clip(<span style="color: #000084; font-weight: bold;">this</span>.right); 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.y + ball.h &gt; field.h)
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vy = - ball.s } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.y - ball.h &lt; - field.h)
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vy = ball.s } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.x - ball.h &lt; - paddle.x + paddle.w &amp;&amp;
      <span style="color: #000084; font-weight: bold;">this</span>.ball.x + ball.h &gt; - paddle.x - paddle.w &amp;&amp;
      <span style="color: #000084; font-weight: bold;">this</span>.ball.y + ball.h &gt; <span style="color: #000084; font-weight: bold;">this</span>.left.pos - paddle.h &amp;&amp;
      <span style="color: #000084; font-weight: bold;">this</span>.ball.y - ball.h &lt; <span style="color: #000084; font-weight: bold;">this</span>.left.pos + paddle.h )
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vx = ball.s } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.x - ball.h &lt; paddle.x + paddle.w &amp;&amp;
      <span style="color: #000084; font-weight: bold;">this</span>.ball.x + ball.h &gt; paddle.x - paddle.w &amp;&amp;
      <span style="color: #000084; font-weight: bold;">this</span>.ball.y + ball.h &gt; <span style="color: #000084; font-weight: bold;">this</span>.right.pos - paddle.h &amp;&amp;
      <span style="color: #000084; font-weight: bold;">this</span>.ball.y - ball.h &lt; <span style="color: #000084; font-weight: bold;">this</span>.right.pos + paddle.h)
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vx = - ball.s }  

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.x - ball.h &lt; -field.w)
  { <span style="color: #000084; font-weight: bold;">this</span>.scores.right++;
    <span style="color: #000084; font-weight: bold;">this</span>.ball.x = 0;
    <span style="color: #000084; font-weight: bold;">this</span>.ball.vx = ball.s } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.x + ball.h &gt; field.w)
  { <span style="color: #000084; font-weight: bold;">this</span>.scores.left++;
    <span style="color: #000084; font-weight: bold;">this</span>.ball.x = 0;
    <span style="color: #000084; font-weight: bold;">this</span>.ball.vx = - ball.s } 

};</pre>
</blockquote>
<p>Let&#8217;s go through it step-by-step:</p>
<ul>
<li>First, it moves objects around. This is done by adding (+=) the moved distance (t * speed) to the position of objects. This computes the final position of objects after that step. The next steps then handle collisions.</li>
<li>The first collision test is handled by the &#8220;clip&#8221; function, which prevents the paddles from leaving the screen (it&#8217;s a function because there are two paddles, so I created it once and used it for both paddles). The basic rule is: clip the paddle to the screen and, if it went outside, set its speed to zero. Since the position of the paddle is the position of its center, I have to take the height of the paddle into account in order to avoid leaving the field.</li>
<li>The next two collision tests happen between the ball and the top and bottom edges of the field: if the ball went beyond these, the vertical speed is set so that the ball moves back into the field.</li>
<li>The next two collision tests happen between the ball and the paddles. It tests whether the ball-rectangle hits the paddle-rectangle by checking whether any of them intersect (collision detection is a <a href="http://www.harveycartel.org/metanet/tutorials/tutorialA.html" target="_blank">topic in itself</a>) and if they do, sets the horizontal speed to move back into the field.</li>
<li>The last two collision tests check if the ball leaves the field on either side. When this happens, the score of the corresponding player is increased (++), the ball is moved to the center (x=0) and its speed is reversed.</li>
</ul>
<p>So, if we call the &#8220;update&#8221; function, it computes the state of the game after 10 milliseconds. If we do it often enough, we can get the game state in real time. Now, we have to display it.</p>
<h3>The View</h3>
<p>The view is the part of the program responsible for displaying things to the player. It reads data from the model, and somehow maps it to whatever display techniques the program has.</p>
<p>In this example, I&#8217;m using the jQuery library. It allows the program to resize and move around DIV elements of a web page (by default, a DIV element is a rectangle with a set position). So, the first step I will take is create the HTML page which will be manipulated by the view:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">html</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">head</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">title</span><span style="color: #7f0055;">&gt;</span>Pong<span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">title</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">script</span> type=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">text/javascript</span><span style="color: #0000ff;">"</span> src=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">jquery.js</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">script</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">script</span> type=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">text/javascript</span><span style="color: #0000ff;">"</span> src=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">pong.js</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">script</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">style</span><span style="color: #7f0055;">&gt;</span>
#playfield {
  color           : black;
  background-color: black;
  border          : 0px none black;
  margin          : 0px;
  padding         : 0px;
  position        : absolute;
  top             : 0px;
  left            : 0px }
div {
  font-size       : 1px;
  color           : white;
  background-color: #33FF33;
  margin          : 0px;
  padding         : 0px;
  position        : absolute;
  top             : 0px;
  left            : 0px }
div.score {
  color           : #33FF33;
  background-color: transparent;
  width           : 640px;
  font-size       : 20px;
  font-family     : courier new }
  <span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">style</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">head</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">body</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">input</span> id=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">playfield</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">/&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span> id=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">paddle_left</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">/&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span> id=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">paddle_right</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">/&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span> class=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">score</span><span style="color: #0000ff;">"</span> style=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">text-align:left</span><span style="color: #0000ff;">"</span> id=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">score_left</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">&gt;</span>0<span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span> class=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">score</span><span style="color: #0000ff;">"</span> style=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">text-align:right</span><span style="color: #0000ff;">"</span> id=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">score_right</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">&gt;</span>0<span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span>
    <span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span><span style="color: #7f0055;">&lt;</span><span style="color: #7f0055;">div</span> id=<span style="color: #0000ff;">"</span><span style="color: #0000ff;">ball</span><span style="color: #0000ff;">"</span><span style="color: #7f0055;">/&gt;</span><span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">div</span><span style="color: #7f0055;">&gt;</span>
  <span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">body</span><span style="color: #7f0055;">&gt;</span>
<span style="color: #7f0055;">&lt;/</span><span style="color: #7f0055;">html</span><span style="color: #7f0055;">&gt;</span></pre>
</blockquote>
<p>This creates several rectangles, with identifiers, and also determines their color and margin. Note that the playfield is an &#8220;input&#8221; (because we need to receive input from the player, so we use this object as a trick). Also, all &#8220;div&#8221; elements are within &#8220;div&#8221; elements, to prevent their relative positions from influencing each other (because several elements with an absolute position are within the same body).</p>
<p>Most of the above should be fairly obvious to you (if it isn&#8217;t you can peek at a few online courses: <a href="http://www.w3schools.com/html/DEFAULT.asp" target="_blank">html</a> and <a href="http://www.w3schools.com/css/DEFAULT.asp" target="_blank">css</a>).</p>
<p>A point of interest here is the fact that the HTML file includes our script (pong.js) as well as the jQuery script (jquery.js). You can download jQuery <a href="http://jquery.com/" target="_blank">here</a>.</p>
<p>what is interesting about jQuery is that it allows selecting the objects quite easily, and then telling them to do things such as moving. An extremely important function in the view is this:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> move = <span style="color: #000084; font-weight: bold;">function</span>(avatar,pos,spd,size)
{ <span style="color: #000084; font-weight: bold;">var</span> x = pos.x - size.w + field.w;
  <span style="color: #000084; font-weight: bold;">var</span> y = pos.y - size.h + field.h;
  avatar.stop()
    .css({left:x,top:y})
    .animate({left:x+10*spd.vx, top:y+10*spd.vy},10000,<span style="color: #0000ff;">"linear"</span>);
};</pre>
</blockquote>
<p>This function has four parameters: the &#8216;avatar&#8217; is a jQuery object representing one of the &#8220;div&#8221; elements above (the ball, a paddle etc), the &#8216;pos&#8217; is the position (with x and y coordinates) where that object should be, &#8216;spd&#8217; is the velocity (with vx and vy coordinates) with which the object moves, and &#8216;size&#8217; is the dimensions (with w and h coordinates) of that object. The dimensions are required because the position of a jQuery object (with &#8216;absolute&#8217; positioning, as we are using here) is expressed as an offset between the top-left corner of the screen and the top-left container of the object itself, whereas the position in the model is the offset between the center of the playing field and the center of the object. So, variables &#8216;x&#8217; and &#8216;y&#8217; are computed to represent the object&#8217;s position on the HTML page.</p>
<p>This function stops the current movement of the avatar with &#8216;stop()&#8217; then sets the left and top coordinates with &#8216;css()&#8217;, and finally asks the object to move with &#8216;animate()&#8217; by specifying the destination (which we compute by adding the distance traversed in ten seconds to the current position), the duration (10 seconds = 10000 milliseconds) and the animation style (&#8220;linear&#8221;, which means there are no accelerations and no brakes).</p>
<p>In short, this function should be called whenever the movement of an object <em>changes</em>: jQuery then takes care of animating the object until its movement changes again. This way, we don&#8217;t have to change the movement of objects every ten milliseconds.</p>
<p>However, this requires the view to store the previous value of movement, in order to determine when movement changes by comparing the new value and the old value (if they&#8217;re the same, no changes happened). So, the view object would look like this:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">function</span> view()
{ <span style="color: #000084; font-weight: bold;">this</span>.ball   = {   vx: <span style="color: #000084; font-weight: bold;">null</span>,    vy: <span style="color: #000084; font-weight: bold;">null</span> };
  <span style="color: #000084; font-weight: bold;">this</span>.scores = { left:    0, right:    0 };
  <span style="color: #000084; font-weight: bold;">this</span>.paddle = { left: <span style="color: #000084; font-weight: bold;">null</span>, right: <span style="color: #000084; font-weight: bold;">null</span> };
  <span style="color: #000084; font-weight: bold;">this</span>.avatar = { ball: $(<span style="color: #0000ff;">'div#ball'</span>),
                  sc_l: $(<span style="color: #0000ff;">'div#score_left'</span>),
                  sc_r: $(<span style="color: #0000ff;">'div#score_right'</span>),
                  pa_l: $(<span style="color: #0000ff;">'div#paddle_left'</span>),
                  pa_r: $(<span style="color: #0000ff;">'div#paddle_right'</span>),
                  play: $(<span style="color: #0000ff;">'input#playfield'</span>) }; 

  <span style="color: #000084; font-weight: bold;">this</span>.avatar.ball.width(1.9*ball.w)  .height(1.9*ball.h);
  <span style="color: #000084; font-weight: bold;">this</span>.avatar.pa_l.width(1.9*paddle.w).height(1.9*paddle.h);
  <span style="color: #000084; font-weight: bold;">this</span>.avatar.pa_r.width(1.9*paddle.w).height(1.9*paddle.h);
  <span style="color: #000084; font-weight: bold;">this</span>.avatar.play.width(2*field.w)   .height(2*field.h);
}</pre>
</blockquote>
<p>This class does the following things:</p>
<ul>
<li>It defines members &#8220;ball&#8221;, and &#8220;paddle&#8221; which contain the velocities (but not positions) of paddles and the ball. So, when velocities change, the view notices and asks jQuery to change the trajectories. It also defines the currently displayed score (so that, when these change, they are updated).</li>
<li>It defines the avatars: this is done by using the jQuery selector: <span style="font-family: courier new,courier;">$(&#8216;div#paddle_left&#8217;)</span> selects the DIV element with the identifier &#8216;paddle_left&#8217; that we defined in the HTML page earlier.</li>
<li>It resizes the avatars based on the constants, with the functions &#8216;width()&#8217; and &#8216;height()&#8217;. Note that the width and height of the ball and paddles are smaller than they should be: this is a common trick for games, since players are bound to notice some close misses and interpret them as &#8220;this shouldn&#8217;t have missed&#8221;, making the image of the paddles and ball smaller reduces near misses and keeps the players happier.</li>
</ul>
<p>Next, the view object uses a &#8216;render()&#8217; function to display things. This function will use the &#8216;move()&#8217; function we defined earlier:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">view.prototype.render = <span style="color: #000084; font-weight: bold;">function</span>(model)
{ <span style="color: #000084; font-weight: bold;">var</span> move = <span style="color: #000084; font-weight: bold;">function</span>(avatar,pos,spd,size)
  { <span style="color: #000084; font-weight: bold;">var</span> x = pos.x - size.w + field.w;
    <span style="color: #000084; font-weight: bold;">var</span> y = pos.y - size.h + field.h;
    avatar.stop()
      .css({left:x,top:y})
      .animate({left:x+10*spd.vx, top:y+10*spd.vy},10000,<span style="color: #0000ff;">"linear"</span>);
  }; 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.ball.vx != model.ball.vx || <span style="color: #000084; font-weight: bold;">this</span>.ball.vy != model.ball.vy)
  { <span style="color: #000084; font-weight: bold;">this</span>.ball.vx = model.ball.vx;
    <span style="color: #000084; font-weight: bold;">this</span>.ball.vy = model.ball.vy;
    move(<span style="color: #000084; font-weight: bold;">this</span>.avatar.ball,model.ball,<span style="color: #000084; font-weight: bold;">this</span>.ball,ball) } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.paddle.left != model.left.vel)
  { <span style="color: #000084; font-weight: bold;">this</span>.paddle.left = model.left.vel;
    move(<span style="color: #000084; font-weight: bold;">this</span>.avatar.pa_l,
         {x: -paddle.x, y:model.left.pos},
         {vx: 0, vy: <span style="color: #000084; font-weight: bold;">this</span>.paddle.left}, paddle) } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.paddle.right != model.right.vel)
  { <span style="color: #000084; font-weight: bold;">this</span>.paddle.right = model.right.vel;
    move(<span style="color: #000084; font-weight: bold;">this</span>.avatar.pa_r,
         {x: paddle.x, y: model.right.pos},
         {vx: 0, vy: <span style="color: #000084; font-weight: bold;">this</span>.paddle.right}, paddle) } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.scores.left != model.scores.left)
  { <span style="color: #000084; font-weight: bold;">this</span>.scores.left = model.scores.left;
    <span style="color: #000084; font-weight: bold;">this</span>.avatar.sc_l.html(model.scores.left) } 

  <span style="color: #000084; font-weight: bold;">if</span> (<span style="color: #000084; font-weight: bold;">this</span>.scores.right != model.scores.right)
  { <span style="color: #000084; font-weight: bold;">this</span>.scores.right = model.scores.right;
    <span style="color: #000084; font-weight: bold;">this</span>.avatar.sc_r.html(model.scores.right) }
}</pre>
</blockquote>
<p>The render function always checks whether the current value inside the model is different (!=) from the value stored in the view (this). When this is the case, the &#8216;move&#8217; function is called to move the appropriate avatar in the appropriate fashion (or, in the case of scores, the inner text of the score avatar is changed using the &#8216;html()&#8217; function from jQuery).</p>
<h3>The Controller</h3>
<p>The last piece of the game is the controller. It should gather information from the user, compute the AI&#8217;s response to ball movement, and measure how long has elapsed since the last time the view has been refreshed and update the model accordingly.</p>
<p>This time, the controller has no reason to be an object, because nobody will manipulate it (except, of course, itself). Instead, we can just define some values inside a function and use them to do the job:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">var</span> gameModel = <span style="color: #000084; font-weight: bold;">new</span> model();
<span style="color: #000084; font-weight: bold;">var</span> gameView  = <span style="color: #000084; font-weight: bold;">new</span> view();</pre>
</blockquote>
<p>As a first step in implementing the controller, we need to extract the keypresses from the user and write a function that applies them. This is done as follows:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">  <span style="color: #000084; font-weight: bold;">var</span> keys  = { up: <span style="color: #000084; font-weight: bold;">false</span>, down: <span style="color: #000084; font-weight: bold;">false</span> }; 

  gameView.avatar.play.keydown(<span style="color: #000084; font-weight: bold;">function</span>(event){
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 38) keys.up = <span style="color: #000084; font-weight: bold;">true</span>;
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 40) keys.down = <span style="color: #000084; font-weight: bold;">true</span>;
    <span style="color: #000084; font-weight: bold;">return</span> <span style="color: #000084; font-weight: bold;">false</span>
  }); 

  gameView.avatar.play.keyup(<span style="color: #000084; font-weight: bold;">function</span>(event){
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 38) keys.up = <span style="color: #000084; font-weight: bold;">false</span>;
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 40) keys.down = <span style="color: #000084; font-weight: bold;">false</span>;
    <span style="color: #000084; font-weight: bold;">return</span> <span style="color: #000084; font-weight: bold;">false</span>
  });   

  <span style="color: #000084; font-weight: bold;">var</span> playerMoveLeft = <span style="color: #000084; font-weight: bold;">function</span>(model)
  { model.moveLeft((keys.up ? -1 : 0) + (keys.down ? 1 : 0)); }</pre>
</blockquote>
<p>The &#8216;keydown&#8217; function provided by jQueryhas a single parameter, which is a function. That parameter will be called whenever an unpressed key is pressed when the playing field is selected. The same happens for &#8216;keyup&#8217;, which reacts when a pressed key is released. The functions check what the key was by looking at &#8216;event.which&#8217;: a value of 38 is the &#8220;up&#8221; arrow key while a value of 40 is the &#8220;down&#8221; arrow key (39 and 41 are the left and right arrow keys, respectively). The functions also use the statement &#8216;return false&#8217;: this notifies the playing field (which is originally a text field from a form) that the key press should be ignored, instead of adding the letter to the field.</p>
<p>What the functions do is set the value of keys.up and keys.down: the &#8220;playerMoveLeft&#8221; function then reads the value of the keys to determine which keys are currently pressed. The &#8220;a ? b : c&#8221; construct uses &#8220;b&#8221; if &#8220;a&#8221; is true, and &#8220;c&#8221; otherwise. So:</p>
<ul>
<li> If the up key is pressed but the down key is not, the direction is -1 + 0 = -1</li>
<li>If the down key is pressed but the up key is not, the direction is 0 + 1 = 1</li>
<li>If neither key is pressed, the direction is 0 + 0 = 0</li>
<li>If both keys are pressed, the direction is -1 + 1 = 0</li>
</ul>
<p>So, the code above correctly responds to player input whenever the &#8216;playerMoveLeft&#8217; function is called.</p>
<p>Another step is to define a similar aiMoveRight function for computing the AI response. We want the AI do to something smart enough to be challenging. However, since the ball moves slowly from left to right, a perfect AI could simply compute where the ball will land and wait there: it would therefore never lose. This is a good thing for computer science, but a bad thing in game: a good game AI is not an AI that always wins, but an AI that loses in a challenging and fun manner.</p>
<p>The following code accomplishes this:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">  <span style="color: #000084; font-weight: bold;">var</span> aiMoveRight = <span style="color: #000084; font-weight: bold;">function</span>(model)
  { <span style="color: #000084; font-weight: bold;">var</span> dir = 0;
    <span style="color: #000084; font-weight: bold;">if</span> (model.ball.vx &gt; 0)
    { <span style="color: #000084; font-weight: bold;">var</span> dist = (paddle.x - model.ball.x);
      <span style="color: #000084; font-weight: bold;">var</span> target = model.ball.y + model.ball.vy * (dist / model.ball.vx);
      <span style="color: #000084; font-weight: bold;">while</span> (target &gt; field.h-ball.h || target &lt; ball.h-field.h)
      { <span style="color: #000084; font-weight: bold;">if</span> (target &gt; 0) { target = 2*(field.h-ball.h) - target }
        <span style="color: #000084; font-weight: bold;">else</span>            { target = 2*(ball.h-field.h) - target }
      }            

      dir =
        (model.right.pos + paddle.h &lt; target ?  1 : 0) +
        (model.right.pos - paddle.h &gt; target ? -1 : 0)  

      <span style="color: #000084; font-weight: bold;">var</span> accuracy =
        field.h * Math.<span style="color: #000084; font-weight: bold;">exp</span>((model.scores.left - model.scores.right)/3); 

      <span style="color: #000084; font-weight: bold;">if</span> (dist &gt; accuracy)
      { dir = -dir }
    } 

    model.moveRight(dir);
  }</pre>
</blockquote>
<p>The general structure of the code is reasonably easy to get: the code computes the direction in which the AI (right) paddle should move, then sets that direction on the last line. If the ball is not moving right (vx &gt; 0) the AI paddle does not move (dir = 0). However, if the ball is indeed moving right, then the computation starts: the algorithm computes the distance between the ball and the paddle. From that, it computes the point where the ball should meet the paddle (and stores the vertical coordinate in the &#8216;target&#8217; variable). Once the target is known, the direction is computed: if the paddle is below the target, it moves up, and if it&#8217;s above, it moves down. This is a perfect AI: it never loses because it always knows where the ball hits and moves there immediately. So, we dumb it down by adding accuracy: if the ball is further away from the paddle than a certain distance threshold (stored in the &#8216;accuracy&#8217; variable) then the paddle does the opposite of what it should do (dir = -dir).</p>
<p>The two important questions here are: how is the target determined, and how is the accuracy determined?</p>
<p>The <strong>target </strong>is computed by determining where the ball would end up if there were no top or bottom edges: one simply calculates the horizontal distance and deduces from the horizontal and vertical speed ratio the vertical distance that it will go from its current position. Once this position is known, the code takes into account bounces: if the target is outside the top or bottom edges, then it will bounce, which means that the target position should be reflected around that edge. For the bottom edge, reflection is done with &#8216;target = 2*(field.h-ball.h) &#8211; target&#8217; and for the top edge it&#8217;s done with &#8216;target = 2*(ball.h-field.h) &#8211; target&#8217;. The AI repeats this reflection process until the target is within the playing field.</p>
<p>The <strong>accuracy </strong>is computed by getting the exponential of the score difference (with a few modifiers, &#8216;field.h&#8217; and &#8217;3&#8242;, obtained through playtesting). The point of using an exponential is that, as the score difference increases (in favor of the player) the exponential increases substantially and so the accuracy also increases, and as the score difference increases (in favor of the AI) the exponential decreases substantially without going below zero. So, the point of the exponential is getting an accuracy that increases when the player is doing well, without going below zero.</p>
<p>As a result, the AI starts playing perfectly when the player has three more points than the AI.</p>
<p>The last thing the controller does is keep the model and view up to date. To do this, it computes the current time (in seconds, with decimals) and also remembers the last time it was updated. Then, if the last update is more than one timestep ago, it updates the model and increases the last-update-time by one timestep, and repeats this process until the model is up-to-date. Then, it renders the model.</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;">  <span style="color: #000084; font-weight: bold;">var</span> time = <span style="color: #000084; font-weight: bold;">function</span>() { <span style="color: #000084; font-weight: bold;">return</span> +(<span style="color: #000084; font-weight: bold;">new</span> Date) / 1000 };
  <span style="color: #000084; font-weight: bold;">var</span> last = time(); 

  <span style="color: #000084; font-weight: bold;">var</span> act  = <span style="color: #000084; font-weight: bold;">function</span>()
  {
    playerMoveLeft(gameModel);
    aiMoveRight(gameModel); 

    <span style="color: #000084; font-weight: bold;">var</span> now = time();
    <span style="color: #000084; font-weight: bold;">while</span> (now &gt; last)
    { gameModel.update();
      last += timestep } 

    gameView.render(gameModel);
    setTimeout(act,50);
  }</pre>
</blockquote>
<p>The time function uses a common trick: it creates a date object (which by default contains the current time), converts it to the number of milliseconds since a fixed point in time, and divides it by 1000. The &#8216;return&#8217; statement means that when the function is called, it will be replaced by the returned value (var last = time();).</p>
<p>The &#8216;act()&#8217; function applies input to the game model, then performs as many updates as necessaryand finally renders the model. Then, it asks Javascript to execute &#8216;act()&#8217; again in 50 milliseconds (that&#8217;s 20 times per second).</p>
<p>The result is to wrap all of this in a single &#8216;controller()&#8217; function and ask jQuery to execute the entire thing when the document has finished loading:</p>
<blockquote>
<pre style="background: #ffffff none repeat scroll 0% 50%; color: #000000;"><span style="color: #000084; font-weight: bold;">function</span> controller()
{ <span style="color: #000084; font-weight: bold;">var</span> gameModel = <span style="color: #000084; font-weight: bold;">new</span> model();
  <span style="color: #000084; font-weight: bold;">var</span> gameView  = <span style="color: #000084; font-weight: bold;">new</span> view();
  <span style="color: #000084; font-weight: bold;">var</span> keys  = { up: <span style="color: #000084; font-weight: bold;">false</span>, down: <span style="color: #000084; font-weight: bold;">false</span> }; 

  gameView.avatar.play.keydown(<span style="color: #000084; font-weight: bold;">function</span>(event){
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 38) keys.up = <span style="color: #000084; font-weight: bold;">true</span>;
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 40) keys.down = <span style="color: #000084; font-weight: bold;">true</span>;
    <span style="color: #000084; font-weight: bold;">return</span> <span style="color: #000084; font-weight: bold;">false</span>
  }); 

  gameView.avatar.play.keyup(<span style="color: #000084; font-weight: bold;">function</span>(event){
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 38) keys.up = <span style="color: #000084; font-weight: bold;">false</span>;
    <span style="color: #000084; font-weight: bold;">if</span> (event.which == 40) keys.down = <span style="color: #000084; font-weight: bold;">false</span>;
    <span style="color: #000084; font-weight: bold;">return</span> <span style="color: #000084; font-weight: bold;">false</span>
  });   

  <span style="color: #000084; font-weight: bold;">var</span> playerMoveLeft = <span style="color: #000084; font-weight: bold;">function</span>(model)
  { model.moveLeft((keys.up ? -1 : 0) + (keys.down ? 1 : 0)); } 

  <span style="color: #000084; font-weight: bold;">var</span> aiMoveRight = <span style="color: #000084; font-weight: bold;">function</span>(model)
  { <span style="color: #000084; font-weight: bold;">var</span> dir = 0;
    <span style="color: #000084; font-weight: bold;">if</span> (model.ball.vx &gt; 0)
    { <span style="color: #000084; font-weight: bold;">var</span> dist = (paddle.x - model.ball.x);
      <span style="color: #000084; font-weight: bold;">var</span> target = model.ball.y + model.ball.vy * (dist / model.ball.vx);
      <span style="color: #000084; font-weight: bold;">while</span> (target &gt; field.h-ball.h || target &lt; ball.h-field.h)
      { <span style="color: #000084; font-weight: bold;">if</span> (target &gt; 0) { target = 2*(field.h-ball.h) - target }
        <span style="color: #000084; font-weight: bold;">else</span>            { target = 2*(ball.h-field.h) - target }
      }            

      dir =
        (model.right.pos + paddle.h &lt; target ?  1 : 0) +
        (model.right.pos - paddle.h &gt; target ? -1 : 0)  

      <span style="color: #000084; font-weight: bold;">var</span> accuracy =
        field.h * Math.<span style="color: #000084; font-weight: bold;">exp</span>((model.scores.left - model.scores.right)/3); 

      <span style="color: #000084; font-weight: bold;">if</span> (dist &gt; accuracy)
      { dir = -dir }
    } 

    model.moveRight(dir);
  } 

  <span style="color: #000084; font-weight: bold;">var</span> time = <span style="color: #000084; font-weight: bold;">function</span>() { <span style="color: #000084; font-weight: bold;">return</span> +(<span style="color: #000084; font-weight: bold;">new</span> Date) / 1000 };
  <span style="color: #000084; font-weight: bold;">var</span> last = time(); 

  <span style="color: #000084; font-weight: bold;">var</span> act  = <span style="color: #000084; font-weight: bold;">function</span>()
  {
    playerMoveLeft(gameModel);
    aiMoveRight(gameModel); 

    <span style="color: #000084; font-weight: bold;">var</span> now = time();
    <span style="color: #000084; font-weight: bold;">while</span> (now &gt; last)
    { gameModel.update();
      last += timestep } 

    gameView.render(gameModel);
    setTimeout(act,50);
  } 

  act();
} 

$(<span style="color: #000084; font-weight: bold;">function</span>(){<span style="color: #000084; font-weight: bold;">new</span> controller});</pre>
</blockquote>
<h2>The Article</h2>
<p>This game uses 200 lines of Javascript and 50 lines of quick-and-dirty HTML. It took me about three hours to develop. This article is the longest article so far on Nicollet.Net and took me an entire day to write. You can expect other video games and maybe even other tutorials in the future, in the same vein as this one. If you have questions, or if you have enjoyed this, make sure to add a comment below. Links to this tutorial from places where beginners ask a lot of questions are also most welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.nicollet.net/2008/12/game-development-tutorial/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

