« Tech Digest

Tips for Technologists #11: Learn Javascript in 30 Minutes

Tips for Technologists is a series aimed at teaching you to engage with technology in best way possible. You can see all the Tips for Technologists articles here.

By Nick Ruffilo

Javascript is a great first language. It can run in a web browser, is everywhere, and uses HTML as its display compliment. For that reason, I’m going to use this tutorial to teach everyone how to program javascript, and along the way teach some core concepts in being a good coder.

Who is this tutorial for:

  • The Non-Coder: If you can open a text editor (not word) such as TextWrangler, Text Edit, Notepad, etc, and you can run a web browser, you can learn Javascript.
  • The Intermediate Coder: Do you already know some javascript? This tutorial will teach you how to best use comments and code organization.
  • The Advanced Coder: While the concepts here are basic — many I didn’t grasp/understand until well into my coding life. Maybe they will help you as well.

The Challenge!

Today, everyone who invests the time (30 minutes tops) will be re-creating the game Pong in Javascript/HTML that will run in every web browser. In fact, this should even run in iBooks if you wish to bundle it up in an EPUB file. Why Pong? Pong was a commercial success and one of the first video games played by the masses. Additionally, it is elegant and simple. You have a ball that bounces, and two paddles that move up/down. Lastly, as I mentioned in a prior post, whenever I wanted to learn a new language, I programmed Pong in it.

Our Tools

While I normally program using an IDE (Integrated Development Environment), that is completely overkill for this project. But, we will still need a few tools to get this done. I suggest you open them all up and get them all ready.

  • A Text Editor: If you’re on Mac, you can open up Text Edit, if you’re on Windows you can open up Notepad. If you wish, I prefer things like TextWrangler (Free)
  • A Project Directory: Wherever you logically want to store your code, create a new directory and name it “pong.” All of your project files will go in this directory.
  • Three Files: Using your text editor, save 3 blank files in your newly created directory (you should have a blank file open, simply use “save as.”  Name these files: pong.html, pong.css, and pong.js
  • A web browser: Open your favorite web browser and drag the “pong.html” file you just saved into a new tab. This should load a blank screen (as there is nothing in there).
  • Open your 3 files: In your text editor, open each of your files: pong.html, pong.css, pong.js. You will need all of them open at once.

Step 1: Hello World

Most programming books will have you create the “hello world” program as your first challenge. Basically it is a program that says: “Hello world.”  While boring, we’re going to quickly do that for our HTML file. Open your pong.html file and put this in:

<html>
<head>
<title>[My Name]’s Pong!</title>
<script type=”text/javascript” src=”pong.js”></script>
<link rel=”stylesheet” href=”pong.css” type=”text/css” />
</head>
<body>
Hello World!
</body>
</html>

Save your file
Now that the .html file is saved, go back to your browser and hit the reload button. You should see the magical words “Hello World!” If not, go back through the steps and make sure you’re not missing anything.

Pseudocode

For long or complicated projects I suggest you create a requirements document, and possibly break out some UML diagraming/modeling to determine how the system will work. For simple bits of code or short projects you are welcome to jump right into pseudocode. Pseudocode is human-readable logic that is ignored as code, so anything you write in pseudocode is ignored. In Javascript, you can write comments/pseudocode using // before the line. In HTML we write pseudocode/comments using <!– [comment here] –>  Lets get to writing the logic down. Comments/Pseudocode in CSS use /* [comment here] */

HTML Pseudocode

When writing Pseudocode, ask yourself: “What do I need and how should it work.” See below for my HTML Pseudocode:

<!– Player controlled paddle on the left side of the screen –>
<!– Computer controlled paddle on the right side of the screen –>
<!– Ball that will bounce and interact with the paddles –>
<!– Button that will move the player paddle UP –>
<!– Button that will move the player paddle DOWN –>

CSS Pseudocode

Now that we know the HTML that is going to be  needed, we can write the CSS rules (in pseudocode).

/* Player Paddle – Left of screen, 10 pixels wide, 64 pixels tall, Black Border, green background  */
/* Computer Paddle – Right of screen, 10 pixels wide, 64 pixels tall, Black Border, red background */
/* Ball – 10 pixels, round, black border, grey background */
/* Up Button – Left side of screen, 24 px wide, 24 px tall, black border, blue background */
/* Down Button – Left side of screen, 24 px wide, 24 px tall, black border, blue background, below the Up Button */

Javascript Pseudocode

This is the meat of the “action.” When learning your first programming language, you do not need to know how/why everything works. That comes with time. To demonstrate skydive thinking, I’ll break down my pseudocode into multiple steps (although, in practice, I do this all in one step)

Step 1: High Level

//Move the ball
//Move the paddle when button is pressed
//Move the Computer’s Paddle

Step 2: a little bit more granular

//Move the ball
//  add X velocity to the X position
//  add Y velocity to the Y position
//  check to see if the ball has hit the player paddle
//    If so – invert the X velocity (change it’s direction)
//  Check to see if the ball has hit the computer’s paddle
//    If so – invert the X velocity (change it’s direction)
//  Check if it is off screen, if so, someone has just won
//Move the paddle when button is pressed
//  If up was pressed – move up
//  If down was pressed – move down
//Move the paddle when button is pressed
//  If the ball is above the computer paddle, move it up a bit
//  If the ball is below the computer paddle, move it down a bit

Step 3: Ground floor

If we required another pass, we could add more granularity, but for such a simple program, we do not.  Up to now, if you haven’t written anything down, You’d be OK. I do suggest at this point you copy the HTML comments into your HTML file (within the <body></body> tag, you can replace “Hello World” if you wish), you copy the CSS comments into your .css file and then the javascript comments into your .js file.

Indents/Tabbing: its important (But I can’t do it here)

WordPress does not handle indents/tabbing very well, but it is KEY towards good coding. For more on indent styling see this wonderful article. You can also download the source files (in a .zip file) at the end of this project to see what my final looks like.

Let’s fill in the HTML comments

I like to see my work. It gives me a sense of progress, and for this reason, I often build a crude/basic UI first. Bring up your .html file text editor window and lets fill in code after our comments (comments go BEFORE the code they are discussing).

<!– Player controlled paddle on the left side of the screen –>
<div id=”player_paddle” class=”paddle”></div>

<!– Computer controlled paddle on the right side of the screen –>
<div id=”computer_paddle” class=”paddle”></div>

<!– Ball that will bounce and interact with the paddles –>
<div id=”ball”></div>

<!– Button that will move the player paddle UP –>
<div id=”up_button” class=”button” onclick=”movePlayerPaddle(‘up’);”>Up</div>

<!– Button that will move the player paddle DOWN –>
<div id=”down_button” class=”button” onclick=”movePlayerPaddle(‘down’);”>Down</div>

Save your file

Thats all we’ll need for the .html file. Now lets modify the .css file to give our HTML file some beauty.

/* Paddle Class – since the Player Paddle and Computer Paddle share common traits */
.paddle {
position: absolute;
height: 64px;
width: 10px;
border: 1px solid rgb(0,0,0);
}

/* Player Paddle – Left of screen, 10 pixels wide, 64 pixels tall, Black Border, green background  */
#player_paddle {
left: 10px;
top: 100px;
background-color: rgb(0,255,0);
}

/* Computer Paddle – Right of screen, 10 pixels wide, 64 pixels tall, Black Border, red background */
#computer_paddle {
right: 10px;
top: 100px;
background-color: rgb(255,0,0);
}

/* Ball – 10 pixels, round, black border, grey background */
#ball {
border: 1px solid rgb(0,0,0);
background-color: rgb(100,100,100);
height: 10px;
width: 10px;
border-radius: 5px; /*makes the ball round instead of square*/
position: absolute;
top: 250px;
left: 250px;
}

/*Button class – since we want the buttons to look the same */
.button {
position: absolute;
height: 24px;
width: 24px;
border: 1px solid rgb(0,0,0);
background-color: rgba(0,0,255,.5);
}

/* Up Button – Left side of screen, 24 px wide, 24 px tall, black border, blue background */
#up_button {
top:25px;
left: 25px;
}

/* Down Button – Left side of screen, 24 px wide, 24 px tall, black border, blue background, below the Up Button */
#down_button {
top: 55px;
left: 25px;
}

Save your .css file!

Now, if reload your .html page (in your web browser) you should see something that looks like this:

Yes, the “Down” goes outside of the button, but I’ll leave it to you to adjust and make this your own.

Adding in the Javascript

Up to now, things have been relatively straight forward. Nothing will change, even though we’re going to do some actual programming. Keep in mind, we’re going to be giving instructions for the computer. Javascript, like all programming languages, lets us store values in something called variables. It is always a good idea to define your variables before you use them, and to do so in a common area. I’ll define them above the comments (and add them as I go and need them).

You can get a copy of the javascript file here.

If you save this to your pong.js, you’ll notice that nothing happens when you reload the pong.html. The reason is, there is nothing going that starts the actual game. You’ll need to go back to your HTML file and modify the body tag from: <body> to <body onload=”moveBall();moveComputerPaddle();”>. This tells the browser that, as soon as the page is fully loaded, run moveBall and moveComputerPaddle.

But, I just copied your code. That’s not coding.

YET! People learn when they can experiment in a safe environment. Sure, I’ve given you a working example, but it is pretty lame. The buttons need to be styled/positioned better, and the AI should never lose (or always lose if you make the browser big/small enough). What I challenge you to do is to look at this code, and play with the values. Change the computerPaddleMovementSpeed value up top to see how that effects the computer paddle. See if you can figure out how to speed up the moveBall function so that it runs more frequently making the game harder. Within a few minutes, the code slowly starts becoming yours. Also, as you edit things, you get a better understanding as to what things do. Another “bug” I’ve put in the code is that right now, the ball interacts with the wrong side of the paddle. Can you fix it?

 

Want more Tips for Technologists?  Join the daily mailing list and see additional content at ZenOfTechnology.com.  You can also see other Tips for Technologists articles here on Publishing Perspectives here.

This entry was posted in Tech Digest and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.
  • Get Publishing Perspectives in your inbox each day and stay up-to-date on international publishing.