Skip to content
ImagineWorld

Building WebAssembly Checkers

node_idnode-book_programming-web-assembly-with-rust_chapter-02-building-webassembly-checkers
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleBuilding WebAssembly Checkers
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Building WebAssembly Checkers

Section titled “Chapter 2 — Building WebAssembly Checkers”

…the imagination is unleashed by constraints. You break out of the box by stepping into shackles. Jonah Lehrer

CHAPTER 2

Building WebAssembly Checkers

Sample applications small enough to fit into a quick blog post are very good at giving you a quick, painless introduction to some new piece of syntax. They show you how to print to the console, they show you how many parentheses you might normally need for a given line of code, and you get to see working code so long as you don’t mind lacking the context of the surrounding appli- cation not shown in the post.

Even when full applications are created, the nature of the easily consumed medium means that these illustrative applications often look nothing like real- world applications, and they bear little to no resemblance to anything you might deploy to production.

In this chapter, you won’t be creating a contrived “Hello, World” WebAssembly module. Instead, you’ll be creating a module that can be used to run a game of checkers (also called draughts depending on which part of the world you are from).

You’ll build this module by creating a series of small functions that, once complete, will work together to provide the fundamentals of a working checkers game. There’s always a trade-off between the complexity of a real application and the need to keep an example simple enough to be used as a learning tool, so we cut a few corners on evaluating some game rules and edge cases, but the code will be playable when you’re done.

Playing Checkers, the Board Game

If you’ve played checkers, then you can probably skip this section. If you need a refresher, then this will still be a quick read.

Checkers is a fairly simple game played on an 8x8 game board. The board’s squares are typically alternating colors (one of the most common in the US is a black and red board).

Each player then positions 12 pieces on the board in fixed squares spaced evenly one square apart from each other. One player controls the black pieces and another controls the white (or red) pieces. The player controlling the black pieces makes the first move.

The simplest move is where a piece is allowed to slide diagonally on the board if there is no other player occupying that spot. If there is, you might be able to jump and capture that player’s piece. Players take turns moving or jumping (which can include multiple jumps per turn if pieces are positioned right) until one player reaches the opponent’s home row. This row is called the kings row or crownhead. Once in the opponent’s kings row, the player’s piece is crowned and gains the ability to move either backward or forward.

The game is over when one player has captured all of their opponent’s pieces, or left their opponent with no more legal moves. When neither side can force a win, the game ends in a draw.

Coping with Data Structure Constraints

if you were to build this game using a high-level programming language like Java, Rust, Python, or even C++, then you would likely have a very different approach to setting up the data structures needed for the game than what you’ll use in WebAssembly.

From the rules described in the previous section, you’re going to need to hold the state of an 8x8 game board. The positions on this game board can be empty, or they can hold black or white pieces. In this section, you’ll learn how to manage this kind of state in WebAssembly using nothing but the limited data structures available to the language.

If you’re playing along with the home game, then you’ll be creating functions throughout the chapter as you’re exposed to more fundamental WebAssembly language primitives and concepts. To get started, let’s create a directory for our project. I called mine wasmcheckers but you can choose anything. One advantage of writing code at this low level is we’re just going to end up with a single text file—no project files, no Makefiles, just text.

Create a checkers.wat file in your project directory and define an empty module:

(module
(memory $mem 1)
)

The 1 in the memory declaration indicates that the memory named $mem must have at least one 64KB page of memory allocated to it. Memory can grow at the request of either the Wasm module or the host.

You can compile this with wat2wasm and then examine the contents with wasm-objdump before moving on to the details of state management. You should see some output that looks like the following:

$ wasm-objdump checkers.wasm -x
checkers.wasm: file format wasm 0x1
Section Details:
Memory:
- memory[0] pages: initial=1

As you continue through this chapter, if you get curious about things you can always compile and then use the tools to examine what ended up in the compiled module.

Managing Game Board State

The first thing to tackle when it comes to managing the state of a game board is, obviously, the board itself. As mentioned, a checkerboard is an 8x8 grid. This probably triggers the part of your programmer brain that wants to declare a two-dimensional array. In Rust, that might look something like this:

let mut checkerboard: [[GamePiece; 8]; 8];

This is how most developers tend to visualize this problem, differences in syntax aside. But here’s the rub: WebAssembly doesn’t have arrays—single-dimension or otherwise. It also doesn’t have complex types, so you can’t create a struct or a tuple or even a hash map called GamePiece.

One thing that WebAssembly does have is linear memory. As we discussed in the preceding chapter, WebAssembly can have named, contiguous blocks of memory that it can write to, read from, import, or export. So if you’re going to use a linear memory block, how do you represent a two-dimensional array in that space?

The solution is to linearize the two-dimensional array. Many of your favorite programming languages most likely already do this linearization for efficiency without you noticing. The trick to linearization is figuring out the math behind converting an (x,y) coordinate pair into a memory offset.

In this figure, you can see some blocks that represent values in individual positions in memory. Above some of these are the corresponding (x,y) coordinate on the game board and below you see the unit offset of that piece of memory. For example, the coordinate (0,0) on the board is at unit offset 0. The coordinate (7,0) on the game board is at unit offset 7, coordinate (7,1) is at unit offset 15, and so on:

You may have detected a pattern, and the equation for that pattern is offset = (x + y*8), where 8 is the number of squares in a row. This would be fine if you were just linearizing a two-dimensional array into a one-dimensional space indexed as an array, but WebAssembly’s memory isn’t indexed like an array. It’s indexed by byte.

This means that if you’re going to store a 32-bit integer (4 bytes) in each spot on the game board, you need to adjust the equation to offset = (x + y*8) * 4 where 4 is the number of bytes per unit offset.

Thinking about data storage this way activated a part of my brain I had long since thought dead and covered in cobwebs. It takes a little getting used to, and it may feel like a harsh constraint compared to what you’re used to, but

If you stick with this until the end of the chapter, you’ll see how operating within these constraints pays off.

The foundation of the entire checkers game will be a function that determines the byte offset for a given X and Y coordinate, as this will be something your code is going to need to do every time it updates the board (this is inside the module declaration, after the memory declaration):

wasmcheckers/checkers.wat

(func $indexForPosition (param $x i32) (param $y i32) (result i32)
(i32.add
(i32.mul
(i32.const 8)
(get_local $y)
)
(get_local $x)
)
)
;; Offset = ( x + y * 8 ) * 4
(func $offsetForPosition (param $x i32) (param $y i32) (result i32)
(i32.mul
(call $indexForPosition (get_local $x) (get_local $y))
(i32.const 4)
)
)

The math being performed here boils down to the following:

offsetForPosition(1, 2)
= (1 + 2 * 8) * 4
= 68

The nesting of the multiplication and addition operators is a little tough to read, but it’s still manageable. Armed with the ability to determine where to put your game state, the next step is to figure out how to represent that state.

In each of the locations in linear memory, you have access to 32 bits (or 4 bytes). You don’t have the luxury of a complex structure or any language primitives for storing lists, fields, or tuples. You’ve just got raw bits, so how are you going to represent game state?

This dusts off another technique from the patterns vault called bit_flags. Bit flags is a technique for assigning meaning to individual bits within a number. When more than one consecutive bit are combined to store some other meaning, that’s typically called bit masking. Most of what we’re going to do is bit flags, though we’ll touch on masking briefly.

You can see the 8-bit number 00101101, but rather than simply meaning the numerical constant 45, this is actually a set of boolean values. As the previous image indicates, the value 45 carries all of the following meaning within the context of a fictional video game:

  • This game object is a player
  • Game object is not illuminated
  • Tutorial is completed
  • Healer has been discovered
  • The Elven king has not been slain
  • The player has access to fire magic
  • The player has not yet unlocked the cave of nightmares
  • The player is not a game master

When you describe certain data structures this way, you end up passing around simple, raw numeric values to represent players and game objects rather than high-level constructs like structs or enums.

Given strategies like bit flags or masking, it’s kind of surprising just how much information you can pack into a single number. Underneath all of your higher level languages, many structs are getting densely packed into numbers just like this. Tooling and compilers doing all this work on your behalf is a recurring theme, and you’re looking at the individual gears within your familiar machine now.

You can use bitwise logical operators on numbers to query and manipulate these bit values. For example, a bitwise AND operation compares each bit of one number with the corresponding bit of a second number, and if both bits in the same relative position are 1, then the bit in the resulting number will be 1. Otherwise, the output bit will be 0. A bitwise OR produces a 1 when either of the two compared bits are 1, and a bitwise XOR performs an exclusive or on the compared bits.

The following quick reference table will come in super handy when working with bit masked or “packed” values:

Logical OperationWebAssemblyBitmask Action
ANDi32.andQuery the value of a bit
ORi32.orSets a bit to true (1)
XORi32.xorToggles the value of a bit

So far, you’ve written a function that lets you convert a Cartesian checkerboard coordinate into a memory address, and you’ve seen how you can pack lots of data into simple integers for storage and retrieval. Now you can assign meaning to the bits of an integer on a checkerboard:

Binary ValueDecimal ValueGame Meaning
[unused 24 bits]…000000000Unoccupied Square
[unused 24 bits]…000000011Black Piece
[unused 24 bits]…000000102White Piece
[unused 24 bits]…000001004Crowned Piece

Using these bit flags, you know that a crowned black piece will have a value of 5 (crowned + black), a crowned white piece will have a value of 6 (crowned + white), and all empty spaces on the board will be represented by 0s. If you have a keen eye, you may have noticed that this bit-packed data structure technically allows for a piece to be both white and black at the same time (a value of 3). Keeping the piece colors mutually exclusive will have to be something you enforce with code, though you could also use different bit flag meanings to avoid this situation if you wanted.

You might have noticed that to activate multiple boolean flags within a bit masked value, you can simply add the two flags together, as in the case of Black (1) and Crowned (4) equals 5. This is a bad idea because this operation isn’t idempotent. If you add the Crown flag to a number twice, you’ve basically corrupted your state. When you activate a flag with i32.or, that’s idempotent, and you can do it over and over again without corrupting the rest of the number.

Once you decide what each bit means, you can write some functions to query, set, and remove these values from a piece. And in this case, a “piece” is literally nothing more than a 4-byte integer value:

wasmcheckers/checkers.wat

;; Determine if a piece has been crowned
(func $isCrowned (param $piece i32) (result i32)
(i32.eq
(i32.and (get_local $piece) (get_global $CROWN))
(get_global $CROWN)
)
)
;; Determine if a piece is white
(func $isWhite (param $piece i32) (result i32)
(i32.eq
(i32.and (get_local $piece) (get_global $WHITE))
(get_global $WHITE)
)
)
;; Determine if a piece is black
(func $isBlack (param $piece i32) (result i32)
(i32.eq
(i32.and (get_local $piece) (get_global $BLACK))
(get_global $BLACK)
)
)
;; Adds a crown to a given piece (no mutation)
(func $withCrown (param $piece i32) (result i32)
(i32.or (get_local $piece) (get_global $CROWN))
)
;; Removes a crown from a given piece (no mutation)
(func $withoutCrown (param $piece i32) (result i32)
(i32.and (get_local $piece) (i32.const 3))
)

This code relies on immutable global values like CROWN,CROWN, BLACK, and $WHITE that act like constants would in other languages. These are defined at the top of the module like so:

(global $WHITE i32 (i32.const 2))
(global $BLACK i32 (i32.const 1))
(global $CROWN i32 (i32.const 4))

The withoutCrown function is a bit tricky. We can’t use XOR with the crown bit (4) to force it to be zero. That will instead toggle it, setting the bit for a piece that isn’t already crowned. The intent of this function is to compare two pieces regardless of their crown status. The safe way to do this is to use AND with a mask that only returns the black and white bits and ignores all else.

For me, as someone who doesn’t think in binary and bitwise operations all day, this was difficult to visualize. Take a look at the following truth table that illustrates how this works:

ValueMeaningOperationMaskResult
0101Crowned Black&00110001 (B)
0001Uncrowned Black&00110001 (B)
0110Crowned White&00110010 (W)

withCrownworksonthesamebitmaskingprincipal,justwithadifferentoperator.Thiscodeinvokesi32.oronthebitsinthewithCrown works on the same bit masking principal, just with a different operator. This code invokes i32.or on the bits in the piece variable and the bits in the 32-bit constant 4. Referring to our handy bit masking reference chart, we know that the OR bitwise operation is used to set a bit. So, the bit in the third spot from the right (2²) will be set to 1 and the new value is returned.

It’s important to remember here that you’re not (yet) affecting stored state, you’re just playing with the bits inside numbers. At this point you’ve created some functions that perform bit masking operations on simple integers to give them contextual meaning within the checkers game.

Before we move on to writing more code, it would be nice to be able to test and experiment with the functions we’re writing. Since you’re using raw wast syntax, there’s no easy unit testing framework or code generation available. The easiest thing to do is just export all the functions we’re working on so we can invoke them from JavaScript until we’re satisfied they work as intended. First, put offsetForPosition,offsetForPosition, indexForPosition, and all of the bit masking functions into a test module called func_test.wat:

wasmcheckers/func_test.wat

(module
(memory $mem 1)
(global $WHITE i32 (i32.const 2))
(global $BLACK i32 (i32.const 1))
(global $CROWN i32 (i32.const 4))
(func $indexForPosition (param $x i32) (param $y i32) (result i32)
(i32.add
(i32.mul
(i32.const 8)
(get_local $y)
)
(get_local $x)
)
)
;; Offset = ( x + y * 8 ) * 4
(func $offsetForPosition (param $x i32) (param $y i32) (result i32)
(i32.mul
(call $indexForPosition (get_local $x) (get_local $y))
(i32.const 4)
)
)
;; Determine if a piece has been crowned
(func $isCrowned (param $piece i32) (result i32)
(i32.eq
(i32.and (get_local $piece) (get_global $CROWN))
(get_global $CROWN)
)
)
;; Determine if a piece is white
(func $isWhite (param $piece i32) (result i32)
(i32.eq
(i32.and (get_local $piece) (get_global $WHITE))
(get_global $WHITE)
)
)
;; Determine if a piece is black
(func $isBlack (param $piece i32) (result i32)
(i32.eq
(i32.and (get_local $piece) (get_global $BLACK))
(get_global $BLACK)
)
)
;; Adds a crown to a given piece (no mutation)
(func $withCrown (param $piece i32) (result i32)
(i32.or (get_local $piece) (get_global $CROWN))
)
;; Removes a crown from a given piece (no mutation)
(func $withoutCrown (param $piece i32) (result i32)
(i32.and (get_local $piece) (i32.const 3))
)
(export "offsetForPosition" (func $offsetForPosition))
(export "isCrowned" (func $isCrowned))
(export "isWhite" (func $isWhite))
(export "isBlack" (func $isBlack))
(export "withCrown" (func $withCrown))
(export "withoutCrown" (func $withoutCrown))

Compile that into func_test.wasm with wat2wasm, then create a JavaScript wrapper that will load the WebAssembly module and execute the exported functions so we can make sure they’re working as we expect:

wasmcheckers/func_test.js
fetch('./func_test.wasm').then(response =>
response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes)).then(results => {
console.log("Loaded wasm module");
instance = results.instance;
console.log("instance", instance);
var white = 2;
var black = 1;
var crowned_white = 6;
var crowned_black = 5;
console.log("Calling offset");
var offset = instance.exports.offsetForPosition(3,4);
console.log("Offset for 3,4 is ",offset);
console.debug("White is white?", instance.exports.isWhite(white));
console.debug("Black is black?", instance.exports.isBlack(black));
console.debug("Black is white?", instance.exports.isWhite(black));
console.debug("Uncrowned white",
instance.exports.isWhite(instance.exports.withoutCrown(crowned_white)));
console.debug("Uncrowned black",
instance.exports.isBlack(instance.exports.withoutCrown(crowned_black)));
console.debug("Crowned is crowned",
instance.exports.isCrowned(crowned_black));
console.debug("Crowned is crowned (b)",
instance.exports.isCrowned(crowned_white));
});

Finally, we can create a little index.html file that starts the func_test.js script:

wasmcheckers/func_test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: rgb(255, 255, 255);
}
</style>
</head>
<body>
<span id="container"></span>
<script src="./func_test.js"></script>
</body>
</html>

Because of cross-site scripting rules in the browser, it might not let you open a file from the file system without having an HTTP server (my Firefox on

Ubuntu won’t, but apparently Firefox on Arch Linux does), so spin up your favorite one or you can just use Python to launch this lightweight one in the same directory as your HTML file:

Terminal window
$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

Now open your browser to localhost:8000/func_test.html. Open up the JavaScript debug console and you should see something like the following output, veri- fying that we’re getting the values we expect:

Loaded wasm module instance WebAssembly.Instance { exports: {…} } Calling offset Offset for 3,4 is 140 White is white 1 Black is black 1 Black is not white 0 Uncrowned white 1 Uncrowned black 1 Crowned is crowned 1 Crowned is crowned (b) 1

While reassuring (our code works), this is also a boring and dry set of console output. As we progress further in the book, you’ll be able to produce real, user- facing web visualizations of state, game boards, and other module internals.

As you progress through this chapter, you can just copy and paste whatever function you like into this harness, make sure it’s exported, and test it with JavaScript. In the next section, you’ll build on what you’ve coded in checkers.wat so far to start reading and writing game state to manage the checkerboard.

Manipulating the Board

The next couple of functions you’re going to write involve storing and retrieving values from the game board grid in linear memory and performing some validation checks on parameters and data before allowing state mutation:

wasmcheckers/checkers.wat

;; Sets a piece on the board.
(func $setPiece (param $x i32) (param $y i32) (param $piece i32)
(i32.store
(call $offsetForPosition
(get_local $x)
(get_local $y)
)
(get_local $piece)
)
)
;; Gets a piece from the board. Out of range causes a trap
(func $getPiece (param $x i32) (param $y i32) (result i32)
(if (result i32)
(block (result i32)
(i32.and
(call $inRange
(i32.const 0)
(i32.const 7)
(get_local $x)
)
(call $inRange
(i32.const 0)
(i32.const 7)
(get_local $y)
)
)
(then
(i32.load
(call $offsetForPosition
(get_local $x)
(get_local $y)
)
)
)
(else
(unreachable)
)
)
)
;; Detect if values are within range (inclusive high and low)
(func $inRange (param $low i32) (param $high i32)
(param $value i32) (result i32)
(i32.and
(i32.ge_s (get_local $value) (get_local $low))
(i32.le_s (get_local $value) (get_local $high))
)
)

The setPiecefunctionhassomenewsyntax,andthisisthefirstplacewhereyourcodeusesthereturnvaluefromonefunctionasaparametertoanotherfunction.setPiece function has some new syntax, and this is the first place where your code uses the return value from one function as a parameter to another function. setPiece calls i32.store, which stores a 32-bit integer in a memory address. The memory address will be the value returned by calling offsetFor−Position,andthevaluestoredwillbetheparameteroffsetFor- Position, and the value stored will be the parameter piece. For example, to set a white piece at grid position (5,5), you could call (i32.store 200 2).

$getPiece illustrates the first use of an if block with a function call as a predicate. You need to specify the type of the value that’ll be returned from a predicate if it executes a function. The block keyword simply wraps one or more statements and indicates the return type of that block, kind of like an anonymous function. The general structure for an if/then/else block that also executes code in the predicate clause looks like this:

(if (result i32) (block (result i32) ...)
(then ...)
(else ...)
)

Finally, the $inRange function is used to prevent querying beyond the edge of the game board. Most high-level programming languages have built-in features that will prevent situations like this or will throw an out-of-bounds runtime exception. Without those luxuries, in WebAssembly you’ve got to manually ensure you never access memory beyond the bounds of a given data structure.

It’s worth pointing out, however, that even an index out-of-bounds error in WebAssembly can never reach beyond the limits of its linear memory. This keeps the chance of heap corruption pretty low.

Bounds Checking Blunders

Throughout computing history, failing to properly check bounds at the assembly level has resulted in some catastrophic bugs, malicious viruses, and some amazing video game exploits. One of my favorites is this one from the original Famicom version of The Legend of Zelda,^a which shows how reading beyond implied bounds can convert raw data into executable instructions to teleport straight to the end of the game.

^a. youtu.be/fj9u00PMkYU

The game board itself isn’t the only bit of state that needs to be maintained in a checkers game. You’ll need to keep track of who has the next move. For obvious reasons, the checkers engine needs to prevent a player from taking two turns in a row or moving pieces that don’t belong to them.

You’ve already defined two different values to indicate piece color: 1 for black and 2 for white. In a regular programming language you might simply create a global variable called currentTurn and set that to an enum like White or Black. With WebAssembly, we can create global variables that are either private to the module or can be shared with the host. Let’s take a look at the global declaration near the top of the module:

(memory $mem 1)
(global $currentTurn (mut i32) (i32.const 0))

When we declare global variables in wast (raw text WebAssembly syntax), we can specify their mutability (immutable globals can be treated like constants in other languages), and we need to specify an initial value. The $currentTurn global will be set to 1 when it is black’s turn and 2 when it is white’s turn. The following code is responsible for querying and updating the current turn state:

wasmcheckers/checkers.wat

;; Gets the current turn owner (white or black)
(func $getTurnOwner (result i32)
(get_global $currentTurn)
)
;; At the end of a turn, switch turn owner to the other player
(func $toggleTurnOwner
(if (i32.eq (call $getTurnOwner) (i32.const 1))
(then (call $setTurnOwner (i32.const 2)))
(else (call $setTurnOwner (i32.const 1)))
)
)
;; Sets the turn owner
(func $setTurnOwner (param $piece i32)
(set_global $currentTurn (get_local $piece))
)
;; Determine if it's a player's turn
(func $isPlayersTurn (param $player i32) (result i32)
(i32.gt_s
(i32.and (get_local $player) (call $getTurnOwner))
(i32.const 0)
)
)

To check whether it is a current player’s turn, we might be tempted to check if the value of playeristhesameasthevaluereturnedbyplayer is the same as the value returned by isPlayersTurn. The problem is that $player can be holding a value indicating a crowned piece, which would mess up our equality check.

To compensate for this, when the isPlayersTurnfunctionchecksiftheplayervaluepassedisthecurrentplayer,itwillperformanAND(remember,thisqueriesonlythebitsinthemask)ofthevalueandtheplayer,andifthatisgreaterthanzero,thatplayeristhecolorcurrentlystoredintheisPlayersTurn function checks if the player value passed is the current player, it will perform an AND (remember, this queries only the bits in the mask) of the value and the player, and if that is greater than zero, that player is the color currently stored in the currentTurn global. This is kind of like comparing player.color with currentturn.color in other, higher-level programming languages. Here, think of the concept of “color” as a bitmask.

From a rules standpoint, checkers is not all that complex of a game. All 12 of your pieces start out with the same movement capabilities, and the only special pieces ever on the board are those that have been crowned.

The goal of this chapter isn’t to produce a game of checkers that might be ready to plug into a WebGL site so you can ship it tomorrow. You’re building a foundation for such a thing, but the nitty-gritty details of checkers edge-case rules are beyond the scope of this chapter.

This checkers game implements some basic rules like crowning a piece and moving. It doesn’t implement jumps, multi-jumps, or detect a winner. If you would like to do that as a reader exercise, I would love to see your game on GitHub!

The first function in the following code listing, shouldCrown,determinesifapieceshouldbecrowned.Apieceiseligibleforupgradeifitresidesinitsopponent′skingsrow.TheshouldCrown, determines if a piece should be crowned. A piece is eligible for upgrade if it resides in its opponent's kings row. The crownPiece function uses a few functions you’ve already written to add a crown to a piece and then store it in the gameboard:

wasmcheckers/checkers.wat

;; Should this piece get crowned?
;; We crown black pieces in row 0, white pieces in row 7
(func $shouldCrown (param $pieceY i32) (param $piece i32) (result i32)
(i32.or
(i32.and
(i32.eq
(get_local $pieceY)
(i32.const 0)
)
(call $isBlack (get_local $piece))
)
(i32.and
(i32.eq
(get_local $pieceY)
(i32.const 7)
)
(call $isWhite (get_local $piece))
)
)
;; Converts a piece into a crowned piece and invokes
;; a host notifier
(func $crownPiece (param $x i32) (param $y i32)
(local $piece i32)
(set_local $piece (call $getPiece (get_local $x)(get_local $y)))
(call $setPiece (get_local $x) (get_local $y)
(call $withCrown (get_local $piece)))
(call $notify_piececrowned (get_local $x)(get_local $y))
(func $distance (param $x i32)(param $y i32)(result i32)
(i32.sub (get_local $x) (get_local $y))
)

The local keyword declares a temporary variable that will only be visible within its enclosing scope. In the case of this code listing, all the locals are scoped to their containing function. The set_local instruction sets the value of a local variable. Sadly, you can’t declare and set a local in the same line of code. High-level languages that allow this sort of thing are just generating the separate declaration and assignment operations on your behalf.

Another thing worth pointing out in the preceding code listing is the call to $notify_piececrowned. This function will be imported by this checkers module and implemented by the host. Whenever a piece is crowned, the module calls this to let the host react to the change. This could include modifying the sprite on display for the newly crowned piece, playing a victorious sound, or both.

The $distance function is just a simple subtraction. In the next section on movement, you’ll see how that value is used to determine if that distance is valid.

Nearly all of the (naive) fundamentals of checkers are done at this point: the only thing left is to code player movement.

Before a player can move, you need to ensure that it is a valid move. In the case of this naive implementation of checkers, a valid move is:

  • The “move distance” from current to target (single axis) is valid
  • The target space is unoccupied
  • The piece being moved belongs to the current player

Let’s take a look at the code to determine if a move is valid:

wasmcheckers/checkers.wat

;; Determine if the move is valid
(func $isValidMove (param $fromX i32) (param $fromY i32)
(param $toX i32) (param $toY i32) (result i32)
(local $player i32)
(local $target i32)
(set_local $player (call $getPiece (get_local $fromX) (get_local $fromY)))
(set_local $target (call $getPiece (get_local $toX) (get_local $toY)))
(if (result i32)
(block (result i32)
(i32.and
(call $validJumpDistance (get_local $fromY) (get_local $toY))
(i32.and
(call $isPlayersTurn (get_local $player))
;; target must be unoccupied
(i32.eq (get_local $target) (i32.const 0))
)
)
(then
(i32.const 1)
)
(else
(i32.const 0)
)
)
)
;; Ensures travel is 1 or 2 squares
(func $validJumpDistance (param $from i32) (param $to i32) (result i32)
(local $d i32)
(set_local $d
(if (result i32)
(i32.gt_s (get_local $to) (get_local $from))
(then
(call $distance (get_local $to) (get_local $from))
)
(else
(call $distance (get_local $from) (get_local $to))
)
)
(i32.le_u
(get_local $d)
(i32.const 2)
)
)
)

The code for validJumpDistancemightlookalittlestrange.SinceWebAssembly′sintegersdon′tsupporttheabs()function,we′rebasicallydecidingontheorderinwhichwesupplyargumentstothevalidJumpDistance might look a little strange. Since WebAssembly's integers don't support the abs() function, we're basically deciding on the order in which we supply arguments to the distance function based on whether or not it will result in a negative number. Also remember that we’re not building a rules-compliant version of checkers—this is just enough code to exercise some basic rules in service of learning WebAssembly.

In the following code listing, the movefunctionwilleventuallybeexported(typicallydoneattheendofthemodulecode)functionsothehostcancallit.SincethismakesitapublicAPImethod,ithastoguardagainstbaddataandinvalidmoves.move function will eventually be exported (typically done at the end of the module code) function so the host can call it. Since this makes it a public API method, it has to guard against bad data and invalid moves. move returns 1 for a successful move and 0 for a failed one:

wasmcheckers/checkers.wat

;; Exported move function to be called by the game host
(func $move (param $fromX i32) (param $fromY i32)
(param $toX i32) (param $toY i32) (result i32)
(if (result i32)
(block (result i32)
(call $isValidMove (get_local $fromX) (get_local $fromY)
(get_local $toX) (get_local $toY))
(then
(call $do_move (get_local $fromX) (get_local $fromY)
(get_local $toX) (get_local $toY))
)
(else
(i32.const 0)
)
)
)

Notice that the movefunctiondeferssomefunctionalitytothemove function defers some functionality to the do_move func- tion. This separates the conditional guard checking code from the actual state changes in $do_move. After a move toggles the current turn owner, the state change sets the piece at the destination location, and wipes out the piece at the original location:

wasmcheckers/checkers.wat

;; Internal move function, performs actual move post-validation of target.
;; Currently not handled:
;; - removing opponent piece during a jump
;; - detecting win condition
(func $do_move (param $fromX i32) (param $fromY i32)
(param $toX i32) (param $toY i32) (result i32)
(local $curpiece i32)
(set_local $curpiece (call $getPiece (get_local $fromX)(get_local $fromY)))
(call $toggleTurnOwner)
(call $setPiece (get_local $toX) (get_local $toY) (get_local $curpiece))
(call $setPiece (get_local $fromX) (get_local $fromY) (i32.const 0))
(if (call $shouldCrown (get_local $toX) (get_local $toY) (get_local $curpiece))
(then (call $crownPiece (get_local $toX) (get_local $toY)))
(call $notify_piecemoved (get_local $fromX) (get_local $fromY)
(get_local $toX) (get_local $toY))
(i32.const 1)
)

As a convenience, the domovefunctioninvokesafunctioncalleddo_move function invokes a function called notify_piece- moved that lets the host know when a piece has finished moving. This function will be declared as an import at the beginning of the module. This function is called so the host can react to player movement rather than repeatedly polling for changes to the game board state.

Finally, with all the basic functions in place, it’s time to connect this module to a host and test it.

Testing Wasm Checkers

Before you can start testing or playing checkers, you need just one more function. You’ve written functions to maintain the game board state, to move player pieces, and even to notify the host when important events occur. What’s missing is the initial set up—placing all of the players’ pieces on the board.

initBoardisasimple,brute−forcefunctionthatjustcallsinitBoard is a simple, brute-force function that just calls setPiece over and over to place the white and black pieces, finally setting the current turn to black:

;; Manually place each piece on the board to initialize the game
(func $initBoard
;; Place the white pieces at the top of the board
(call $setPiece (i32.const 1) (i32.const 0) (i32.const 2))
(call $setPiece (i32.const 3) (i32.const 0) (i32.const 2))
(call $setPiece (i32.const 5) (i32.const 0) (i32.const 2))
(call $setPiece (i32.const 7) (i32.const 0) (i32.const 2))

<<many, many more calls to $setPiece>>

(call $setTurnOwner (i32.const 1)) ;; Black goes first
)

The next step is to include all the imports at the top of the checkers.wat module:

wasmcheckers/checkers.wat

(import "events" "piecemoved"
(func $notify_piecemoved (param $fromX i32) (param $fromY i32)
(param $toX i32) (param $toY i32))
(import "events" "piececrowned"
(func $notify_piececrowned (param $pieceX i32) (param $pieceY i32)))

And declare the exports at the bottom of the module:

wasmcheckers/checkers.wat

(export "getPiece" (func $getPiece))
(export "isCrowned" (func $isCrowned))
(export "initBoard" (func $initBoard))
(export "getTurnOwner" (func $getTurnOwner))
(export "move" (func $move))
(export "memory" (memory $mem))

It is important to notice that not all of the functions are exported. The host is limited to invoking only the public (exported) API. For example. you do not export $setPiece, which could possibly let the host code cheat or allow a bug to corrupt the game board. This is a standard defensive programming practice.

With the checkers.wat file complete, you should be able to build it using wat2wasm: $ /path/to/wabt/bin/wat2wasm checkers.wat -o checkers.wasm

Next, create an index.js file to load the module and run through some sample moves:

wasmcheckers/index.js fetch(’./checkers.wasm’).then(response =>

response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes, {
events: {
piecemoved: (fX, fY, tX, tY) => {
console.log("A piece moved from (" + fX + "," + fY +
") to (" + tX + "," + tY + ")");
},
piececrowned: (x, y) => {
console.log("A piece was crowned at (" + x + "," + y + ")");
}
},
})
).then(results => {
instance = results.instance;
instance.exports.initBoard();
console.log("At start, turn owner is " +
instance.exports.getTurnOwner());
instance.exports.move(0, 5, 0, 4); // B
instance.exports.move(1, 0, 1, 1); // W
instance.exports.move(0, 4, 0, 3); // B
instance.exports.move(1, 1, 1, 0); // W
instance.exports.move(0, 3, 0, 2); // B
instance.exports.move(1, 0, 1, 1); // W
instance.exports.move(0, 2, 0, 0); // B - this will get a crown
instance.exports.move(1, 1, 1, 0); // W
// B - move the crowned piece out
let res = instance.exports.move(0, 0, 0, 2);
document.getElementById("container").innerText = res;
console.log("At end, turn owner is " + instance.exports.getTurnOwner());
})
.catch(console.error);

The moves in this test are just exercising the naive game rules. A real game wouldn’t allow movement like this, but this at least helps us verify that the code we did write works as intended. Now you can create an index.html file that will run this script:

wasmcheckers/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: rgb(255, 255, 255);
}
</style>
</head>
<body>
<span id="container"></span>
<script src="./index.js"></script>
</body>
</html>

As you did earlier in the chapter, you can host this file behind a simple Python web server:

Terminal window
$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

You should now be able to point your browser at localhost:8000, open the developer tools, and see the following in your JavaScript console:

At start, turn owner is 1 A piece moved from (0,5) to (0,4) A piece moved from (1,0) to (1,1) A piece moved from (0,4) to (0,3) A piece moved from (1,1) to (1,0) A piece moved from (0,3) to (0,2) A piece moved from (1,0) to (1,1) A piece was crowned at (0,0) A piece moved from (0,2) to (0,0) A piece moved from (1,1) to (1,0) A piece moved from (0,0) to (0,2)

The module works, so we’ve got that going for us. Take a step back and bask in the glow of knowing that you’ve written WebAssembly to handle in-memory game board state, turn management, game rule validation, and even notify the host when important events occur. Before you rush off to make millions on your new checkers game, there’s one more thing you really need to see— take a look at the file size of your compiled wasm module:

Terminal window
$ ls -l
total 48
-rw-r--r-- 1 kevin kevin 853 Oct 28 13:08 checkers.wasm
-rw-r--r-- 1 kevin kevin 9952 Oct 28 11:04 checkers.wat
-rw-r--r-- 1 kevin kevin 243 Oct 28 10:38 func_test.html
-rw-r--r-- 1 kevin kevin 1063 Oct 28 11:13 func_test.js
-rw-r--r-- 1 kevin kevin 184 Oct 28 10:57 func_test.wasm
-rw-r--r-- 1 kevin kevin 1405 Oct 28 10:57 func_test.wat
-rw-r--r-- 1 kevin kevin 238 Jul 7 15:16 index.html
-rw-r--r-- 1 kevin kevin 1072 Jul 15 10:57 index.js

Your eyes are not deceiving you—the compiled size of the checkers module is a mere 853 bytes! It might vary a bit depending on your OS and file system, but it will still be tiny. You also know, because you wrote all your own state management code, that the checkers module will never use more than a single 64KB page of memory. In fact, your module only uses a grand total of 256 bytes of linear memory. Just think about how many simultaneous, in-memory copies of a live checkers game a server could hold.

You’ll see in subsequent chapters that as you add tooling and code generation, this will dramatically affect the size of your wasm modules. Some of the tools you’ve seen so far can also be used to trim out some of the excess fat from these modules, but you’ll never be able to create modules this small unless you’re hand-coding your wat.

There was more to this chapter than just learning how to write WebAssembly “the hard way.” Even now, in the early days of the WebAssembly ecosystem, multiple layers of tooling and code generation are available that can easily hide the inner workings from you.

Because you’ve written more than just a simple module that adds two numbers together, you know what’s going on at the bottom levels of abstraction. More importantly, you can appreciate what tools and code generators will do for you. This gives you a deeper understanding of the consequences of the Rust code you’ll write and the design decisions you’ll make when building WebAssembly solutions. Further, when you get to the chapter on hosting WebAssembly with Rust, you will already have an in-depth knowledge of the components of a WebAssembly module and so the parsing, loading, and exe- cuting tasks will all make more sense.

In the next chapter, you’ll start to write at higher levels of abstraction, using Rust to target WebAssembly. As you explore that chapter, keep in mind what you’ve learned so far, as keeping a mental map between high-level code and its raw WebAssembly equivalent will help you squeeze every ounce of power, performance, and elegance from WebAssembly.

Part II Interacting with JavaScript

In this part, we’ll expand on our foundation by learning how to build WebAssembly modules with Rust and integrate them with JavaScript and the browser.