# Calculating dynamic light and shadows in tile based roguelike games – part 1: Bresenham’s line algorithm

I love roguelike games. From the simple ASCII games to more complex turn based games like Sproggiwood.

I also made some blog posts about roguelike games.

One of the features a good roguelike game should have is dynamic light and shadows, as well as a “fog of war” effect.

Although it may seem complex, I’ll show you this feature in a way you will find it a lot easier than it seems. I will use a logic similar to the one used in the creation of a survival horror game, but this time we are dealing with tiles.

In this first step, we’ll see the algorithm which will be the core of dynamic lights in tile based environments: Bresenham’s line algorithm.

From Wikipedia: Bresenham’s line algorithm is an algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points. It is commonly used to draw lines on a computer screen, as it uses only integer addition, subtraction and bit shifting, all of which are very cheap operations in standard computer architectures. It is one of the earliest algorithms developed in the field of computer graphics.

To create a demo with Bresenham algorithm I am going to use the JavaScript code found on RosettaCode together with the magic of Phaser.

This is what we are going to create:

We have two draggable tiles, the white ones, a green straight line connecting the tiles, and the result of Bresenham algorithm made of grey tiles. Try to drag white tiles and see what happens.

This will be our ray of light.

The source code is very basic at the moment, let’s have a look:

It’s just the management of draggable sprites which snaps on a grid and the rendering of Bresenham algorithm itself, which runs from line 44 to line 75.

The reason I am leaving this script uncommented is most of it will be discarded in the final version as it’s only a demo to show you how Bresenham algorithm works.

Next time I am going to show you how to use this algorithm to create dynamic light and shadows, meanwhile if you already have some idea, you can download the source code and start from here.

• Dario

Really great idea, I know about the algorithm, but I’m interested in how to apply that to phaser.. I’m used to use the algorithm in 3D where you have control over triangles and vertices, so I’m really happy to see how can you use that with sprites in a framework that totally obscure the underlying 3D primitives in favour of “sprites”.

Looking forward the sequel to the article, thanks.

• Emanuele Feronato

I already made three sequels, check the latest posts!