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 ...

Get Head First JavaScript Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.