7 Cool JavaScript Expressions You Should Never Use

I think we can all agree that JavaScript is a pretty cool language. And as with many things, some bits of JavaScript are cooler than others. However, the cool-ness of a piece of JavaScript code is by no means synonymous with its practicality. In fact, one might go so far as to say that the coolness of a JavaScript statement is an inverse measure of how often it should be used. That is, the cooler the code is, the less you should use it.

And if that’s the case, then you should never, ever use anything you see in this article, because from here on out you will be exposed to some Seriously Cool Code.

1) Truncating numbers with bitwise operators

You can use bitwise operators to truncate numbers, like so:

num = ~~num;
num = num#
num = num|num;

Each of these is roughly equivalent to using parseInt or floor on a number, and will all yield the same result. They behave like Math.floor(num) would, assuming the number is positive. They always behave like parseInt(num, 10). Of the three, the last appears to be the fastest.

2) While loop with the iterator in the condition

// while loop with iterator as condition
var i = 5;
while(i--) {

}

This is a reverse for loop with what appears to be no conditional logic! Is it infinite? Nope. Since 0 is a falsy value, when i– results in zero, the loop will execute a final time and quit. It’s quick, easy, and the fastest loop currently known.

3) If statements without the if

someBoolean && (someStatement = 10);

Okay, what’s going on here? We’re taking advantage of the fact that when parsing conditional statements, the return value of the statement is evaluated. We also know that if the left hand statement of an && operator is evaluated as truthy, the right hand will be evaluated as well; otherwise, it won’t be. So this code is essentially equivalent to this:

if(someBoolean) {
someStatement = 10;
}

4) Comma operator

var a = 1,
b = 2;

b = (a++, 10);

The little known comma operator can be a bit mysterious and tricky to understand, but once you know what it means, it can be rather useful. Note, however, that useful is not equivalent with maintainable or understandable, and both of those take precedence over “useful”. Anyways, the comma operator performs all statements enumerated and returns the last statement’s value.

That means, in the above code, “a” will end up equaling 2, and “b” will end up equaling 10; the two statements in the last line are evaluated, and the return value of the last one is passed on.

5) The double exclamation point!!

value = !!value;

Using a double exclamation point will instantly identify you as an over-excited internet poster under-familiar with the colloquial usage of English. (unless you’re writing in JavaScript, in which case it’s perfectly ok). The double exclamation point, or double bang, converts a truthy or falsy value to “true” or “false”. In other words, it operates exactly like Boolean(value) would.

6) Define value if undefined

value = value || "hello world";

This function is quite simple. It defines a value if it appears to be undefined. That is, if the value already evaluates to a falsy value (which by some strange twist of fate, “undefined” does), it’s replaced by whatever comes after the OR operator. Note: the following is a much safer, but slightly longer, way of ensuring the same thing:

value = (typeof value !== "undefined") ? value : "hello world";

The above code checks to see if “value” is literally exactly equal to undefined, and will not fail if “value” does not exist anywhere in the code and is unrecognized in addition to being undefined. However, it is a mouthful. Or lineful, dare I add.

7) The void operator

undefined = void 0;

There is an operator called void. It evaluates whatever expression is passed to it and then returns a true, unadulterated value of undefined. This is useful in cases where you suspect that undefined may in fact have been defined at some point (and yes, that is legal in JavaScript). You can also compare directly against void 0 if you don’t want to overwrite whatever definition undefined has.

That’s all, folks!

I think that’s a sufficient amount of coolness in JavaScript for now, I don’t want to freeze anybody out. And, having read this article, keep in mind that you should never, ever use any of the code I’ve demonstrated for you above.

But, since I know you’ll ignore me, at least just remember to comment your super-cool JavaScript code. If not for yourself, at least for the sake of the next developer that comes along, who, being naturally less cool than you, will be unable to understand it.

And please, if you have any more cool, comment-worthy JavaScript, be sure to leave it below in the comments or shoot me an email–I’d love to see it.

How to Round Numbers To Arbitrary Values

This is just a quick little function I find pretty useful. It allows you to round any number to an arbitrary value, and can be useful for when you’re working with and rendering to a grid or want a slider that increments by a certain step.

if(typeof Math.roundTo === "undefined") {
Math.roundTo = function(num, step) {
return Math.floor((num / step) + .5) * step;
}
}

Math.roundTo(15, 10); // >> 20
Math.roundTo(14.99, 10); // >> 10
Math.roundTo(42, 1); // >> 42

As you can see, it’s pretty straightforward. Just pass in the number you want to round, and the step you want it rounded to and voilá, you’re good to go.

Field of view in Javascript using recursive shadow casting

Field of view, and stuff

Field of view, which involves determining which tiles are visible to the player, is a particularly fun aspect of writing roguelikes, in my opinion. When writing a field of view algorithm, you often find yourself trading quality for performance, or vice versa. Some algorithms get around this with a bit of trickery, like the Rogue algorithm. Other algorithms have no visible artifacts and in fact are quite pleasing visually, but pay for this with a definite decrease in performance.

There have been, of course, plenty of articles written about field of vision, and there is in fact an excellent compendium of resources over at Roguebasin (you can check that out here). This is a problem that has been thoroughly solved many times, beginning with Rogue’s rudimentary solution (you can see all the tiles in the room you’re in, but nothing else is visible; when in corridors, only the corridor tiles next to you are visible). The thing is, only a few Javascript algorithms (if any) are available to calculate FOV. Since I’m writing a Roguelike and have of course come up with an algorithm of my own, I have decided to remedy this lack of JS algorithms by sharing mine with you. It’s nothing fancy, but does provide a rather nice gradient falloff, which works in tandem with the display.js library that I previously posted.

Finding the happy medium

Many FOV algorithms have been written in an attempt to find the happy medium between performance and quality. After trying a few algorithms out, I eventually settled with recursive shadowcasting, which was both optimized for maximum performance but also very few artifacts. All in all, I’m happy with my choice. Here are some of the results you can get with recursive shadowcasting combined with a gradient falloff:

Demonstration of Saege's FOVMore Saege FoV

The field of view you see here is using a radius that is roughly double that of which is found in my game in order to better display the nice lighting falloff. However, even with aforementioned smoothed lighting, performance isn’t impacted in the slightest.

Has the happy medium been found?

As I’ve mentioned before, performance is usually achieved at the cost of quality. However, I was able to find a way to boost the performance of the algorithm without impacting quality. Now, to update the lighting, most algorithms clear the map of light and reset all the tiles to “unlit” or, depending on whether the player has already seen the tiles, “unseen”, which basically means the player has seen that tile at some point but can’t currently see it. The lighting algorithm then calculates the tiles within the player’s field of view and sets those tiles to “visible”, and the rendering engine displays them as lit up. Pretty straightforward.

The difference in my algorithm is that instead of clearing the entire map, it only sets to “unseen” those tiles which were lit the previous turn. This means that loads of CPU cycles aren’t wasted trying to reset the entire map’s lighting, most of which is outside the player’s field of view anyways. The algorithm simply appends each tile that is set to “visible” to an array, which is stored. When the lighting is next updated, those tiles in the array, and only those tiles, are set to “unseen” and the algorithm proceeds to calculate lighting as normal; wash, rinse, repeat, and you’ve got yourself one quick little field of view algorithm.

If you’ve stuck with me this long…

…you must be interested in seeing the algorithm. So, without further ado, here it is. It’s been sparsely commented, but hopefully should be of some help to some of you. And, as before, the LightSource class which contains the algorithm does make use of some external functions, which I will be introducing to you later on as progress on my game continues. And, before I forget, here’s a demo demonstrating its use.

Hopefully this article has given you something to think about, and, as always, feel free to comment and let me know if I’ve made any mistakes or typos!

Generating caverns with cellular automata

In this article, I’ll be discussing how to generate neat-looking fully connected caves using cellular automata. This algorithm builds off of another algorithm which can be found here. As noted, the linked algorithm is incomplete and cannot be used for generating dungeons that are suitable for a real roguelike. This article is about the method I used to make that algorithm workable.

First off, the basic algorithm:

To begin, let’s take a look at basic algorithm behind generating nice-looking cave levels with cellular automata:

1. Scatter wall blocks across the level at a 30-40% saturation level (I've found that 39% is ideal).

2. Iterate through all the tiles on the map four times: 
  - For each tile in each iteration, set the tile to be floor.
  - Then, calculate the number of wall tiles within both one square of the original tile (these are neighbors) and two squares (these tiles are nearby). Store these numbers.
  - If the number of neighbors for the tile is greater than or equal to 5, or there are less than two wall tiles nearby, set this tile to be a wall.
  - If it is not a wall already, leave this tile as a floor tile. 3. Iterate through all the tiles on the map three more times:
  - For each tile in each iteration, set the tile to be floor.
  - Calculate the number of wall tiles within both one square of the original tile.
  - If this tile has five or more neighboring walls, make it a wall. Otherwise, leave it as a floor tile.

The issue with cellular automata is…

…the caves generated with the cellular automata technique are often unconnected. Since many roguelikes depend on all parts of a level being accessible, this is usually a bad thing. So, clearly, we need a way to drop the disconnected regions or otherwise ignore them. The best way to do this is with a flood fill algorithm. A flood fill algorithm is able to find all the nodes connected to each other that aren’t delimited by another type of node. In graphics applications, this is usually used to find regions of similar color.

In our algorithm, the flood fill algorithm will be used to find all the regions of the cave that are comprised of purely floor tiles–in other words, all the caverns (unconnected or not) on the map. Once we have a list of the caverns, we can select the largest cavern–this will be the main cavern. We can then simply drop the other patches, as they are small unconnected regions that are precisely what we don’t want.

Flood fill algorithm in Javascript:

Here’s how I managed the flood fill algorithm and subsequent cavern managing in Javascript:

// this variable will be used to store the various unconnected caverns 
var caverns = [];

// begin looping through the map
for (var x = 1; x < this.size.x; x++) {
for (var y = 1; y < this.size.y; y++) {
var cavern = [];
var totalCavern = [];

if (this.data[x][y].type != "dirty floor") { // we've already been over this tile or it is already part of a cavern,
// no need to check it
continue;
}

cavern.push(this.data[x][y]);
totalCavern.push(this.data[x][y]);

while (cavern.length > 0) {
var n = cavern.pop();

if (n.type == "dirty floor") { // set a flag on the tile indicating it has already been checked
n.setType("floor");

for (var i = 0; i < 8; i++) {
var curTile = this.data[n.position.x + x_array[i]][n.position.y + y_array[i]];
if (curTile.type == "dirty floor") {
cavern.push(curTile);
totalCavern.push(curTile);
}
}
}
}

// add this cavern
caverns.push(totalCavern);

// sort the caverns
caverns.sort(function (a, b) {
return (b.length - a.length);
});
}
}

// remove the largest cavern, as it is the main cavern
caverns.shift();

// now that we've got the unconnected caverns, change their tile type
if (caverns.length > 0) {
for (var i = 0; i < caverns.length; i++) {
for (var j = 0; j < caverns[i].length; j++) {
caverns[i][j].setType("wall");
}
}
}

As you can see, I loop through all the tiles. First, I check to see if I’ve already been over the tile; if so, I pass it on. If I haven’t, I go through that tile and search its neighbors, too. Eventually, I’ve searched all the tiles on the map and sorted them into the various caverns to which they belong. Once I’ve done that, I sort the caverns by size, from largest to smallest, and pick out the one with the most tiles in it (in other words, the biggest cavern). This is the main cavern, so we can get rid of or ignore the rest. I personally chose to get rid of my unconnected caverns, but it’s possible to connect them or just ignore them for the rest of the dungeon generation code–it’s up to you really.

In finis…

If you’ve read this far, you’re at least slightly intrigued by the cellular automata/flood fill cave generation algorithm–good! Hopefully you’ll have as much fun playing around with it as I did. As you can see, the Javascript code I included above makes heavy use of some external data-managing structures, such as a map data structure and a tile structure as well; I’ll be writing more articles about how I handle the map and tile stuff later. As always, thanks for the read, and if I made any mistakes during this article or if any of my code can be improved, please let me know!

Console-like display in the browser?

I’ve been working for some time on a Roguelike in Javascript. One of the first things I had to do for my Roguelike, of course, was establish some sort of display routine. I could have gone with HTML5’s new <canvas> tag or something similar, but setting up a console-like environment for canvas can get a little involved. So instead, I established a way to use the browser’s native text rendering. Say hello to a simple Javascript class for console-like rendering in the browser: I call it display.js.

So, let’s take a look at the code required initialize a basic 80 by 25 console and draw a few characters with the display class:

// create a display for console-like rendering
display = new Display(new Vector2(80, 25), new Vector2(10, 35), true);

// let's draw the classic @ sign:
display.ch("@", new Vector2(10, 10));

// maybe fake a few walls
for(var x = 0; x<10; x++) {
display.ch("#", new Vector2(x, 0));
}

// let's put a green slime down, too
display.ch("j", new Vector2(15, 15), "green");

Okay, let’s step through this code really quickly. Before we begin, though, I’d like to note the Vector2 class I use here; it’s nothing more than a utility function I use to hold a position with X and Y values (you can grab a copy of it here). So, in the code, the first line initializes the console display. The first variable we pass in to this function call is the size of the display–I use 80 by 25 because that’s a standard console size, but these numbers could be anything you want. The second variable we pass in is the offset of the console from the rest of the page. The third variable we pass in is whether we want this display to open in a new window or not. If you set it to false, the display will simply be written to your HTML page. If it’s set to true, the console will open in a popup window.

The next line calls a function on our newly created console, namely ch. This allows you to display a character on the screen and takes a minimum of two and up to five parameters. In order, these are: the character to display, the position of that character, the color of the character, the opacity of the character, and the background color of the character. Only the character you want to write and the position of that character are required; the others are optional. The color variable accepts a few basic color names as well as hex values. The next few lines do nothing more than demonstrate the various applications of the ch function, which is the only function display.js makes use of.

In finis…

As you can see, the display class isn’t very advanced right now, but it’s been all I’ve needed so far. If you want to download the class, you can grab it here. Quick note, it does make use of jQuery, so make sure you include that in your project before you attempt to use it. As progress on my game continues, this library will likely be updated with more functions as I need them. Thanks for taking a look, and be sure to keep an eye on Hey Javascript for more updates in the near future! (hopefully, I’ll be posting some dungeon generation algorithms in Javascript soon)

Roguelike game programming and development in Javascript?

The Roguelike genre has been in development for decades–since 1980, in fact, when Rogue, the first Roguelike game, was written. Since then, Roguelike games have been created in many different programming languages. Among the more popular of these languages are C, C++, Java, and Python. However, a new contender is appearing: Javascript. Although it’s the new kid on the block, Javascript is quickly becoming a popular choice for Roguelike development and has already been used to make quite a few games.
Continue reading Roguelike game programming and development in Javascript?

8 great A* pathfinding resources

If you’re writing a game that incorporates both a terrain of some sort and enemies that walk around, the chances are you’ll need some version of pathfinding to control the enemy movement patterns. The thing is, pathfinding is serious business–it’s not easy to grasp. To make things worse, there aren’t many good pathfinding resources–most of the articles that turn up on Google and such only serve to confuse you further. That’s why I’ve taken the time to compile this list of pathfinding resources that I’ve found to be actually helpful, as opposed to confusing or just plain wrong. Enjoy!
Continue reading 8 great A* pathfinding resources

A revolutionary and amazing new way to loop through arrays

…well, revolutionary and amazing to me, anyhow. Like most Javascript programmers, I usually use a for loop to iterate through my arrays, a method which typically works pretty nicely and doesn’t really have many drawbacks. However, I recently discovered another method which takes a tad less typing while maintaining the same functionality–the forEach loop. It’s quite handy and you don’t have to declare a bunch of variables to loop through an array.

The forEach loop behaves pretty much like your standard for loop, except that it’s a function that you call only on arrays. It looks like this:

myArray.forEach(function(element, index, array) {
console.log(element); // element is the current element in the array
console.log(index); // index is the position of that element in the array
console.log(array); // this is the array the forEach loop was called on
});

The above code passes an anonymous function into the forEach method, but you can use any function you want. Within that function, element refers to the current element in the array, index is the index of the current element of the array, and array is the array the forEach function was called on (note: you don’t have to pass in all the variables; just make sure you pass them in in the correct order). The forEach loop is a pretty handy alternative to the standard for loop and something I’ll definitely be turning to in the future.

The only drawback is that the forEach loop is relatively new, so you’ll have to provide a fallback for older browsers if you’re worried about compatability. Mozilla’s documentation provides an extensive article on the forEach loop and elaborates on a method to provide that fallback for older browsers I was talking about earlier.

Javascript’s little-known do-while loop

Many Javascript programmers are familiar with the while loop, which executes iterates until a given condition evaluates to false. It’s a pretty handy construct and can provide the fastest loops in the Javascript world (if used properly). However, there is a drawback. If the given condition evaluates to false immediately, the while loop will not run even once. This is because the while loop’s condition is evaluated before executing the code within the loop. “Oh well,” you say, “if that’s the case, then too bad, right?” Wrong.

Introducing: the do-while loop

The do-while loop is a lesser-known cousin of the while loop that few Javascript programmers know about. Unlike the while loop, it executes its statement exactly once before evaluating its condition. The do-while loop looks like this:

do {
statement;
} while (condition);

Because the statement of a do-while loop is executed once before the condition is evaluated, you can do interesting stuff like this:

do {
// statement
} while (false);

If we were using an ordinary while loop, the above statement would fail. However, because the statement of a do-while loop is executed before the condition is evaluated, the above code runs once and then fails.

Too long; didn’t read

Functionally, the do-while loop is the equivalent of this while loop:

while(true) {
// statement

if(condition == false) {
break;
}
}

Top 8 Javascript learning tools

Javascript is a complex and multi-faceted language, and can be hard to learn properly. I’ve found quite a few invaluable tools that have helped me along my Javascript-learning journey, but some of them have been a little hard to dig up and others aren’t very well-known. To save you the pain, I’ve scrounged around and pulled together a list of what I’ve found to be the most useful Javascript learning tools. Enjoy!
Continue reading Top 8 Javascript learning tools