How to Use JavaScript and Node.js to Fight a Dragon

A step by step guide to building a simple command-line terminal game

Shane McGrath
GitStacks
Published in
6 min readAug 6, 2021

--

Photo by Clint Bustrillos on Unsplash

Man, dragons are annoying am I right?

Being an adult is hard enough. We have to pay bills, show up to jobs, and handle the rest of our obligations.

So when a level 30 draco causticus sputem shows up in the grocery store parking lot at the end of a workday, it’s broadsword time baby.

That’s right, time to draw your trusty weapon from your ’08 Honda Civic and get to business.

But hold your horses there cowboy. Before you thrust that razor sharp blade into some nasty dragon scales, we’re going to need a little code to implement battle.

Come one, you didn’t think it would be THAT easy did you?

No need to worry though because we’re going to defeat that rush hour commute headache together.

Here’s how to use your programming skills to slay that dragon so you can get home in time for a hot slice of Digiorno.

Getting Started

Seriously, put the sword down and instead get ready to code your way out of this predicament.

Brains over brawns pal, don’t forget we’re developers here.

We are going to download Node.js, set up a project folder in our IDE (integrated development environment), and grab a useful Node package.

Then, we’ll write some JavaScript code so we can take care of that dragon with proper weaponry.

Node is a great tool for building highly scalable real time apps.

Or in our case, fighting a dragon.

Set up Node and Your Project Folder

If you don’t have Node in your JavaScript coding arsenal already, let’s walk through a basic Node.js set up.

Step 1: Make your way over to https://nodejs.org/en/

Step 2: Download Node for your appropriate operating system (MacOS, windows, Linux).

Step 3: Open your command line terminal.

Step 4: Type “node” and hit enter. You should see something similar to the image in figure 1. If not, you may need to redownload to get it working.
Hurry up though, that dragon is scorching the parking lot with it’s fire breath and the store manager is totally freaking.

node successfully downloaded onto your machine

Step 5: (optional): Warm up with a little code to see how it works. Try typing “5 * 8” and hitting enter. You should see the result.

What we are doing is running JavaScript outside of the browser. We are making progress with our set up!

Step 6: Create a folder on your desktop or wherever you prefer on your system. Make a note of the file path (In windows you can right click the folder and see the path where it says “properties”).

Step 7: In your IDE, open the folder and add a file called “index.js”

Set up the Readline-sync Npm Package

Next, we are going to add an npm package to our project, which will expand our functionality to write our dragon slaying syntax.

Step 8: Go to npmjs.com, and run a search for “Readline-sync.” You can read more about it in the documentation and err, fight more dragons with it.

Step 9: To install it, copy the text in the image shown here in figure 2:

Text to copy shown in green

Step 10: Go back to your terminal, and navigate to the directory of your project folder. Type “cd” then your file path, the cd means change directory in case you’re wondering.

Step 11: Paste the text from step 9 into the terminal and hit enter. This should install the Readline-sync npm for you.

The Readline-sync lets us create interactions with the user in the terminal, kind of like those old school text adventure games from the 80's.

Step 12: Go back to your IDE and take a look at the files. You should see a new directory similar to the figure 3:

If you want to see the Readline-sync in action right away, copy a code example from the documentation, add into your indjex.js file, write “node” in your terminal, then your project file path and hit enter and see how it works.
If you’d rather take care of this pesky dragon, then read on.

Write Some Code

Let’s write some JavaScript code and make good use of our npm functionality in the process. I’ll explain some of the highlights of the code sequence, and leave the rest up to you to explore and review.

Step 13: in your project index.js file, add the following code at the top:

var rs = require(‘readline-sync’);

So when the JavaScript file is read, the npm functionality for Readline-sync will be returned to our program, which unlocks some functionality for command line terminal interactions.

Step 14: create a few new line of code as follows:

i = 0;

var welcome = rs.keyInYN(‘The dragon approaches, are you brave enough to fight? ‘);

This line is leveraging the npm functionality by asking the user a yes or no question, then storing the result in a variable.

From here, we can make use of some boolean logic in the stored variable to drive a decision in our code. In our case, making choices about how to fight dragons.

Step 15: Add the below code into the project:

if (!welcome){
console.log(‘You flee in terror, and the dragon burns you up!’);
i += 2;
} else {
weopons = [‘Broadsword’, ‘Bow & Arrow’, ‘Machine Gun’, ‘Magic Wand’],
index = rs.keyInSelect(weopons, ‘Choose your weapon’);
console.log(‘Ok, you equip the ‘ + weopons[index] + ‘ , You are now ready for battle’)
i += 3;
}

Let’s cover some key aspects of how its working:

Note this line:

if (!welcome){

If the user says no when previously asked to fight(read: coward), welcome will be false value and will increment the i variable to 2 for us. This triggers another while loop later in the code which then increments the value to lead to a “game over.”

Note these lines:

weopons = [‘Broadsword’, ‘Bow & Arrow’, ‘Machine Gun’, ‘Magic Wand’],
index = rs.keyInSelect(weopons, ‘Choose your weapon’);

These lines are letting us ask the user (with help of the npm pacakge and keyInSelect method) which weapon to use from an array of values. I packed some good ones into the array for you so you can fight the good fight.

Take a look at this line:

console.log(‘Ok, you equip the ‘ + weopons[index] + ‘ , You are now ready for battle’)

This line let’s us reference the chosen weapon in a logged string statement back to the user.

Step 16: Add this code next:

while(i == 2){
i += 5;
}

while (i == 3){
var choice = rs.keyInYN(‘Do you attack immediately? ‘);
if(!choice){
console.log(‘The Dragon screaches, his belly is exposed!’);
i += 1;
}else{
console.log(‘The dragon sees your attack and burns you to a crisp!’);
i += 4;
}
}

while(i == 4 ){
var choice2 = rs.keyInYN(‘Do you attack with your’ + weopons[index]);
if(!choice2){
i += 1;
}else{
console.log(‘You attack with your’ + weopons[index]);
i += 2;
}
}

if (i == 7){
console.log(‘Game Over!’);
} else {
console.log(‘You Defeat the dragon!’);
}

Step 17: Now that the code is ready, go ahead and play the game. Go to your command line terminal, make sure you are in your dragon game project directory, then enter the following: node index.js

This will initiate the game.

See if you can defeat the dragon or perhaps, make the game even better with your new tricks.

Happy coding.

--

--

I help technical/creative professionals master productivity and deep work to build prosperous and rewarding careers