Playing with ConfigCat's Feature Flags in a Phaser.io application
Tags: phaser, featureflags, configcat, javascript
Published: 2022-02-05 19:27:53

Let's take a look at how practical a feature flag can be in a [Phaser.io](https://phaser.io) application. Phaser is one of the most popular browser game libraries and with its help, I'll build a simple game that replicates the experience of being in a music studio. Let's get started!

## An introduction to Feature Flags

What is a feature flag, exactly? You can think of a feature flag as an On/Off button for features. When pressed, the selected feature becomes available, and vice versa. Typically, these buttons are useful for targeting a specific audience or number of users, releasing an experimental feature, releasing it gradually, or customizing the product experience based on permission.

## How will the app use a Feature Flag?

To begin with, why would I want a feature flag in my game? Let's assume that my game is a success and users love it. I still want to keep the application free to play and ad-free, so to monetize it, I'll add another feature (a paid one) that only premium users will have access to. In the free version of my _Beatmaking Simulator_, the player has access to an on-screen drum machine controlled by the keyboard, while the full version offers a piano with playable keys as well. Therefore, I am intending to integrate [ConfigCat](https://configcat.com)'s feature management service to control which version of the game I would like to display.

## Getting started with Phaser 3

Let's get to the most exciting part - developing the application. I'll create a new folder for it that contains a plain _index.html_ file. There are several ways to get started with Phaser: you can clone it, you can get it via **npm**, or download pre-built versions of it. For the sake of simplicity, I'll use the last option. I'll download the _phaser.js_ file from Phaser's [downloads page](https://phaser.io/download/stable) and just drag it into my project folder. In order to import it, I'll include the following script in my _index.html_ file:

```html
<script type="text/javascript" src="phaser.js"></script>
```

And it's that easy - I'm ready to use the Phaser library! First, let's create a new Phaser.game object with the help of the initial configuration, containing mostly visual stuff such as the game's width, height, and background color. I now see an empty game canvas if I open my _index.html_ file in a browser.
**Hot tip**: If you're a newbie to web development, Visual Studio Code's Live Server extension will allow you to see your changes instantly in the browser.

```javascript
const config = {
  width: 1200,
  height: 900,
  renderer: Phaser.AUTO,
  backgroundColor: '#d4feff',
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
  },
  scene: { preload: preload, create: create, update: update },
};

const game = new Phaser.Game(config);
```

The most relevant part of the _config_ object is the _scene_, which contains the following functions:

- **preload**, which is used for loading sounds and images
- **create**, used for generating game content
- **update**, responsible for redrawing game objects

### Loading assets

Next up, I'm going to preload (hence the function name) a drum machine image and the drum sounds that I want to play.

```javascript
function preload() {
  this.load.image('drumpad', 'assets/images/drumpad.png');
  this.load.setPath('assets/sounds');
  this.load.audio('kick', 'kick.wav');
  this.load.audio('clap', 'clap.wav');
  this.load.audio('hat', 'hat.wav');
}
```

I have implemented the following logic to load the image on the canvas and make the kick pad playable:

```javascript
function create() {
  //loading the drum pad image and the kick sound
  const drumpad = this.add.sprite(340, 280, 'drumpad');
  const kick = this.sound.add('kick');

  //linking the A key to the kick sound
  this.input.keyboard.on('keydown-A', function () {
    kick.play();
  });
}
```

Now, let's do this a couple more times for the clap and hi-hat sounds. Let's add some text over the pads as well so I know which one's which, maybe some user instructions, and boom! I have a working drum machine right at my fingertips.


![myapp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uipgwlql7o4xsps3hqvh.png)

## Importing ConfigCat for my feature flag

I'm going to load the piano image and sounds in the same manner, and now I can view it and play as well! However, as I mentioned before, I only want to display the piano in the full version of the game. For that, I'm intending to use a ConfigCat feature flag: if the feature flag holds a truthy value, the piano keys will be shown and otherwise only the drum pad will be available.

If I navigate to the ConfigCat [dashboard](https://app.configcat.com), I can see a feature flag already created for me. From here I can change my flag's value, change some targeting options, view my SDK key, and more.


![dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43o18rldzsqppnmat1al.png)

Let's import ConfigCat via CDN in our index.html file:

```html
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/configcat-js@latest/dist/configcat.min.js"></script>
```

Next, I will need to create a _configcatClient_, which will link my application to the actual feature flag. I will need my SDK key from the dashboard for this. The _createClient_ function also supports various options such as _pollIntervalSeconds_, which is pretty self-explanatory, _configChanged_ - a callback that notifies you when a change occurs, and _logger_, which lets you choose what log level you want to use. These (and more) options are described in more detail in the [ConfigCat docs](https://configcat.com/docs/sdk-reference/js/#auto-polling-default). Here's an example of a level 3 logger, that will log pretty much everything: warnings, errors, and feature flag evaluation:

```javascript
const logger = configcat.createConsoleLogger(3);

let configCatClient = configcat.createClient('YOUR_SDK_KEY', { logger: logger });
```

And that's pretty much it! Now that my game is hooked up to ConfigCat, if I open the console, I can see the logger giving me some information about the feature flag. But how can I put the flag to proper use for what I want to display?

## Making use of the feature flag

Before moving any further let's move all the logic for the drum pad and piano in separate functions (_initializeDrumpad_ and _initializePiano_) to tidy up the code and allow for a better understanding of how feature flags work. Finally, I need the actual value of the feature flag. I can get it via the callback way or the asynchronous way, using the **getValueAsync** function.

```javascript
function create() {
  this.add.text(20, 560, 'Keyboard controls', { font: '44px Courier', fill: '#000000' });

  initializeDrumpad(this);

  let configCatClient = configcat.createClient('YOUR_SDK_KEY');

  configCatClient.getValueAsync('isMyFirstFeatureEnabled', false).then((flagValue) => {
    if (flagValue) {
      initializePiano(this);
    }
  });
}
```

This function has two parameters: the name of the feature flag and the default flag value. Now we have access to the value of the flag, and depending on it, I can choose if I want to display the piano. Lastly, let's head back to the dashboard and set the flag value to a truthy one. The game will display the piano keys by flipping the switch!


![finalapp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8uoxkfhidu16dw0bozn.png)

## Summary

To sum it up, we got to learn a little bit about two awesome pieces of technology today - Phaser.io and Feature Flags. Here's a walkthrough of what I did:
- installing Phaser and ConfigCat and importing them via CDN
- developing a small game
- creating a ConfigCat client that links the app to the feature flag service
- handling what the game will display based on the flag value

I also did a short demo video on this because I figured screenshots wouldn't do justice to a music creation app, right? You can check it out [here](https://www.youtube.com/watch?v=G-ckBtneAq4).

[![Making a beat](https://img.youtube.com/vi/G-ckBtneAq4/0.jpg)](https://www.youtube.com/watch?v=G-ckBtneAq4)

## Conclusion

ConfigCat’s feature flag management service can be practical in a Phaser application as well. It is also easy to understand and use, with its 10 minutes trainable [user interface](https://configcat.com). I hope you've enjoyed this article, and if you want to take a peek at the source code from this demo, it's available on [GitHub](https://github.com/bigmirc/feature-flags-in-phaser). 

For more informative and fun articles, you can also check out [ConfigCat's blog](https://configcat.com/blog/). You can also stay in the loop with all the latest developments by following ConfigCat on:
- [Facebook](https://www.facebook.com/configcat) 
- [Twitter](https://twitter.com/ConfigCat)
- [LinkedIn](https://www.linkedin.com/company/configcat)