After my partner and I built our first Ruby program in the first module of our Bootcamp, I was so excited by the accomplishment that the following weekend I decided to take my programming skills a step further and make a command-line game.

The result was Badgers and Gyms, a game where you kill badgers with grenades:

Image for post

&: User | %: Badger

After I had graduated from the Bootcamp and was building a portfolio site for my projects, I wanted to incorporate this game into the site somehow. I looked around for ways to embed a terminal on the site that could run Ruby, but I couldn’t find anything. So, I decided to adapt the game into React.

Wiring Up SVG

The first problem I faced was how to display the game with moving parts and animations. When first learning JavaScript, I had played around with moving <div> elements on the page, but that didn’t seem like the best way to handle this.

I had used SVG before, but not with moving parts. I started experimenting with some different things and discovered the <circle> tag, which has a cx and cy attribute for positioning the circle within the <svg> tag. This seemed like a straightforward way to start.

I found an SVG graphic of a basketball court on Wikimedia Commons and wrapped its paths in their own <g> layer. I then added a second layer on top for the moving parts:

If you look at the bottom <g> layer, you’ll see I’ve controlled the cx and cy attributes and pointed them to values on a user object. The next task is to change those values to move the objects around within the boundaries of the basketball court.

If you look at the bottom <g> layer, you’ll see I’ve controlled the cx and cy attributes and pointed them to values on a user object. The next task is to change those values to move the objects around within the boundaries of the basketball court.

Functional Programming To The Rescue

There are three types of moving objects in this game: the user, the badgers, and the grenades. While these three objects might move at different speeds, they all need to know how to move about the <svg> basketball court.

#svg-animation #game-development #svg #react #javascript

SVG in React: Building a Game
17.25 GEEK