#3 Building a JavaScript & HTML Browser RPG: Creating Units

Emil Nordsted Sivertsen
2 min readFeb 2, 2022

--

In this episode we will be looking into the process of generating units for our grid-based browser RPG.

There is a lot to consider when creating interactive NPC units for our game: How do we keep track of the units, how do we access them at a later stage, how do we generate them, and how many do we want?

Storing units as JavaScript objects, or in an array would be obvious first choices, and likely good solutions. Feel free to follow that route. In a future iteration, I might even do that. But not this time.

For this project we wil store our NPC game units directly in the HTML, directly part of the DOM. To create the NPCs that will populate our DOM, we create a function, see below:

I suspect we’re likely going to be creating more than one type of unit, and more than one unit and likely with options for customization. So I create a function for this, createUnit().

document.createElement() lets us create DOM elements very easily, but in the future we might split this creation-process further up into even more functions, depending on how many attributes etc. we want. Just adding the ‘name’ attribute, class, and id to the player we can begin to see how bloatet it can get.

With this createUnit() function we can already very easily create units (albeit braindead) for our game. We need to place them on our board as well though.

For this we create another function, getTile() , which will utilize the x and y attributes we set during our board generating for-loop.

Retuns first instance of element matching our x and y aparameters

document.querySelectorAll() returns a list of HTML nodes, but given that there should only be a single instance of each (x,y) coordinate in our game board, we should get the first ([0]’th ) of that list. We can ‘query-select’ elements which matches our requested parameters very easily and quite will performing by just requesting by attributes.

Finally, we want to place some units in our game board. We do that by chosing a specific tile with our getTile() function, then appending a unit we create with our createUnit() function.

Let’s append a player unit and an enemy unit!

combines above functions getTile() and createUnit() to place a player unit on tile (3,3) and a enemy unit on tile (6,6).

Before looking at the results, our units cannot appear visible before we give them styling in our CSS stylesheet.

our .player unit gets a background: hotpink because we’re hot and they’re not. The enemy unit gets an ugly toady green.

Alltogether, you should end up with a board that looks something like below.

In the next post hopefully we will get at least one of these cubes, representing a unit, moving.

Thank you for reading!

--

--