O'Reilly logo

Head First JavaScript Programming by Elisabeth Robson, Eric T. Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. Going further

Writing Real Code

image with no caption

You already know about variables, types, expressions... we could go on. The point is, you already know a few things about JavaScript. In fact, you know enough to write some real code. Some code that does something interesting, some code that someone would want to use. What you’re lacking is the real experience of writing code, and we’re going to remedy that right here and now. How? By jumping in head first and coding up a casual game, all written in JavaScript. Our goal is ambitious but we’re going to take it one step at a time. Come on, let’s get this started, and if you want to launch the next casual startup, we won’t stand in your way; the code is yours.

Let’s build a Battleship game

It’s you against the browser: the browser hides ships and your job is to seek them out and destroy them. Of course, unlike the real Battleship game, in this one you don’t place any ships of your own. Instead, your job is to sink the computer’s ships in the fewest number of guesses.

Goal: Sink the browser’s ships in the fewest number of guesses. You’re given a rating, based on how well you perform.

Setup: When the game program is launched, the computer places ships on a virtual grid. When that’s done, the game asks for your first guess.

How you play: The browser will prompt you to enter a guess and you’ll type in a grid location. In response to your guess, you’ll ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required