{"id":21672475,"url":"https://github.com/redis-developer/redis-kaboom-rpg","last_synced_at":"2025-07-20T19:32:49.049Z","repository":{"id":46307433,"uuid":"375159846","full_name":"redis-developer/redis-kaboom-rpg","owner":"redis-developer","description":"Redis RPG game example with Kaboom.JS.","archived":false,"fork":false,"pushed_at":"2023-06-30T21:41:24.000Z","size":2149,"stargazers_count":12,"open_issues_count":3,"forks_count":13,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-11T11:24:07.386Z","etag":null,"topics":["game","hacktoberfest","hacktoberfest2021","javascript","kaboom-js","kaboomjs","nodejs","redis"],"latest_commit_sha":null,"homepage":"https://developer.redis.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/redis-developer.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-06-08T22:22:20.000Z","updated_at":"2024-12-08T20:45:49.000Z","dependencies_parsed_at":"2025-04-12T03:53:12.269Z","dependency_job_id":"0fa48986-c467-400d-addb-d18ab31784a7","html_url":"https://github.com/redis-developer/redis-kaboom-rpg","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/redis-developer/redis-kaboom-rpg","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fredis-kaboom-rpg","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fredis-kaboom-rpg/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fredis-kaboom-rpg/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fredis-kaboom-rpg/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/redis-developer","download_url":"https://codeload.github.com/redis-developer/redis-kaboom-rpg/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fredis-kaboom-rpg/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266187188,"owners_count":23889928,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["game","hacktoberfest","hacktoberfest2021","javascript","kaboom-js","kaboomjs","nodejs","redis"],"created_at":"2024-11-25T13:29:25.798Z","updated_at":"2025-07-20T19:32:49.031Z","avatar_url":"https://github.com/redis-developer.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Redis Kaboom RPG Game\n\nThis is an RPG maze type game built with [Kaboom.js](https://kaboomjs.com/), [Node.js](https://nodejs.org/) and [Redis](https://redis.io).  It makes use of the [Redis JSON](https://redisjson.io) module from [Redis Inc](https://redis.com).\n\n![Demo of the game running](https://raw.githubusercontent.com/redis-developer/redis-kaboom-rpg/main/redis_kaboom_game.gif)\n\n[Watch the video on YouTube!](https://www.youtube.com/watch?v=cowIZWASJNs)\n\nSince making the video and GIF above, we changed out the sprite images as part of our Hacktoberfest initiative.  If you're looking for the originals that you see in the video, they're in this repo in `public/sprites/original`.\n\n## Setup\n\nTo run this game, you'll need [Docker](https://www.docker.com/) (or a local Redis instance, version 5 or higher with Redis JSON installed) and [Node.js](https://nodejs.org/) (use the current LTS version).  First, clone the repo and install the dependencies:\n\n```bash\n$ git clone https://github.com/redis-developer/redis-kaboom-rpg.git\n$ cd redis-kaboom-rpg\n$ npm install\n```\n\n### Docker setup\n\n With Docker - you need to have Docker installed and there are no other requirements. You can use Docker to get a Redis instance with Redis JSON:\n\n```bash\n$ docker-compose up -d\n   ⠿ Network redis-kaboom-rpg_default  Created\n   ⠿ Container redis_kaboom            Started\n   ⠿ Container node_kaboom             Started\n$\n```\n\nRedis creates a folder named `redisdata` (inside the `redis-kaboom-rpg` folder that you cloned the GitHub repo to) and writes its append-only file there.  This ensures that your data is persisted periodically and will still be there if you stop and restart the Docker container.\n\nNote that when using Docker, there is no need to load the game data as this is done for you. Once the containers are running you should be able to start a game simply by pointing the browser at http://localhost:8080/.\n\n### Stopping Redis (Docker)\n\nIf you started Redis using `docker-compose`, stop it as follows when you are done playing the game:\n\n```bash\n$ docker-compose down\n  Container node_kaboom             Removed\n  Container redis_kaboom            Removed\n  Network redis-kaboom-rpg_default  Removed\n$\n```\n\n### Redis Setup (without Docker)\n\nWithout Docker - you will need Redis 5 or higher, Redis JSON and Node.js (current LTS version recommended)\n\nThis game uses Redis as a data store.  The code assumes that Redis is running on localhost port 6379. You can configure an alternative Redis host and port by setting the `REDIS_HOST` and `REDIS_PORT` environment variables.  If your Redis instance requires a password, supply that in the `REDIS_PASSWORD` environment variable.  You'll need to have Redis JSON installed.\n\n### Loading the Game Data\n\nNext, load the game map into Redis.  This stores the map data from the `game_map.json` file in Redis, using Redis JSON:\n\n```bash\n$ npm run load\n\n\u003e redis-kaboom-rpg@1.0.0 load\n\u003e node src/data_loader.js\n\nData loaded!\n$\n```\n\nYou only need to do this once.  Verify that the data loaded by ensuring that the key `kaboom:rooms` exists in Redis and is a Redis JSON document:\n\n```bash\n127.0.0.1:6379\u003e type kaboom:rooms\nReJSON-RL\n```\n\n### Starting the Server\n\nTo start the game server:\n\n```bash\n$ npm run dev\n```\n\nOnce the server is running, point your browser at `http://localhost:8080`.\n\nThis starts the server using [nodemon](https://www.npmjs.com/package/nodemon), so saving changes to the source code files restarts the server for you automatically.\n\nIf the server logs an error similar to this one, then Redis isn't running on the expected / configured host / port:\n\n```\n[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379\n    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)\n```\n\n### Stopping the Server\n\nTo stop the Node.js server, press Ctrl-C.\n\n\n### Playing the Game\n\nPress space to start, then use the arrow keys to move your character.  Red doors are locked until you have found the appropriate number of keys.  Touch a red door to find out how many keys are required, or pass through it if you have enough keys.  Green doors are unlocked and don't require keys.\n\nFind all 3 keys and unlock the door in the room you started in (room 0) to escape.  Touching a flag teleports you to a random other room.\n\nAt the end of the game, you'll see how long you took to complete the challenge, and how many times you moved between rooms.\n\n## How it Works\n\nLet's take a look at how the different components of the game architecture fit together.\n\n### Project Structure\n\nThe project consists of a Node.js back end that has API routes for some of the game logic and a static server for the front end.\n\nThe back end code lives in the `src` folder, along with the data loader code, used to load the game room map into Redis.  It uses the [Express framework](https://expressjs.com/) both to serve the front end HTML / JavaScript / CSS and image files, and also to implement a small API for starting and tracking game events.  Redis connectivity is handled using the [ioredis client](https://www.npmjs.com/package/ioredis).\n\nThe front end is written in JavaScript using [Kaboom.js](https://kaboomjs.com/) as the game engine, and the [Bulma CSS framework](https://bulma.io/) for some basic layout.  It lives in the `public` folder.\n\n### Working with Kaboom.js\n\n[Kaboom.js](https://kaboomjs.com/) describes itself as \"...a JavaScript library that helps you make games fast and fun!\".  It renders games as a set of scenes in a HTML `\u003ccanvas\u003e` element, the ID of and size of which can be configured, along with some other properties:\n\n```javascript\nconst k = kaboom({\n  global: true, // imports all kaboom functions to global namespace.\n  scale: 3, // pixel scale.\n  clearColor: [0, 0, 0, 1], // black background.\n  canvas: document.getElementById('game'), // which canvas to render in.\n  width: 180, // width of the canvas.\n  height: 180 // height of the canvas.\n});\n```\n\nEach screen in a game is called a \"scene\" in Kaboom.  Our game has three sorts of scene:\n\n1. The `start` scene: this is shown when the game is first loaded, and encourages the player to press space to start a new game.\n2. The `play` scene: used to render the room that the player is currently in, and handle player movement and collisions with other game objects (doors, flags, walls, keys).\n3. The `winner` scene: used to dispay game stats once the player has defeated the game by collecting three keys and exiting through the locked door in room 0.\n\nThe `start` and `winner` scenes have static text based layout.  Kaboom provides a `scene` function to define a new scene, and other utility functions.  Here's the complete definition of the `start` scene, which displays some centered text and waits for the space button to be pressed:\n\n```javascript\nscene('start', () =\u003e {\n  keysHeld = [];\n\n  add([\n    text('press space to begin!', 6), // 6 = font size.\n    pos(width() / 2, height() / 2),\n    origin('center'),\n  ]);\n\n  keyPress('space', () =\u003e {\n    newGame();  // a function run when space is pressed.\n  });\n});\n```\n\nTo start a game, we use the provided `start` function, passing it the name of a scene:\n\n```javascript\nstart('start');\n```\n\nThe `start` scene is then rendered.  To change to another scene, we add logic that calls the `go` function, providing the name of the next scene:\n\n```javascript\nscene('start', () =\u003e {\n  ...\n\n  keyPress('space', () =\u003e {\n    go('play', 0); // Go the the 'play' scene, passing room ID 0 as a parameter.\n  });\n});\n```\n\nThere are 31 rooms in the maze for our game, and all of them are rendered using a single scene named `play`.  This takes a room ID as a parameter, and uses that to retrieve the room's map from the back end which in turn gets it from Redis.  Let's look at features of Kaboom that help enable this...\n\nFirst, a scene definition takes a function as its parameter.  This defines what's in the scene, plus any logic.  Here, our `play` scene has an `async` function parameter and the first thing it does it makes a request to the back end to get the map for the room it's been asked to render:\n\n```javascript\nscene('play', async (roomNumber) =\u003e {\n  // Get the room details from the server.\n  const res = await fetch(`/api/room/${gameId}/${roomNumber}`);\n  const roomDetails = await res.json();\n```\n\nEach room's details contain an encoded tile map where different characters represent different graphics in the room.  Kaboom provides sprite loading functionality, allowing us to use images as sprites and lay them out like tiles.  Here, I'm loading some images:\n\n```javascript\nloadSprite('player', 'sprites/player.png');\nloadSprite('wall', 'sprites/wall.png');\nloadSprite('key', 'sprites/key.png');\nloadSprite('flag', 'sprites/flag.png');\nloadSprite('door', 'sprites/door.png');\nloadSprite('lockeddoor', 'sprites/lockeddoor.png');\n```\n\nKaboom's [`addLevel` function](https://kaboomjs.com/#addLevel) takes the room layout expressed as an array of characters (see the \"Using Redis as a Data Store\" section for details) and a series of objects describing which sprite to use for each character and any additional properties.  It then renders this layout into the canvas and assigns each tile the appropriate properties.  For example:\n\n```javascript\nconst roomConf = {\n  '@': [\n    sprite('player'),\n    'player'\n  ],\n  '=': [\n    sprite('wall'),\n    solid()\n  ],\n  'k': [\n    sprite('key'),\n    'key',\n    solid()\n  ],\n  'f': [\n    sprite('flag'),\n    'flag',\n    solid()\n  ]\n```\n\nNow, each `@` character in the room layout becomes the player's sprite, each `=` a solid wall and so on.  For our game, I chose to represent doors as the numbers 1..9 and give them extra properties such as whether they are locked or not.  These are added to the `roomConf` array dynamically:\n\n```javascript\n[\n  // Use the 'lockeddoor' sprite if the door's locked.\n  sprite(door.keysRequired \u003e 0 ? 'lockeddoor' : 'door'),\n  'door',\n  // Extra properties to store about this door - need\n  // these when the player touches it to determine what\n  // to do then.\n  {\n    leadsTo: door.leadsTo,\n    keysRequired: door.keysRequired,\n    isEnd: door.isEnd || false\n  },\n  solid()\n]\n```\n\nPlayer movement is handled by describing how the player should move (x, y) when each of the cursor keys is pressed:\n\n```javascript\nconst directions = {\n  'left': vec2(-1, 0),\n  'right': vec2(1, 0),\n  'up': vec2(0, -1),\n  'down': vec2(0, 1)\n};\n```\n\n`vec2` is a Kaboom function.  Each direction is then associated with a `keyDown` event handler which calls Kaboom's `move` function on the player's sprite object:\n\n```\nfor (const direction in directions) {\n  keyDown(direction, () =\u003e {\n    // Move the player.\n    player.move(directions[direction].scale(60));\n  });\n}\n```\n\nThe Kaboom `scale` function adjusts the speed at which the movement happens.  The real game code also handles `keyPress` events for each cursor - the callback for these deals with tidying up any transient on screen messaging e.g. as the player moves away from a locked door having been told they don't yet hold enough keys.\n\nWe also need to detect collisions between the player and other game objects (keys, flags, doors).  Kaboom provides a simple API for this.  For example, when the player touches a flag, we provide a function containing the logic describing what to do:\n\n```javascript\n  player.overlaps('flag', async () =\u003e {\n    // Go to a random room number.\n    const res = await fetch('/api/randomroom');\n    const roomDetails = await res.json();\n    go('play', roomDetails.room);\n  });\n```\n\nThe code above asks the back end application for a random room number and receives a response that looks like `{room: 22}`.  It then tells Kaboom to move to the `play` scene for that room.  So, when the player touches a flag... they're teleported to another room (or maybe back to the one they're already in).  The game code for this has additional logic that creates a camera spin effect too.\n\nThere's no need to provide code for when the player collides with a wall, as we don't need to take any specific action.  Kaboom knows that players can't walk over or through walls as we declared them `solid` and that's all we need to say about them.\n\nThe game tracks keys that the player has found using a global `keysHeld` array, containing the room ID(s) that the key(s) were found in.  When a player touches a door, we can then figure out if they have enough keys to open it or not:\n\n```javascript\nplayer.overlaps('door', (d) =\u003e {\n  // Wait a short time before revealing what is going to happen.\n  wait(0.3, ()=\u003e {\n    // Does opening this door require more keys than the player holds?\n    if (d.keysRequired \u0026\u0026 d.keysRequired \u003e keysHeld.length) {\n      showMsg(`You need ${d.keysRequired - keysHeld.length} more keys!`);\n      camShake(10);\n    } else {\n      // Does this door lead to the end state, or another room?\n      if (d.isEnd) {\n        go('winner');\n      } else {\n        go('play', d.leadsTo);\n      }\n    }\n  });\n});\n```\n\nIf the player doesn't hold sufficient keys to open the door, Kaboom's `camShake` function is used to shake the camera and provide visual feedback that the door can't be opened.  If they do have enough keys, they'll be taken to the next room or the `winner` scene if this door is the end of the maze.  Kaboom's `wait` function is equivalent to a `setTimeout` in JavaScript, and is used to provide a small dramatic pause.\n\nThese are the main things you need to know to build a game with Kaboom.  The code for the game is in `static/js/game.js` and contains a few more nuances than we covered here..\n\n### Using Redis as a Data Store\n\nThis game uses the following Redis data types and features:\n\n* **JSON (using Redis JSON)**: The tile map for each level (describing where the walls, doors, keys, flags and player's initial position are) is stored in Redis in a single key using Redis JSON.  The data loader uses the `JSON.SET` command to store the data in a Redis key named `kaboom:rooms`.  The Node.js back end retrieves the map for a given room with the `JSON.GET` command.  Room data is stored as a JSON array in Redis.  Each room's data is an object in the array: room 0 is the 0th array element, room 1 the first and so on.  We use the `JSON.ARRLEN` command whenever we need to know how many rooms are in the map (for example when choosing a random room to teleport the user to when they touch a flag).  Each room's data looks like this:\n\n```json\n{\n  \"layout\": [\n    \"============\",\n    \"=          =\",\n    \"=          =\",\n    \"=     k    =\",\n    \"=    ==    =\",\n    \"1  f  @=   2\",\n    \"=     ==   =\",\n    \"=          =\",\n    \"=          =\",\n    \"=          =\",\n    \"============\"\n  ],\n  \"doors\": {\n    \"1\": {\n      \"leadsTo\": 5\n    },\n    \"2\": {\n      \"leadsTo\": 3,\n      \"keysRequired\": 3,\n      \"isEnd\": true\n    }\n  }\n}\n```\n  * The `layout` array contains the tilemap for the room, which Kaboom uses in the front end to render the appropriate tiles. `=` is a solid wall, `@` is the position that the player starts in when they enter the room, `f` is a teleporter flag, and numeric characters are doors to other rooms.\n  * Each door is further described in the `doors` object.  In the example above, door 1 leads to room 5, and door 2 to room 3.  Door 2 is locked and the player requires 3 keys to pass through it.  Door 2 is also the special `isEnd` door, which represents the escape point from the maze.\n* **Streams**: Each new game gets its own Stream.  We use the timestamp when the game began as part of the key name, for example `kaboom:moves:1625561580120`.  Each time the player enters a new room an entry is written to the Stream (using the `XADD` command).  At the end of the game, data from the Stream is used to determine:\n  * How many times the player entered a room (using the `XLEN` command).\n  * How long the player took to complete the game (each Stream entry is timestamped, so we can calculate the game duration as the difference between the timestamps of the first and last entries).  For this we use the `XRANGE` and `XREVRANGE` commands.\n  * Each Stream entry looks like this:\n\n```bash\n127.0.0.1:6379\u003e xrevrange kaboom:moves:1625561580120 + - count 1\n1) 1) \"1625561643258-0\"\n   2) 1) \"roomEntry\"\n      2) \"1\"\n```\n  * Additionally, we write a \"start\" event to the Stream when the game starts, so that we get the timestamp of the start of the game in the Stream, rather than waiting until the player first moves to another room to start the game clock.  The \"start\" event will always be the first entry in the Stream, and looks like this:\n\n```bash\n127.0.0.1:6379\u003e xrange kaboom:moves:1625561580120 - + count 1\n1) 1) \"1625561580122-0\"\n   2) 1) \"event\"\n      2) \"start\"\n```\n* **Sets**: Every time the player begins a new game, the code \"hides\" the keys that the player needs to find to escape.  It does this by putting random room numbers into a Redis Set until there are 3 members there, using the `SADD` and `SCARD` commands for this.  There needs to be one set per running game, so we use the timestamp that the game was started as part of the key, for example `kaboom:keylocations:1625561580120`. The `SISMEMBER` commmand is used to check if a room number should have a key in it when sending the room map to the front end.  If it should, then the `k` (key sprite) character is left in the room map, otherwise it's removed before sending the map to the front end.  Each new game has its own set, containing three room numbers like so:\n\n```bash\n127.0.0.1:6379\u003e smembers kaboom:keylocations:1625561580120\n1) \"5\"\n2) \"17\"\n3) \"29\"\n```\n* **Key Expiry**: We use the `EXPIRE` command to ensure that keys associated with each game are removed from Redis after a day.  This ensures that we don't have uncontrolled data growth in Redis, for example because the player abandons the game.  When the player wins the game, keys are tidied up immediately using the `DEL` command.  Here, I'm looking at the time to live for a game's Stream key with the `TTL` command:\n\n```bash\n127.0.0.1:6379\u003e ttl kaboom:moves:1625561580120\n(integer) 86210\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredis-developer%2Fredis-kaboom-rpg","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fredis-developer%2Fredis-kaboom-rpg","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredis-developer%2Fredis-kaboom-rpg/lists"}