Lab: Mars Adventure#
This exercise will walk you through building an interactive text adventure game about traveling to the planet, Mars. You’ll practice capturing user input, producing dynamic output, using conditional statements and comparison operators, and converting data types.
Setup#
Download the starter code with the command below:
$ dmget wb-mars
Then, cd
into the newly-created project folder.
Getting started#
Before we do anything else, let’s get familiarized with the files included in the starter code package.
mars.js
#
This is the file you’ll edit and add code to during this lab.
index.html
#
You’ll open the index.html
file in the browser to run the game. This is made possible by the highlighted line below, which tells the browser to load and execute the code in mars.js
:
<!DOCTYPE html>
<html lang="en" style="background: black; color: white">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mars Adventure</title>
<script src="mars.js"></script>
</head>
<!--- ... ---></html>
Whenever you want to run and test your code, you’ll open (or refresh) index.html
in your browser.
Building the game#
The sections below will walk you through building various segments of the game.
Using the alert()
function#
You’ll use the alert()
function to display messages to the user. The alert()
function comes
with every web browser and causes the browser to display a pop-up window.
Follow the steps below to call the alert()
function so you can understand how it works:
Open
mars.js
in your text editor.Add the following line of code to
mars.js
:alert('Hello!');
Save your changes to
mars.js
(in VS Code, you can use Ctrl-S or Cmd-S to save).Open
index.html
in your browser. This will cause your browser to run the code inmars.js
. An easy way to openindex.html
is by running a command in your terminal (make sure your working directory is thewb-mars/
project folder before you run these commands):For macOS:
$ open index.html
For Windows:
$ start index.html
After opening index.html
in your browser, a pop-up window should appear with the message
Hello!
. Press the OK button or the Enter key to close the window.
![](_images/prompt-example.png)
Screenshot of the alert()
pop-up as it appears in Google Chrome.#
Display introductory flavor text#
To introduce the game and immerse the player into the world of Mars Adventure, you’ll display
some introductory flavor text to the user with the alert()
function. You can display whatever text you’d like, but here’s what we recommend:
![](_images/flavor-text-example.gif)
Pop-up windows that say, “Starting your Mars Adventure!” then, “Booting up…” then, “All systems go!” and finally, “Let’s start!”#
Code for the output above
alert('Starting your Mars Adventure!');
alert('Booting up...');
alert('All systems go!');
alert("Let's start!");
Ask for the user’s name#
Next, you’ll prompt the user to enter their name so you can display a welcome message and explain
the premise of the game. You’ll do this with the prompt()
function. This function is similar to
alert()
, except it waits for the user to type something into a dialog box and returns whatever
they typed.
Altogether, it might look something like this:
![](_images/username-prompt-example.gif)
A pop-up window with the prompt, “Hi there. What’s your name?” followed by windows that say, “Hi Balloonicorn — Welcome to The Mars Adventure Game.”, “Yesterday, you received a call from your good friend at NASA”, and “They need someone to go to Mars this weekend, and YOU’VE been chosen!!”#
Follow the steps below to create this introduction:
Create a variable called
username
and call theprompt()
function to set its value to the user’s input. You can customize the message that gets displayed in the dialog box by passing in an argument toprompt()
:mars.js#const username = prompt("Hi there. What's your name?");
Use the
alert()
function to greet the user with a customized greeting that displays their name. You can use string concatenation or a template string to do this.How to format a variable into a template string
mars.js#alert(`Hi, ${username} --- Welcome to The Mars Adventure Game.`);
Output the text explaining the premise of the game.
A completed example
const username = prompt("Hi there. What's your name?");
// Explain game
alert(`Hi, ${username} --- Welcome to The Mars Adventure Game.`);
alert('Yesterday, you received a call from your good friend at NASA.');
alert("They need someone to go to Mars this weekend, and YOU'VE been chosen!!");
Ask the user a question#
Next, we’ll write a conditional statement based on user input. We’ll ask the user if they’re excited and then output a message that depends on whether they’re excited or not. It’ll look something like this:
Prompt: Are you excited? (Type Y or N) User types Y and presses OK Alert: I knew you’d say that. It’s so cool that you’re going to Mars!
If the user answers N
instead of Y
:
Prompt: Are you excited? (Type Y or N) User types N and presses OK Alert: Well, it’s too late to back out now.
Add the following lines to your program. This will prompt the user for their answer and store whatever they typed in the variable
excited
.const excited = prompt('Are you excited? Type Y or N');
Next, we’ll show an appropriate message based on whether the user said they were excited or not.
If they’re excited (they typed
Y
), then the program should show an alert saying, “I knew you’d say that. It’s so cool that you’re going to Mars!”If they aren’t excited, it should show an alert saying, “Well, it’s too late to back out now.”
Take a moment to stop and discuss what this conditional logic might look like in JavaScript. If you’d like to try it out on your own, do so.
When you’re ready, reveal our idea about how to write it in the hint below.
Handling excited and non-excited users
mars.js#if (excited === 'Y') { alert("I knew you'd say that. It's so cool that you're going to Mars!"); } if (excited === 'N') { alert("Well, it's too late to back out now."); }
Normalizing input#
Currently, if the user types a lowercase y
or n
, they won’t see a message. The code checks for
Y
and N
, and strings are case-sensitive. In other words, a lowercase y
is not equivalent
to an uppercase Y
.
Let’s amend our code slightly so regardless of whether they capitalize their input or not, we’ll
be able to show them a message. We’ll do this by reassigning excited
to an uppercased version of
the string.
First, change the
const
declaration to alet
declaration:mars.js#let excited = prompt('Are you excited? Type Y or N');
Reassign the value of
excited
using thetoUpperCase
method to convertexcited
so all letters are uppercased:mars.js#excited = excited.toUpperCase();
Save your changes and try running your program again. You can do this by refreshing index.html
in the browser. Confirm that the appropriate message is shown if you type Y
, y
, N
, or n
into the prompt.
Time to pack#
Now comes the fun. We’ll take the user through some packing and other preparations for their trip to Mars. We’ll ask the user how many suitcases they plan to bring. If they want to bring more than two suitcases, we’ll mock them slightly and say the spaceship won’t be able to accommodate their luggage.
In order to check whether the number they’ve typed is greater than two, we’ll need to convert the user’s input from a string to a number.
Why type conversion?#
Any input that’s captured using the prompt()
function is going to be a string. If we want to
perform mathematical operations or numerical comparisons on user input, we’ll need that input to
be a number instead.
Attempting to treat strings like numbers can lead to a common bug. You can see this bug for youself by executing the following lines of code in your browser’s JavaScript console:
console.log('4' + 1); // 41
\(4 + 1\) should give us \(5\), but since '4'
is a string, JavaScript performs
string concatenation instead of addition.
Prompt the user for their number of suitcases#
Add the following code to your program to ask the user how many suitcases they plan to bring:
mars.js#alert("It's time to pack for your trip to Mars."); let numSuitcases = prompt('How many suitcases do you plan to bring?');
Call the
Number()
function to convertnumSuitcases
into a number:mars.js#numSuitcases = Number(numSuitcases);
Add a conditional statement to check if
numSuitcases
is greater than two.If the user is planning on bringing more than two suitcases, show an alert saying, “That’s way too many. You’ll have to pack more lightly.”
Otherwise, show an alert saying, “Perfect. You’ll certainly fit in the spaceship!”
Try this out on your own. Once you’ve given it a shot, expand the hint below to reveal our implementation:
Check if there are too many suitcases
mars.js#if (numSuitcases > 2) { alert("That's way too many. You'll have to pack more lightly."); alert('Please try to fit your stuff into 2 suitcases.'); } else { alert("Perfect. You'll certainly fit in the spaceship!"); }
Companion animal#
Next, we’ll have the user choose a companion animal to go with them on their Mars adventure. The companion animal can have any name and be any type of animal (like Janey the Frog or Henry the Unicorn). We’ll prompt the user for both pieces of information—the type of the companion animal and the name of the companion animal.
Add the following to your program:
mars.js#alert("You're allowed to bring one companion animal with you.");
Ask the user for the type and name of their companion animal:
const companionType = prompt('What kind of companion animal would you like to bring?'); const companionName = prompt("What is your companion's name?");
Echo the user’s input back to indicate we’ve understood their preferences. For example, if the user’s companion is Henry the Unicorn, you can show an alert like this:
Cool, so you're bringing Henry the Unicorn.
When you’re ready to check your code with our implementation, reveal the hint below.
Confirm the user’s companion
const companionType = prompt('What kind of companion animal would you like to bring?');
const companionName = prompt("What is your companion's name?");
alert(`Cool, so you're bringing ${companionName} the ${companionType}.`);
Improving how companion animals are displayed#
It’s possible that the user didn’t capitalize their companion animal’s name when they typed it
into the program. If they typed lena the lemur
, we’d want to display Lena the Lemur
instead.
Think about the steps you’d take to convert lena
to Lena
(or LENA
to Lena
):
Take the first letter,
l
.Use
toUpperCase()
to convertl
toL
.Take the other letters,
ena
.Use
toLowerCase()
to convertena
toena
(this will handle cases where users give animal names with all uppercased letters)Use string concatenation to add
L
withena
.
Let’s test this idea out in the JavaScript console using mock data.
In your browser’s JavaScript console, create a mock companion name:
let companionName = 'hammy';
Use
companionName[0]
to get the first character of the string:let firstLetter = companionName[0]; console.log(firstLetter); // h
Convert it to all-uppercased characters:
firstLetter = firstLetter.toUpperCase(); console.log(firstLetter); // H
Use
companionName.slice(1)
to get the rest of the string, starting at the second character:let otherLetters = companionName.slice(1); console.log(otherLetters); // ammy
Convert
otherLetters
to all lowercased characters:otherLetters = otherLetters.toLowerCase(); console.log(otherLetters); // ammy
Use string concatenation to put
firstLetter
together withotherLetters
and reassign the value ofcompanionName
:companionName = firstLetter + otherLetters; console.log(companionName); // Hammy
Once you understand how the code above works you can go ahead and add it to mars.js
. Compare your code with our implementation in the hint below.
Title-casing the animal’s name
alert("You're allowed to bring one companion animal with you.");
const companionType = prompt('What kind of companion animal would you like to bring?');
let companionName = prompt("What is your companion's name?");
let firstLetter = companionName[0];
firstLetter = firstLetter.toUpperCase();
let otherLetters = companionName.slice(1);
otherLetters = otherLetters.toLowerCase();
companionName = firstLetter + otherLetters;
// Confirm animal
alert(`Cool, so you're bringing ${companionName} the ${companionType}.`);
Spaceship decor#
Next, we’ll alert the user that they can choose the style of decorations in their spaceship! Very
fun. We’ll give them three options. Depending on the option that they choose, we’ll assign an
appropriate value to a variable called decor
.
Here’s the first part. Feel free to get creative and modify the options to your heart’s content!
mars.js#alert('NASA has a interior design team offering to outfit your space ship.'); alert(`You have a couple of options for the interior decor of your ship. Your options are: A Sleek, modern minimalism B Retro/vintage space age C Victorian-era steampunk `);
Try this part on your own. Prompt the user for their choice of spaceship decor. Once you’ve tried it out for yourself, you can check your code with our implementation below.
Prompting for decor choice
mars.js#let decorChoice = prompt('Which decor would you like? Choose A, B, or C.'); // Clean up user input decorChoice = decorChoice.toUpperCase();
While the user’s choice is helpful to have, we need to access which decor they’d like later in our program. So, we’ll write another conditional in order to assign the correct value to the variable
decor
.Here’s how to start:
let decor; if (decorChoice === 'A') { decor = 'modern minimalist'; }
Finish handling the other two options, assigning an appropriate value to
decor
for each of the choices. Then, you can check your code with our implementation below.Assigning a value for
decor
mars.js#let decorChoice = prompt('Which decor would you like? Choose A, B, or C.'); // Clean up user input decorChoice = decorChoice.toUpperCase(); let decor; if (decorChoice === 'A') { decor = 'modern minimalist'; } else if (decorChoice === 'B') { decor = 'retro'; } else if (decorChoice === 'C') { decor = 'steampunk'; }
Impress the user#
Combining several of the pieces of user input from our adventure game so far, we’ll give a brief summary of the user’s Mars adventure that’s about to go down.
This next print statement uses variables from the previous sections. Remember to type this out; please don’t copy/paste.
alert(`${username} and ${companionName}, surfing the celestial abyss, in a ${decor} spaceship.`);
Time for lift off#
To conclude the adventure, we’ll have the user crawl into the spaceship with their companion animal and take off into space.
They’ll take off after a countdown sequence. One way to implement the countdown is by writing out each part of the countdown:
alert('5...');
alert('4...');
alert('3...');
alert('2...');
alert('1...');
alert('*** LIFTOFF ***');
However, you can save yourself from a lot of repetitive typing using a loop to output the
countdown instead. We’ll do this with a while
loop (although you could also implement this with
a for
loop too):
First, we’ll make a counter variable called
timer
and set its initial value to5
.In the
while
loop, we’ll print that variable.At the end of the loop, we’ll subtract one from
timer
and keep going.Once
timer
drops to0
, the loop should end.
Here’s a version of this loop with some parts missing. Fill them in and test it out before peeking at our implementation in the hint below.
let timer = 5;
while (timer > ____) {
alert(`${timer}...`);
timer = ____;
}
alert('*** LIFTOFF ***');
Code for countdown
let timer = 5;
while (timer > 0) {
alert(`${timer}...`);
timer -= 1;
}
alert('*** LIFTOFF ***');
Finished!#
You’re finished with the main part of the Mars Adventure game. Call over a staff member for a brief code review. Then, you can add more options and features to your game. You’ll find ideas in the optional Further Study section linked below.
Further Study (optional)#
After you’ve gotten a code review, click here to move on to further study.