We were finally going to build the JavaScript Mahjong game. We’re still doing that, but in two parts. As I wrote this tutorial, I realized the backend needs its own guide. So today, we’ll focus on that. Welcome to building the JavaScript Mahjong game’s backend—in PHP.
Before you continue, I recommend checking out a couple of earlier tutorials. That way, we can skip repeating those details here:
Ready to get started? Great! There’s a lot to cover. To follow along with this tutorial, you should know:
- Some CSS
- Basic knowledge of PHP
- And from the tutorials we mentioned:
- How to create the tiles
- What the layout file is
The requirements
When starting a project, we first decide what the game must do, what we want it to do, and what would be nice to have. Since this tutorial is just about the backend, we’ll focus on setting up the game board. The browser will send a request, and the server will return a board object to display. For the board to work, it needs to meet the game’s requirements.
This isn’t a full design document—just a list of what we need and what we’ll build. We’ll go into more detail as we continue. Use this as a checklist to see if we’ve covered everything.
What is needed
- A game board with the tiles.
- Tiles can be selected and matched.
- Matched tiles leave the board.
- Win condition: The board is empty
What is wanted
- Allowing the player to select a board layout.
- Making sure boards are solvable.
- Knowing how many matches are available (in the next tutorial)
- Giving the player a better chance with a shuffle (in the next tutorial)
- Providing the player with hints (in the next tutorial)
Nice to have
- A bit of sound (in the next tutorial)
- A bit of animation (in the next tutorial)
Since we’re only covering the backend in this tutorial, there isn’t a game demo yet. But you can still download the complete source code as a ZIP file. In the next tutorial, you will get full access to a game demo with the front-end included.
Running the downloaded code
This time, because we’re using PHP, you can’t just open index.html in your browser and have it work. You’ll need a web server that supports PHP.
I’ll assume you already have a web server or know how to set one up. But if you don’t, you can get one running quickly with a tool like XAMPP, MAMP, Laragon, or others to set up Apache and PHP with a user-friendly interface. Or you can even just use the PHP built-in development server: php -S localhost:8000
You can view a sample of a full backend response by visiting the backend demo.
We might add a full guide on setting up a development environment later—let me know in the comments if you’d like that.
You’ll notice the code uses typed class constants. This feature was added in PHP 8.3, so that’s the minimum version you’ll need to run the code.
As I mentioned, there’s a lot to cover, so let’s get started.
A game board with the tiles.
We’re making a JavaScript Mahjong Solitaire, a tile-matching game. We start with 144 tiles. We organize them according to the layout, which is represented in a JSON file.
The web server processes the layout file, and that’s where PHP comes in. Sometimes the task decides the language, but sometimes it’s just the developer’s choice. There aren’t any special requirements here, and I still enjoy using PHP, so I picked it.
The server loads the layout and prepares the grid data for the client (JavaScript) to display. In short, PHP does the processing, and JavaScript handles the rest.
The place where it starts
Every request to the server needs to reach some entry point. Our entry point knows what the request needs and which method to call to process it. Let’s see what our entry point looks like, and then I’ll explain it in more detail:
<?php
declare( strict_types=1 );
ini_set( 'display_errors', '0' );
require_once __DIR__ . '/backend/JsonResponse.php';
$response = new JsonResponse();
try {
require_once __DIR__ . '/backend/Backend.php';
$backend = new Backend( __DIR__ );
$boardData = $backend->createBoard( $_GET );
$response->send( $boardData );
} catch ( InvalidArgumentException $error ) {
$response->fail( $error->getMessage(), 400 );
} catch ( Throwable $error ) {
$response->fail( $error->getMessage(), 500 );
}
PHP is not a strict language by nature. It can be very permissive. But being strict can save us a lot of bugs later on. So the first thing we do is to declare that we want it to be strict.
We want basic security and to be user-friendly, without ugly error pages that can leak information about our deployment structure. For that, we need to create some safety guards. There are a few things we need to do for that. One of them is telling it not to display errors to the client. We will go over a few others later on.
Still, we want to know if there were errors in the request and sometimes display a simple, easy-to-understand message to the user instead of a generic “Server error” message. While log files help identify errors, the front end also needs to be considered. It helps to catch those errors. We use a try-catch block to accomplish this.
Our client and server communicate with JSON. So we load a JSON response class before we try to process the request. This way, we can catch most errors and return a properly structured object to the client. We will see that class a bit later.
I usually like to keep the files organized and put all the require/include statements in the same place, near the start of the file. It can’t be directly at the start, since the strict declaration needs to be there. However, I also want to catch cases where a file can’t be required. So this time my require statements are split, and the second one is inside the try-catch block.
Our entry point doesn’t create the board itself. However, it knows that, to process the request, it needs to call createBoard in our Backend class. Then it sends what it gets back in JSON format.
__DIR__ is a PHP magic constant. It always contains the directory where the current file is located. This means that in any file that is being required, it returns the path of that specific file, not the file that included/required it. By passing __DIR__ to the Backend class, we help avoid broken relative paths when loading different files. Magic constants can be very helpful when used right.
$_GET is an associative array that contains the parameters we received with the request. We can also use $_REQUEST, which includes them. But that includes parameters from any type of request, like POST, and even the cookies. I want to be specific and tell it to give me only the query-string parameters. It’s part of being strict: “Request things the way I want, or I won’t respond the way you want”.
But what about the board?
Ok, we know how to prepare to handle the request. Time to see how our script actually does what we want it to. Let’s take a look at our Backend→createBoard method.
public function createBoard( array $query ): array {
$includeLayouts = $query['includeLayouts'] ?? '1';
if ( $includeLayouts !== '0' && $includeLayouts !== '1' ) {
throw new InvalidArgumentException( 'includeLayouts must be "0" or "1".' );
}
$deckRepository = new DeckRepository( $this->directory . '/decks' );
$wantedDeck = $query['deck'] ?? Config::DEFAULT_DECK;
$deck = $deckRepository->get( $wantedDeck );
$layoutRepository = new LayoutRepository( $this->directory . '/layouts' );
$wantedLayout = $query['layout'] ?? Config::DEFAULT_LAYOUT;
$layout = $layoutRepository->get( $wantedLayout );
$generator = new BoardGenerator();
$tiles = $generator->create( $layout, $deck );
$data = [
'layoutLabel' => $layout['label'],
'deck' => $deck->summary(),
'layers' => count( $layout['layers'] ),
'tiles' => $tiles,
];
if ( $includeLayouts === '1' ) {
$data['layouts'] = $layoutRepository->list();
}
return $data;
}
Our Backend class is like the person at a hotel’s front desk. They know how to get us a valid layout, with deck descriptions and tile placements. This useful person doesn’t leave their position to get us these things. They also don’t need to do the actual work. Instead, they just “use” others.
The Backend checks whether it needs to provide a list of possible layouts. This affects the response it will send. This means the client can get a slightly shorter response.
It checks which deck and layout to send back. To keep things interesting, the default is random.
A quick summary
So far, our request for a board flows like this:
- The JavaScript client is sends a request.
- The entry point adds some guards and calls our useful
Backendclass. - The
Backendclass then coordinates the handling of the request. - Once the work is done, the
Backendclass gathers all the data in an associative array and returns it to the entry point. - From there, the entry point asks the
JsonResponseclass to send back the array to the JavaScript client. - If the entry point detects an error during this process, it asks
JsonResponseto send an error instead. - The JsonResponse encodes the data it gets into a JSON string and sends it to the client (we will see it later).
- The JavaScript client receives a JSON string and processes it into an object. The object might be an error or the board.
We saw that the Backend works with repositories and a board processor. But we haven’t yet seen what those actually do, or how the board is actually processed.
The Repositories
As you saw, the createBoard method uses two repository classes: DeckRepository and LayoutRepository. These classes are named that way so it’s easy to spot that we are using the Repository Design Pattern. This means we have a layer between our logic and our data. Our logic doesn’t care where the data comes from. It can be a database, files, a remote API, and so on. So, if we are ever to change the source of the data to, say, a database, the code handling the logic doesn’t need to change, only the repository classes.
The Layout Repository
This is the part that works with the JSON file we covered in the Creating a Mahjong Board Layout with JSON tutorial.
Getting ready to work
The LayoutRepository is in charge of providing the layout’s configuration. To do this, the repository loads the JSON files, validates them, and keeps a list of valid files and their content. Having just 144 tiles to place, the files are small. However, since we may end up with many layout files that might need to be changed, there is no need to be greedy.
private function init(): void {
if ( $this->layouts !== null ) {
return;
}
$files = glob( $this->directory . '/*.json' );
if ( $files === false ) {
throw new RuntimeException( 'The layout directory could not be read.' );
}
$layouts = [];
foreach ( $files as $file ) {
$name = pathinfo( $file, PATHINFO_FILENAME );
try {
$layouts[ $name ] = $this->load( $file, $name );
} catch ( RuntimeException $error ) {
// If the layout can't be loaded, skip it.
continue;
}
}
if ( $layouts === [] ) {
throw new RuntimeException( 'No valid Mahjong layouts were found.' );
}
$this->layouts = $layouts;
}
The init method is marked as private and is called by the repository itself before getting the layouts list or a single layout. That is why we check before it runs that it hasn’t already done its task. It would be a shame to work twice, and it would also be very inefficient. It uses the glob function, so the files are loaded according to a pattern. In our case, it only returns files that end in .json. We could also use a DirectoryIterator with the glob:// wrapper.
Loading a layout file
Each file found by the glob function in init is loaded. Loading it is also quite simple:
private function load( string $file, string $name ): array {
$json = file_get_contents( $file );
if ( $json === false ) {
throw new RuntimeException( sprintf( 'Could not read layout "%s".', $name ) );
}
try {
$layout = json_decode( $json, true, 512, JSON_THROW_ON_ERROR );
} catch ( JsonException $error ) {
throw new RuntimeException( sprintf( 'Layout "%s" contains invalid JSON: %s', $name, $error->getMessage() ) );
}
$validator = new LayoutValidator();
$validator->validate( $layout, $name );
return [ 'name' => $name, 'label' => $layout['label'], 'layers' => $layout['layers'] ];
}
load reads the JSON file, then tries to decode the string into an associative array and runs a layout validator. We already saw earlier that if loading the file fails, we skip it and continue to the next. This includes calls to $validator->validate, which might throw an exception.
Getting the data
After the RepositoryLayout sorts out the layouts, getting a list of names and labels is quite simple.
public function list(): array {
$this->init();
$choices = [];
foreach ( $this->layouts as $layout ) {
$choices[] = [
'name' => $layout['name'],
'label' => $layout['label']
];
}
return $choices;
}
To allow us to get a single layout configuration by name or at random. This class also has a get method:
public function get(mixed $requestedLayout='random'): array {
$this->init();
if ( $requestedLayout === 'random' ) {
$requestedLayout = (string) array_rand( $this->layouts );
}
if ( ! is_string( $requestedLayout ) || ! isset( $this->layouts[ $requestedLayout ] ) ) {
throw new InvalidArgumentException( 'Unknown board layout.' );
}
return $this->layouts[ $requestedLayout ];
}
After running init, we know that $this->layouts contains the existing, validated layouts, so the method doesn’t need to do anything fancy.
Actually, we don’t know that they are really validated yet. We still haven’t reviewed the load method used by the init method.
Making sure the data is valid
Loading the layout configuration from the file itself is a matter of:
- Reading its contents
- Making sure it can be decoded into an associative array.
- And then, doing some deeper validation.
private function load(string $file, string $name): array {
$json = file_get_contents( $file );
if ( $json === false ) {
throw new RuntimeException( sprintf( 'Could not read layout "%s".', $name ) );
}
try {
$layout = json_decode( $json, true, 512, JSON_THROW_ON_ERROR );
} catch ( JsonException $error ) {
throw new RuntimeException( sprintf( 'Layout "%s" contains invalid JSON: %s', $name, $error->getMessage() ) );
}
$validator = new LayoutValidator();
$validator->validate( $layout, $name );
return [ 'name' => $name, 'label' => $layout['label'], 'layers' => $layout['layers'] ];
}
The deeper validation is the more interesting one.
Deeper validation
If you check the LayoutValidator class, you’ll see that it requires quite a bit of work to create. I remember when I first started coding and did these kinds of validation, one of my first thoughts was: “But I wrote the file myself”. Older me’s answer to that is: “But everyone makes mistakes”. At least I’m pretty sure I’m not the only one. Mistakes happen, files can get corrupted, and who knows what else. Our code needs to be prepared for this “remote” possibility.
Most of the LayoutValidator code is quite simple. However, it does have some interesting bits when it comes to the tiles’ placement itself. Let’s see how the less common validation works.
The general concept is that our layout files contain an array of layers. Each layer in that array contains an array of rows, and each row contains a string of characters representing column markers:
public const string LAYOUT_TILE_MARKER = '#'; public const string LAYOUT_EMPTY_MARKER = '.';
An important detail from the layout tutorial is that a row or column step is only half a tile. Meaning a tile covers two columns and/or two rows. # marks where a tile starts. That tile then covers two columns and two rows of these smaller cells. A . means no tile starts at that position. The position can still be covered by a tile starting beside or above it.
For example, a tile starting at row 4, column 6 covers these cells:
Those are four cells belonging to one tile. We use keys such as 4:6 to look up each cell in a PHP array. Once we can track occupied cells, the same little two-by-two patch answers both questions: “Does this tile overlap another one?” and “Is this tile fully supported?”
Carrying the coverage map up the stack
As we go over all the layers, from the bottom to the top, we keep track of a couple of things:
$coveredCells: Cells that already have a tile on the current layer. Used to catch overlaps.$layerBelow: The cells that already have a tile on the layer directly below the current one. Used to check for support.
validateLayers has the loop that carries this mapping from one layer to the next:
private function validateLayers( mixed $layers, string $name ): void {
if ( ! is_array( $layers ) || ! array_is_list( $layers ) || $layers === [] ) {
throw new RuntimeException( sprintf( 'Layout "%s" needs a non-empty list of layers.', $name ) );
}
$tileCount = 0;
$layerBelow = null;
foreach ( $layers as $layerNumber => $rows ) {
$layerLabel = sprintf( 'Layout "%s", layer %d', $name, $layerNumber + 1 );
$validatedLayer = $this->validateLayer( $rows, $layerBelow, $layerLabel );
$layerBelow = $validatedLayer['coveredCells'];
$tileCount += $validatedLayer['tileCount'];
}
$this->validateTileCount( $tileCount, $name );
}
$layerBelow starts as null because the ground layer has no supporting layer to check. For the first call, validateLayer receives that null and builds the ground layer’s coverage map.
The assignment deserves a second look: PHP finishes the method call on the right before assigning its result to the left. The method receives the previous layer’s map. Only when it returns does $layerBelow become the map for the layer we just finished.
We replace that map instead of combining it with older layers. A tile on layer 2 needs support from layer 1. A tile two floors down cannot reach through a gap to hold it up.
The loop also adds each layer’s tile count. We’ll come back to the division by four once we’ve seen how those cells get recorded.
Building the current layer’s map
Each layer gets a fresh $coveredCells array:
private function validateLayer( mixed $rows, ?array $layerBelow, string $layerLabel ): array {
if ( ! is_array( $rows ) || ! array_is_list( $rows ) || $rows === [] ) {
throw new RuntimeException( $layerLabel . ' must contain a non-empty list of rows.' );
}
$coveredCells = [];
$tileCount = 0;
foreach ( $rows as $rowNumber => $row ) {
$this->validateRow( $row, $rowNumber, $layerBelow, $coveredCells, $layerLabel );
$tileCount += substr_count( $row, Config::LAYOUT_TILE_MARKER );
}
return [ 'coveredCells' => $coveredCells, 'tileCount' => $tileCount ];
}
This map starts empty even when there is a full layer below us. Occupying the same row and column on two different layers is perfectly normal; that is how we stack tiles. Only sharing cells on the same layer is an overlap error.
Every row contributes to the same current-layer map. That matters because a tile starting in a later row can overlap one that started in an earlier row. Resetting the map for each row would miss those collisions.
After all rows pass, we return the completed map. That is the value the outer loop saves as the next $layerBelow.
Finding the tile starts in a row
The row tells us where to start checking each tile:
private function validateRow(
mixed $row,
int $rowNumber,
?array $layerBelow,
array &$coveredCells,
string $layerLabel,
): void {
$markers = Config::LAYOUT_EMPTY_MARKER . Config::LAYOUT_TILE_MARKER;
$pattern = '/^[' . preg_quote( $markers, '/' ) . ']+$/D';
if ( ! is_string( $row ) || preg_match( $pattern, $row ) !== 1 ) {
throw new RuntimeException( sprintf(
'%s, row %d must be a non-empty string containing only "%s" and "%s".',
$layerLabel,
$rowNumber,
Config::LAYOUT_EMPTY_MARKER,
Config::LAYOUT_TILE_MARKER,
) );
}
for ( $column = 0, $length = strlen( $row ); $column < $length; $column ++ ) {
if ( $row[ $column ] === Config::LAYOUT_TILE_MARKER ) {
$this->validateTile( $rowNumber, $column, $layerBelow, $coveredCells, $layerLabel );
}
}
}
To be honest, I never liked regex much. However, they can be helpful. The $pattern variable here is actually: '/^[.#]+$/D' and it is checking the following:
^: From the start of the string.[.#]+: One or more dots or hash signs.$: To the end of the string.D: Requires the actual end, rejecting even a trailing newline.
After we make sure the row fits the regex pattern, we go over all the characters in that row. Every LAYOUT_TILE_MARKER character (#) is a tile we need to validate.
The & in array &$coveredCells means the array is passed by reference. The row and tile methods update the same coverage map created for this layer. Those updates remain available when we move on to the next tile or row.
Checking all four cells of a tile
Now we turn a single tile start into its complete footprint:
private function validateTile(
int $row,
int $column,
?array $layerBelow,
array &$coveredCells,
string $layerLabel,
): void {
foreach ( [ [ 0, 0 ], [ 0, 1 ], [ 1, 0 ], [ 1, 1 ] ] as [$rowOffset, $columnOffset] ) {
$key = ( $row + $rowOffset ) . ':'. ( $column + $columnOffset );
$this->validateOverlap( $coveredCells[ $key ] ?? null, $row, $column, $layerLabel );
$this->validateSupport( $key, $layerBelow, $row, $column, $layerLabel );
$coveredCells[ $key ] = [ 'row' => $row, 'column' => $column ];
}
}
The four offset pairs are relative to the starting position:
[0, 0]– The starting tile.[0, 1]– One cell to the right.[1, 0]– One row below.[1, 1]– One diagonally below-right.
For our tile at (4, 6), they produce 4:6, 4:7, 5:6, and 5:7.
For each key, we first check whether the current layer already owns that cell. We then check whether the supporting layer contains it. Only after both checks pass do we record the cell in $coveredCells.
The stored value contains the starting row and column of the tile that owns the cell. For example, all four cells of our example tile store ['row' => 4, 'column' => 6].
Catching overlaps on the same layer
Here is the first check called for each cell:
private function validateOverlap( ?array $other, int $row, int $column, string $layerLabel ): void {
if ( $other === null ) {
return;
}
if ( $other['row'] === $row ) {
$reason = sprintf(
'Tiles in adjacent columns overlap; use "%s%s%s" instead of "%s%s".',
Config::LAYOUT_TILE_MARKER,
Config::LAYOUT_EMPTY_MARKER,
Config::LAYOUT_TILE_MARKER,
Config::LAYOUT_TILE_MARKER,
Config::LAYOUT_TILE_MARKER,
);
} elseif ( $other['column'] === $column ) {
$reason = 'Tiles in adjacent rows overlap; leave an empty position between tile starts vertically.';
} else {
$reason = 'Tiles overlap diagonally; separate tile starts by at least two positions along a row or column.';
}
throw new RuntimeException( sprintf(
'%s, row %d, column %d: %s',
$layerLabel,
$row,
$column,
$reason,
) );
}
$coveredCells[$key] ?? null supplies the existing owner, or null if nobody has claimed this cell yet. An unclaimed cell is fine. An existing owner means two tiles are trying to occupy the same part of the current layer, so validation stops.
Imagine we already placed the tile at (4, 6). Another start at (4, 7) shares its right-hand cells. A start at (5, 6) overlaps vertically, and one at (5, 7) shares the corner cell 5:7. Checking all four cells catches all three cases without needing three separate collision algorithms.
The row and column comparisons choose the error explanation. The collision has already been detected by finding an owner for the key. That is also why ## is rejected but #.# is allowed: neighboring tile starts need a whole tile’s width, or two half-tile steps, between them.
Requiring support under the whole tile
The second check looks in the other map:
private function validateSupport(
string $key,
?array $layerBelow,
int $row,
int $column,
string $layerLabel,
): void {
if ( $layerBelow !== null && ! isset( $layerBelow[ $key ] ) ) {
throw new RuntimeException( sprintf(
'%s, row %d, column %d: the tile must be fully supported by the layer immediately below it.',
$layerLabel,
$row,
$column,
) );
}
}
On the ground layer, $layerBelow is null, so support is not required. On every upper layer, the key must exist in the map immediately below. Because validateTile calls this for all four keys, one missing cell is enough to reject the tile. Checking only the cell at its starting position could leave the rest of it hanging over an edge.
We check covered cells, rather than asking whether another # starts directly below this one. A tile can rest on one aligned lower tile or span several lower tiles. For example, an upper tile starting at (1, 1) can rest over four lower tiles:
Each lower tile contributes one cell under the upper tile. All four keys exist in $layerBelow, so its footprint is fully supported. There is no rule requiring exactly four supporting tiles; the requirement is that all four cells have support.
An empty array is different from null here. An empty array means a layer exists below us but contains no tiles. We must still check it, and any upper tile will fail. Only the ground layer gets to skip the support check.
The code in the zip file contains the full LayoutValidator class with the rest of the checks. Check it out if you want to see them all. Can you think of validations we didn’t do? I have a feeling this was too short to cover everything.
There is one important check we still need to do. A very important one: Making sure the board is solvable. We will get to it in a bit.
The Deck Repository
So far we’ve kept talking about the layout. The layout isn’t all the data we have. If layout is the shape, the deck is the theme. A layout tells us where a tile goes. A deck tells us what is on it and what it can match. The demo includes WDP drawings and classic Mahjong drawings. Both contain 144 tiles and 42 distinct faces.
It’s a JSON configuration… again
I’ll show the configuration here in parts. Since we care about accessibility in our game interface, we want to know what to call our tiles. If the artwork can be replaced by using a different deck, we might also need to replace the names. Calling a tile “1 dot” and having 1 triangle on the tile itself doesn’t feel right. So, in addition to supplying just a different CSS, we also have a different JSON file for each deck.
Mahjong has three suits of numbered tiles. If you look at decks/wdp.json, the numbered tiles configuration is:
{
...
"numberedSuits": {
"tilesPerSuit": 9,
"copiesPerTile": 4,
"suits": [
{
"id": "dots",
"label": {
"singular": "{number} triangle",
"plural": "{number} triangles"
}
},
...
]
},
...
}
Listing all nine pictures in each suit is too much work. So, instead, we set the suit length, copies per face, and a label with {number}. We later create the full suits with our code.
Mahjong also has other tile types. They can have slightly different matching rules. A named group can work differently. For example, all the tiles in the flowers suit can be matched with each other.
{
"id": "flowers",
"copiesPerTile": 1,
"matchTogether": true,
"tiles": [
{
"id": "daffodil",
"label": "Daffodil flower"
},
{
"id": "orchid",
"label": "Orchid flower"
},
{
"id": "rose",
"label": "Rose flower"
},
{
"id": "tulip",
"label": "Tulip flower"
}
]
},
With matchTogether: true, two different flowers can match. Without it, only tiles with the same drawing match. Check out the decks/wdp.json file itself for the rest of the suits configuration:
- Winds
- Seasons
- Dragons (also known as our mighty owls)
Not just JSON
The deck needs a CSS file that controls the style changes, mainly the drawings on the tiles. We saw we can invent new tile names to describe their artwork better. However, the game expects certain classes to exist in the CSS file. Therefore, the CSS contains the original tiles’ names.
Getting the deck data
Just like the LayoutRepository handled the layouts data, the DeckRepository does the same for the decks. Well, not exactly the same. It does have very similar init, list, load, and get.
I probably should have created a base repository, like a JsonFileRepository or something similar, and extended it, or an interface to keep the code organized and make sure the needed methods are implemented. But the backend already took over this tutorial, so I’ll refrain from it for now.
The load method is worth going over, since it includes something extra:
private function load(string $file, string $name): Deck
{
$json = file_get_contents($file);
if ($json === false) {
throw new RuntimeException(sprintf('Could not read deck "%s".', $name));
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
throw new RuntimeException(sprintf('Deck "%s" contains invalid JSON: %s', $name, $error->getMessage()));
}
$deck = new Deck($data, $name);
$stylesheet = $this->directory . '/' . $name . '.css';
if (!is_file($stylesheet)) {
throw new RuntimeException(sprintf('Deck "%s" stylesheet "%s.css" was not found.', $name, $name));
}
return $deck;
}
As we can see, it is not enough for the JSON file to exist and be valid JSON. We also verify that a CSS file, with the same name as the .json file, exists.
The main differences between the LayoutRepository and the DeckRepository are:
- The
DeckRepositoryreturns anew Deckvariable and not just an array. - A deck configuration also includes a CSS file.
Oh, and to keep things interesting, the deck can’t be selected by the player. It is always random.
The deck
You might wonder why we need a Deck class if we don’t need a Layout class. Remember that earlier I thought it was too much work to create all the numbered tiles in the configuration? That is the reason. I’d rather add a few lines of code than describe the same type of tiles 9 times for 3 suits. The deck gets its configuration from the file, but still has some work to do, as a Deck.
It already starts at the Deck constructor:
public function __construct(mixed $data, string $name)
{
$validator = new DeckValidator();
$validator->validate($data, $name);
$this->init($data, $name);
}
Notice that we run deck data validation at the class level, not from the repository, for this one. We do that so that, no matter where a deck is initialized, if its configuration data isn’t valid, it won’t be created.
About the validation
The repository checks the basics. It checks that the files exist and are readable. While deck validation is simpler than layout validation, we still have a few things to check:
- All the needed information is in the JSON file.
- The resulting tile count is correct (144).
- Labels are in the right format.
- All the tiles are configured to have a pair.
- No duplicate IDs.
We also write the deck configuration files, so it raises the question of why we run all these tests at runtime. Why not just validate the files in a script and run it after the files are created? Isn’t it too much work to do while waiting for a response from the server? To answer this, remember that files are also inputs. We should always validate inputs. Running these tests has a small impact on response time. However, having invalid configuration will hurt the game and might even make it unplayable.
After reviewing the LayoutValidator, the DeckValidator doesn’t seem to need any special explanation. However, if you find yourself staring at the code in the file, leave a question in the comments.
Preparing the deck
We saw in the deck constructor that it calls init after the configuration data is validated. That is where we add the “missing” tiles’ definitions.
private function init(array $data, string $name): void
{
$faces = [];
foreach ($data['groups'] ?? [] as $group) {
$faces = array_merge($faces, $this->createGroupFaces($group));
}
if (isset($data['numberedSuits'])) {
$faces = array_merge($faces, $this->createNumberedFaces($data['numberedSuits']));
}
$this->definition = ['name' => $name, 'label' => $data['label'], 'faces' => $faces];
}
Different definitions apply to different types of suits. For the special suits (also known as “grouped”):
private function createGroupFaces(array $group): array
{
$faces = [];
foreach ($group['tiles'] as $tile) {
$id = $group['id'] . '-' . $tile['id'];
$match = ($group['matchTogether'] ?? false) ? 'group:' . $group['id'] : 'face:' . $id;
$faces[] = ['id' => $id, 'label' => $tile['label'], 'copies' => $group['copiesPerTile'], 'match' => $match];
}
return $faces;
}
The grouped suits need to account for whether we can match their tiles together. For example, if “seasons-winter” matches with “seasons-spring”. If so, it adds a matching rule like: group:seasons. But if matchTogether is false, the matching rule will be the exact label for the match.
The numbered suits need a different kind of preparation:
private function createNumberedFaces(array $numbered): array
{
$faces = [];
foreach ($numbered['suits'] as $suit) {
for ($number = 1; $number <= $numbered['tilesPerSuit']; $number++) {
$id = $suit['id'] . '-' . $number;
$form = $number === 1 ? 'singular' : 'plural';
$label = str_replace('{number}', (string) $number, $suit['label'][$form]);
$faces[] = ['id' => $id, 'label' => $label, 'copies' => $numbered['copiesPerTile'], 'match' => 'face:' . $id];
}
}
return $faces;
}
It uses the tilesPerSuit to create the tiles I skipped in the JSON file. And to avoid dealing with spelling rules, it uses a singular label for the tile representing one and a plural label for the rest.
Once this code runs, my laziness is no longer a problem, and our deck is ready to use.
Processing the layout
So now we are at a point where we have everything we need to build a board. I can’t make any more excuses for delays. Let’s move to the reason we are in this tutorial to begin with. Let’s turn all this configuration data into a full board configuration.
The browser needs positions it can use, rather than rows full of dots. For this, we have the BoardGenerator class.
public function create(array $layout, Deck $deck): array
{
$positions = $this->createPositions($layout);
$removalPlan = $this->createRemovalPlan($positions);
$facePairs = $deck->createPairs();
$tiles = [];
foreach ($removalPlan as $pairIndex => $positionIds) {
foreach ($positionIds as $tileIndex => $positionId) {
$tiles[] = array_merge($positions[$positionId], $facePairs[$pairIndex][$tileIndex]);
}
}
return $tiles;
}
create does a few things:
- builds the positions we can place tiles in
- finds a removal plan, and asks the deck for matching pairs
- joins each pair to two positions from that plan.
Let’s dive into these methods. To create positions for tile placement, we need to loop over the layers in the layout. Each layer has its own tile positions.
private function createPositions(array $layout): array
{
$positions = [];
foreach ($layout['layers'] as $layerNumber => $rows) {
$positions = array_merge($positions, $this->createLayerPositions($rows, $layerNumber));
}
return $positions;
}
private function createLayerPositions(array $rows, int $layerNumber): array
{
$positions = [];
foreach ($rows as $rowNumber => $row) {
for ($column = 0, $length = strlen($row); $column < $length; $column++) {
if ($row[$column] === Config::LAYOUT_EMPTY_MARKER) {
continue;
}
$id = sprintf('%d-%d-%d', $layerNumber, $rowNumber, $column);
$positions[$id] = [
'id' => $id,
'layer' => $layerNumber,
'row' => $rowNumber,
'column' => $column,
];
}
}
return $positions;
}
An ID such as 2-4-6 means layer 2, row 4, column 6.
We keep positions in an associative array keyed by those IDs. That lets the generator look up a tile directly, while another small array tracks which positions remain. It avoids deleting and rebuilding the full position data at every step.
Making sure it is solvable
For this game, we will make a simple solver.
We could deal random pictures and then try to solve the result. That works, but the solver would need to search through matching choices and undo bad ones. We can save ourselves some work by deciding on a legal removal order first.
Imagine the tiles are blank. Find two free positions, remove them, and repeat. If we reach an empty board, we have a complete plan. Now put matching pictures on each recorded pair. Following that same plan will clear the real board.
private function createRemovalPlan(array $positions): array
{
for ($attempt = 0; $attempt < Config::MAX_REMOVAL_PLAN_ATTEMPTS; $attempt++) {
$plan = $this->tryCreateRemovalPlan($positions);
if ($plan !== null) {
return $plan;
}
}
throw new RuntimeException('Could not create a solvable board.');
}
private function tryCreateRemovalPlan(array $positions): ?array
{
$remaining = array_fill_keys(array_keys($positions), true);
$plan = [];
while ($remaining !== []) {
$freeIds = $this->findFreePositionIds($positions, $remaining);
if (count($freeIds) < 2) {
return null;
}
shuffle($freeIds);
$pair = [$freeIds[0], $freeIds[1]];
$plan[] = $pair;
unset($remaining[$pair[0]], $remaining[$pair[1]]);
}
return $plan;
}
This is a randomized greedy search with retries. “Greedy” means it picks a legal pair now, without planning all the later choices. It doesn’t backtrack within an attempt. If it gets stuck, the attempt returns null, and we start again from the beginning.
?array means the method can return an array or null. A complete plan is an array; null tells the caller this attempt got stuck.
I believe in the saying “If at first you don’t succeed, try, try again”. However, we can’t try forever. At some point we need to say: “ok, this can’t be solved”. In our case, it doesn’t really mean it can’t be solved. But it does mean we tried enough times. Meaning, we have to set a limit on how many times we try to create a removal plan. It might mean that even though the layout is valid, it’s too hard to solve. In any case, we need to avoid an infinite loop.
The tryCreateRemovalPlan method calls findFreePositionIds, which returns the IDs of all remaining positions that are currently free.
private function findFreePositionIds(array $positions, array $remaining): array
{
return array_values(array_filter(
array_keys($remaining),
fn (string $id): bool => $this->positionIsFree($positions[$id], $positions, $remaining),
));
}
private function positionIsFree(array $position, array $positions, array $remaining): bool
{
$leftIsBlocked = false;
$rightIsBlocked = false;
foreach ($remaining as $otherId => $_) {
if ($otherId === $position['id']) {
continue;
}
$other = $positions[$otherId];
if (
$other['layer'] > $position['layer']
&& abs($other['row'] - $position['row']) <= 1
&& abs($other['column'] - $position['column']) <= 1
) {
return false;
}
if (
$other['layer'] === $position['layer']
&& abs($other['row'] - $position['row']) <= 1
) {
$leftIsBlocked = $leftIsBlocked
|| $other['column'] === $position['column'] - 2;
$rightIsBlocked = $rightIsBlocked
|| $other['column'] === $position['column'] + 2;
}
}
return !$leftIsBlocked || !$rightIsBlocked;
}
A tile above us overlaps if its row and column are each at most one half-step away. We check any higher layer. A tile beside us blocks the left or right edge if it is on the same layer, two column steps away, and overlaps our row.
Both side flags start as false. We return false as soon as we find something covering the tile. Otherwise, !$leftIsBlocked || !$rightIsBlocked means at least one side is clear.
It isn’t the surest way to get a solvable board. Nor is it the most efficient one. Another possible solution is recursive backtracking. When a pair leads to a dead end, we undo that choice and try another pair instead of restarting the entire board. Exploring every alternative will find a removal plan if one exists, or establish that none exists. However, that search can become expensive, which is why this demo uses a simpler search with a fixed attempt limit.
(To deal with the board not being 100% solvable, we will later add shuffle to the client side of the game)
From a plan to a board
We now have a board that should be solvable, but we are missing the lovely artwork. We need to create pairs of tiles so the player can actually see the pairs and play.
The Deck class we saw earlier has a createPairs method:
public function createPairs(): array
{
$deck = $this->definition;
$matchingSets = [];
foreach ($deck['faces'] as $face) {
$tile = ['face' => $face['id'], 'match' => $face['match'], 'label' => $face['label']];
for ($copy = 0; $copy < $face['copies']; $copy++) {
$matchingSets[$face['match']][] = $tile;
}
}
$pairs = [];
foreach ($matchingSets as $tiles) {
shuffle($tiles);
for ($index = 0, $count = count($tiles); $index < $count; $index += 2) {
$pairs[] = [$tiles[$index], $tiles[$index + 1]];
}
}
shuffle($pairs);
return $pairs;
}
createPairs makes the requested copies, groups them by matching key, and shuffles each group. It splits those groups into pairs, then shuffles the list of pairs. Different flower pictures may share a pair, while an ordinary face’s group contains identical copies.
Back in BoardGenerator::create, those pairs are assigned to the removal plan. So every successfully returned new board has a complete legal route to an empty board. The player can still choose another matching pair and get stuck later. A local match and a good long-term move are two different things.
Preparing the response to the client
The response from Backend::createBoard looks like:
{
"layoutLabel": "Classic turtle",
"deck": {
"name": "classic",
"label": "Classic",
"stylesheet": "decks\/classic.css"
},
"layers": 5,
"tiles": [
{
"id": "2-4-10",
"layer": 2,
"row": 4,
"column": 10,
"face": "seasons-spring",
"match": "group:seasons",
"label": "Spring season"
},
{
"id": "1-6-18",
"layer": 1,
"row": 6,
"column": 18,
"face": "seasons-winter",
"match": "group:seasons",
"label": "Winter season"
},
{
"id": "0-0-8",
"layer": 0,
"row": 0,
"column": 8,
"face": "dots-4",
"match": "face:dots-4",
"label": "4 dots"
}
...
],
"layouts": [
{
"name": "cat",
"label": "Cat"
},
{
"name": "classic",
"label": "Classic turtle"
},
{
"name": "owl-head",
"label": "Owl Head"
}
]
}
You can see it is not a full response since it has just 3 tiles. A full response will include 144.
The response contains:
- Layout label
- Deck (name, label, stylesheet)
- Tiles (id, layer, row, column)
- A list of layouts (can be excluded by adding
includeLayouts=0to the request)
The JsonResponse class contains a few things that are worth a look.
final class JsonResponse {
private int $bufferLevel;
private ?string $memoryReserve;
public function __construct() {
$this->bufferLevel = ob_get_level();
ob_start();
set_error_handler( [ $this, 'handleError' ] );
$this->memoryReserve = str_repeat( ' ', 64 * 1024 );
register_shutdown_function( [ $this, 'handleShutdown' ] );
}
/**
* @throws ErrorException
*/
public function handleError( int $severity, string $message, string $file, int $line ): bool {
if ( ( error_reporting() & $severity ) === 0 ) {
return false;
}
throw new ErrorException( $message, 0, $severity, $file, $line );
}
public function handleShutdown(): void {
$this->memoryReserve = null;
$error = error_get_last();
$fatalTypes = [ E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ];
if ( $error !== null && in_array( $error['type'], $fatalTypes, true ) ) {
$this->write( '{"error":"The board request could not be completed."}', 500 );
}
}
private function write( string $json, int $status ): void {
while ( ob_get_level() > $this->bufferLevel ) {
ob_end_clean();
}
http_response_code( $status );
header( 'Content-Type: application/json; charset=utf-8' );
header( 'Cache-Control: no-store' );
echo $json;
}
}
When the class is instantiated, it joins the effort of always sending a JSON response. register_shutdown_function registers a method to be called when the script exits. This method will be called whether the script finished successfully or not, even if there was an error we didn’t catch. handleError registers an error handler that tries to convert reported PHP warnings into exceptions. Without it, a warning could appear before the JSON, which would prevent the client from decoding the JSON string into an object.
The class also uses a nice little trick so it can still send a response in cases of memory failures. By assigning a value to $memoryReserve, we make sure we can use that space if a memory allocation problem occurs. When the handleShutdown method runs, it releases the $memoryReserve memory by setting its value to null.
The constructor starts an output buffer. That gives us a place to catch accidental output from a required file. Before writing JSON, write clears buffers opened since this process began. It leaves any older buffers alone.
We also set a few headers:
'Content-Type: application/json; charset=utf-8': to tell the browser this is JSON.Cache-Control: no-storeto tell it not to keep an old generated board as the answer to a later request.
Final words
That was longer than expected, but it will all be worth it. Now we have a backend we can use to ask for new Mahjong boards, and in the next tutorial we are going to get into the JavaScript and finally build the game. The game itself, btw, is ready, so it shouldn’t take too long. In the meantime, we covered quite a lot, but we still left a lot out. Download the ZIP, review the code, and see if you can improve it while still getting the same response. Or stay tuned till the next part, in a few days.