Hacking a JavaScript text adventure game 2

<< First post

Following on with our series on hacking a JavaScript adventure game.  Today we will look at how to add images for each location in the game.

1. Download the files
2. Adding images

1. Download the files

You will need a copy of three files to use this example.  Download here.

The files are:
index.html (this is the code for the main page)
flags.json (this code keeps track of the various flags used in the game; more on this later)
script.json (this code keeps all of the adventure game - the options and paragraphs of text).


2. Adding images

First I am going to create a folder to store all my images in my project.  Make sure you put this folder in the same location as your project files!  It is a common mistake to put your images in "my documents" or "my pictures".

I have created a new folder called 'images' to store the images I will use in the project.

You can call your folder whatever you like, however 'images' works for this example.  If you change it then you will have to change the code as well!

Now I have found a couple of images that I like and so I will add them into my images folder.

Once I have the files in the right folder I will go into the code and tell each location to display the appropriate image.

Here I have added images called "door.png" and "bronzekey.png" into the locations script.

The next step is to change the JavaScript so that it displays the correct image for each location.

Paragraphs with an image.

This is done with the following lines of code:

From line 59:


What this line of code does is to create a new image tag with a width and height of 200 pixels.  It looks inside the script for the current image for this location.

The image is actually put onto the screen with line 100:

document.getElementById("imageContainer").innerHTML = newimage;

Which means 'go and find the thing called 'imageContainer' and change its html so that it is the same as what is written in the variable 'newimage' (from line 59).

Now that we have written this code we don't have to change the code any further.  Adding more images for new paragraphs is as simple as setting the "image" attribute in the script file.

Next time we will look at the code in more depth.