Building a Random-Pokémon-GB-like Frame Generator

2026-11-22en17 minhandwritten

While implementing vibe coding my blog I had this cool idea to give the images Pokémon-like frames, even cooler if it was a random one on every refresh (like other parts of my blog). Said and done, Claude did a good job and I was really excited that my cool idea was up and running. Here’s an example:

I know it's a bit weird, but this is one of my favorite gen-1 sprite
I know it's a bit weird, but this is one of my favorite gen-1 sprite

But of course as a pre-AI software developer umarell I wanted to look at the code and try to understand how it worked. It did not go well. That made me a bit sad and nostalgic. And looking at the frames more carefully ->they were nothing like GB Pokémon!

That sentiment did not last long, I thought about why I liked to be a software developer, and the answer is simple: because I like building stuff! By building stuff I allow my creativity to come out, and I have fun doing it. So, let’s try to improve the solution, by doing what I like in the way I like.

That ended up as a little journey of building step by step, exploring different possibilities, understanding the solutions, checking out various sources, using AI the right way, learning a lot and, most importantly, having fun.

Result

This article is not a tutorial (does it even make sense to have tutorials nowadays?) but it is similar in that it goes through the various parts, step by step, exploring each piece (and its code) in different ways. If you are interested only in the code, here’s the gist:

Gist - javekk/pokemon-frame.js

and an example of it (you can refresh the page to see the randomness)

A random Game Boy text box

Using the AI the right way

What does it mean to use AI in the right way? Well, I don’t know. What I do know is that for this experience, I wanted to have something like a course, like the ones you find on Coursera, with some hints, some sources; you write the code and then you get corrected in some way. So I did what most people do nowadays: I built a skill -> Course

It worked well, not great but enough for the goal.

PRNG

One of the requirements of this implementation was to have a Random frame, but it should not be “too random”. One of the reasons is that while building we wanted the output to be somehow consistent, to be able to understand if we were going in the right direction while making changes. Another good reason for the blog implementation was that on resizing an image, it should keep the same frame. So starting from a seed was the right choice. Let’s look at the code:

javascript
function mulberry32(seed) {
  let t = seed >>> 0;
  return () => {
    t = (t + 0x6d2b79f5) >>> 0;
    let x = Math.imul(t ^ (t >>> 15), t | 1);
    x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
  };
}

Well, for you it can be a bunch of nonsense, or something that can make a bit of sense.

As for me, having built a little chess engine myself, I already knew a bit about pseudo random number generation and bitwise operations. To be completely honest here, every time I have to deal with them, I realize how cool they are and how powerful they can be.

As for that function, it is tiny, but we really have a lot to learn from it; about unsigned shift operations, why we need Math.imul, why we have 61 or 14 or 4294967296.

To get there, we have to understand what I think is the core concept here. This is essentially a Hash function, one input X, one output Y. mulberry32 is exactly that, and it tries to do it the right way!

What’s the right way you may ask? Well that’s what I learned from this article Prospecting for Hash Functions, by Chris Wellons:

There are two key properties I’m looking for in randomly generated hash functions.

  1. High avalanche effect. When I flip one input bit, the output bits should each flip with a 50% chance.

  2. Low bias. Ideally there is no correlation between which output bits flip for a particular flipped input bit.

xor, shift, multiplication are a good way to do that. Andddd, that’s it, that’s all you need to know about mulberry32. Pretty cool!

Data structure

First of all, let’s remember we are talking about Game-Boy-Pokémon-text-box-like frames. As good software engineers, the first thing we have to set up is how we model it, how we “structure” a frame.

As always in SW, there are many ways, but let’s be principled. KISS is the right way. If we think about the Game Boy we think about pixel art, and ultimately it’s just a rectangle in which we have to draw some pixels. We probably need 1 color (like in the blog) or a limited number (GB has 4 colors), so what’s a good way to represent that?

Matrix MxN, type Integer, translated into JS:

javascript
class Grid {
  constructor(width, height) {
    this.width = width;
    this.height = height;
    this.cells = new Uint8Array(width * height);
  }
  get(x, y) {
    return this.cells[y * this.width + x];
  }
  set(x, y, v) {
    this.cells[y * this.width + x] = v;
  }
}

A matrix can easily be structured as a vector, and even if JS is not famous for number operations (even tho it’s not its fault, blame floating points), it has a lot of types and good built-in sugars that can come in handy, like Uint8Array.

As simple as it is, there are different ways to map rows and columns into a vector, the most common being row-major (one row at a time) and column-major (one column at a time):

javascript
const array = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
];

function seq_() {
  let init = 0;
  return () => array[init++];
}

function print_grid(grid) {
  for (let y = 0; y < 5; y++) {
    let row_s = "";
    for (let x = 0; x < 4; x++) {
      row_s += "[";
      row_s += grid.get(x, y);
      row_s += "]";
    }
    console.log(row_s);
  }
}

let seq = seq_();
let grid = new Grid(4, 5);

console.log("Row-major:");
for (let y = 0; y < 5; y++) {
  for (let x = 0; x < 4; x++) {
    grid.set(x, y, seq());
  }
}
print_grid(grid);

seq = seq_();
grid = new Grid(4, 5);

console.log("\nColumn-major:");
for (let x = 0; x < 4; x++) {
  for (let y = 0; y < 5; y++) {
    grid.set(x, y, seq());
  }
}
print_grid(grid);

output:

Row vs Column major
Row vs Column major

Distance Functions

We are going to have just a taste of computer graphics here, no need to go into too much detail, but if you are interested, while developing I was reading about Domain Repetition, Raytracing, Basic Shaders and the book of shaders. Really, really cool stuff.

To have a cool random generated frame, we only need one thing, symmetry.

Let’s get this grid as an example:

Empty grid
Empty grid

You can divide it into 4 parts, add random pixels to one of them:

1/4 of grid filled
1/4 of grid filled

Mirror it on the 2 axes:

It's more visually pleasant no?
It's more visually pleasant no?

And we can see that we already achieved something that is more aesthetically pleasant. We can code this concept by using a distance function: the distance from the nearest border (a simple cousin of Signed distance functions). Nothing fancy, what we need is a simple minimum function. Check this code:

javascript
class Grid {
  /*...*/
}

const print_grid = (grid, name) => {
  console.log("\n");
  if (name) {
    console.log("⬇️⬇️⬇️" + name + "⬇️⬇️⬇️");
  }
  for (let y = 0; y < grid.height; y++) {
    let row = "";
    for (let x = 0; x < grid.width; x++) {
      row += grid.get(x, y) > 0.5 ? "⬛" : "⬜";
    }
    console.log(row);
  }
};

const quadrant = new Grid(10, 8);

quadrant.set(1, 1, 1);
quadrant.set(1, 2, 1);
quadrant.set(0, 3, 1);
quadrant.set(2, 0, 1);
quadrant.set(4, 0, 1);
quadrant.set(3, 2, 1);

const W = quadrant.width;
const H = quadrant.height;

for (let y = 0; y < H; y++) {
  for (let x = 0; x < W; x++) {
    // fx and fy = distance from the nearest border
    // W = 7:  x = 0 1 2 3 4 5 6  →  fx = 0 1 2 3 2 1 0   (one center cell)
    // W = 6:  x = 0 1 2 3 4 5    →  fx = 0 1 2 2 1 0     (two center cells, same value)
    // fx(W-1-x) = min(W-1-x, x) = fx(x)
    const fx = Math.min(x, W - 1 - x);
    const fy = Math.min(y, H - 1 - y);

    quadrant.set(x, y, quadrant.get(fx, fy));
  }
}

print_grid(quadrant);

This works for any size, but it’s not quite what we want: if we have a look at Pokémon gb frames, we can notice that they are repetitions of a single pattern. We can simulate that by generating a sample grid and projecting it onto a bigger grid. Let’s update the code from before:

javascript
class Grid {
  /*...*/
}

function mulberry32(seed) {
  /*...*/
}

const print_grid = (grid, name) => {
  /*...*/
};

const sample = new Grid(4, 4);
// Pseudo random filling of the sample
const random_number_126 = mulberry32(126);
for (let row = 0; row < 4; row++) {
  for (let col = 0; col < 4; col++) {
    sample.set(col, row, random_number_126() > 0.5);
  }
}
print_grid(sample, "Sample");

const big_grid = new Grid(8, 8);
const W = big_grid.width;
const H = big_grid.height;

for (let y = 0; y < H; y++) {
  for (let x = 0; x < W; x++) {
    // fx and fy = distance from the nearest border
    // W = 7:  x = 0 1 2 3 4 5 6  →  fx = 0 1 2 3 2 1 0   (one center cell)
    // W = 6:  x = 0 1 2 3 4 5    →  fx = 0 1 2 2 1 0     (two center cells, same value)
    // fx(W-1-x) = min(W-1-x, x) = fx(x)
    const fx = Math.min(x, W - 1 - x);
    const fy = Math.min(y, H - 1 - y);

    big_grid.set(x, y, sample.get(fx, fy));
  }
}

print_grid(big_grid, "Filled");
Fill a grid with a sample
Fill a grid with a sample

Let’s not hallucinate here: the code is not complete, as we can notice in a second by changing the big_grid dimensions:

Fill a grid with a sample without modulo
Fill a grid with a sample without modulo

We need the last piece to have a real domain repetition, i.e. the modulo operator. So if you switch

javascript
big_grid.set(x, y, sample.get(fx, fy));

with

javascript
big_grid.set(x, y, sample.get(fx % sample.width, fy % sample.height));
Domain repetition
Domain repetition

You will have the magic. The last piece to have a frame is to not fill the inner squares; we can add a continue like this:

javascript
const big_grid = new Grid(14, 14);
const W = big_grid.width;
const H = big_grid.height;
const FRAME_SIZE = 3;

for (let y = 0; y < H; y++) {
  for (let x = 0; x < W; x++) {
    const fx = Math.min(x, W - 1 - x);
    const fy = Math.min(y, H - 1 - y);

    // this make the image became a frame
    if (fx >= FRAME_SIZE && fy >= FRAME_SIZE) continue;

    big_grid.set(x, y, sample.get(fx % sample.width, fy % sample.height));
  }
}

and this is the final result:

Domain repetition
Domain repetition

This is an example of domain repetition, a common technique in shaders. Try this code in shadertoy:

glsl
void mainImage(out vec4 o, in vec2 fc) {
    vec2 p = floor(fc / 6.0), s = floor(iResolution.xy / 6.0); // pixel grid
    vec2 d = min(p, s - 1.0 - p);                              // fold: distance from the edges
    float across = min(d.x, d.y), along = max(d.x, d.y);
    bool on = across < 8.0 && mod(along - across, 4.0) < 2.0;  // mod = domain repetition
    o = vec4(on ? vec3(0.06, 0.22, 0.06) : vec3(0.61, 0.74, 0.06), 1.0);
}

and you will have something similar.

Blitting

If we look at Pokémon Crystal frames more closely, we notice that basically we have 2 patterns: one for the edges and one for the corners.

To have something similar we can generate the 2 patterns (edge and corner) ourselves as grids, like we did in the example above, and repeat the pattern on the frame, flipping or rotating it depending on where we are in the frame.

There is a special technique to do exactly that, it’s called blitting, and it essentially works like a stamp. This is the basic code:

javascript
const blit = (src_grid, dst_grid, ox, oy) => {
  const w = src_grid.width;
  const h = src_grid.height;
  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++) {
      const dx = ox + x;
      const dy = oy + y;
      dst_grid.set(dx, dy, src_grid.get(x, y));
    }
};

Reusing some of the utilities from the code before we can see the result:

Basic blitting
Basic blitting

To be able to flip it on the X or Y axis, we can simply read the stamp pixels from right to left and from the bottom to the top. Let’s add some optional fields to the function:

javascript
const blit = (
  src_grid,
  dst_grid,
  ox,
  oy,
  { flip_x = false, flip_y = false },
) => {
  const w = src_grid.width;
  const h = src_grid.height;
  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++) {
      const dx = ox + x;
      const dy = oy + y;

      const sx = flip_x ? w - 1 - x : x;
      const sy = flip_y ? h - 1 - y : y;
      dst_grid.set(dx, dy, src_grid.get(sx, sy));
    }
};

let’s play with it to see the results:

In some cases we may also want to “flip” it along the diagonal, essentially making a transposition; we also want to support different heights and widths for the stamp. Let’s update the code.

javascript
const blit = (
  src_grid,
  dst_grid,
  ox,
  oy,
  { flip_x = false, flip_y = false, transpose = false },
) => {
  const w = transpose ? src_grid.height : src_grid.width;
  const h = transpose ? src_grid.width : src_grid.height;

  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++) {
      const dx = ox + x;
      const dy = oy + y;

      const sx = flip_x ? w - 1 - x : x;
      const sy = flip_y ? h - 1 - y : y;

      dst_grid.set(
        dx,
        dy,
        transpose ? src_grid.get(sy, sx) : src_grid.get(sx, sy),
      );
    }
};

Last but not least, we don’t want to encounter weird overflows, and at certain moments we may want to crop the stamp so it does not cross a certain x or y in the frame. Let’s modify the code a bit to be able to do that:

javascript
const blit = (
  src_grid,
  dst_grid,
  ox,
  oy,
  {
    flip_x = false,
    flip_y = false,
    transpose = false,
    x0 = 0,
    x1 = dst_grid.width,
    y0 = 0,
    y1 = dst_grid.height,
  },
) => {
  const w = transpose ? src_grid.height : src_grid.width;
  const h = transpose ? src_grid.width : src_grid.height;

  for (let y = 0; y < h; y++)
    for (let x = 0; x < w; x++) {
      const dx = ox + x;
      const dy = oy + y;

      if (dx < x0 || dx >= x1 || dy < y0 || dy >= y1) {
        continue;
      }

      const sx = flip_x ? w - 1 - x : x;
      const sy = flip_y ? h - 1 - y : y;

      dst_grid.set(
        dx,
        dy,
        transpose ? src_grid.get(sy, sx) : src_grid.get(sx, sy),
      );
    }
};
blit(stamp, big_grid, 3, 3, { x1: 6, y1: 7 });
blit(stamp, big_grid, 3, 3, { x1: 6, y1: 7 });

This will be our base building function.

9-Slice

What we want to do now is use the blitting function to start drawing the whole frame. We can first create the corner and the edge samples, then blit them with different procedures.

We can reuse the idea of the 9-slice scaling in which we split the image into 9 pieces: the 4 corners, the 4 edges and the center.

The center is easy, we can leave it empty. For the 4 corners, it is just a matter of blitting the sample correctly. Let’s check the code:

javascript
class Grid {
  /*...*/
}

function mulberry32(seed) {
  /*...*/
}

const print_grid = (grid, name) => {
  /*...*/
};

const get_random_grid = (seed, W = 4, H = 4) => {
  /*...*/
};

const blit = (/*...*/) => {
  /*...*/
};

const assemble = (corner, edge, frame) => {
  const W = frame.width;
  const H = frame.height;

  blit(corner, frame, 0, 0, { flip_x: false, flip_y: false });
  blit(corner, frame, W - corner.width, 0, { flip_x: true, flip_y: false });
  blit(corner, frame, W - corner.width, H - corner.height, {
    flip_x: true,
    flip_y: true,
  });
  blit(corner, frame, 0, H - corner.height, { flip_x: false, flip_y: true });

  return frame;
};

const corner = get_random_grid(1134, 3, 3);
print_grid(corner, "Corner");

const frame = new Grid(21, 17);
assemble(corner, {}, frame);
print_grid(frame, "Frame");

This is the result:

Blitting corners
Blitting corners

For edges we have a couple of options: we can blit starting from one corner to another clockwise (or counterclockwise) like Frame 4 above. Or my favorite, start from each corner and stop in the middle, so even with an odd number of pixels we can preserve a nice symmetry. Let’s update the code and in particular the assemble function:

javascript
const assemble = (corner, edge, frame) => {
  const W = frame.width;
  const H = frame.height;

  const edge_size = edge.width;
  const mid_x = W / 2;
  const mid_y = H / 2;

  for (let x = edge_size; x < mid_x; x += edge_size) {
    // Top and bottom, left half
    blit(edge, frame, x, 0, { x1: mid_x });
    blit(edge, frame, x, H - edge_size, { flip_y: true, x1: mid_x });
  }
  for (let x = W - 2 * edge_size; x + edge_size > mid_x; x -= edge_size) {
    // Right half, mirrored
    blit(edge, frame, x, 0, { flip_x: true, x0: mid_x });
    blit(edge, frame, x, H - edge_size, {
      flip_x: true,
      flip_y: true,
      x0: mid_x,
    });
  }
  for (let y = edge_size; y < mid_y; y += edge_size) {
    // Left and right, top half: the edge rotated
    blit(edge, frame, 0, y, { transpose: true, y1: mid_y });
    blit(edge, frame, W - edge_size, y, {
      transpose: true,
      flip_x: true,
      y1: mid_y,
    });
  }
  for (let y = H - 2 * edge_size; y + edge_size > mid_y; y -= edge_size) {
    // Bottom half, mirrored
    blit(edge, frame, 0, y, { transpose: true, flip_y: true, y0: mid_y });
    blit(edge, frame, W - edge_size, y, {
      transpose: true,
      flip_x: true,
      flip_y: true,
      y0: mid_y,
    });
  }

  blit(corner, frame, 0, 0, { flip_x: false, flip_y: false });
  blit(corner, frame, W - corner.width, 0, { flip_x: true, flip_y: false });
  blit(corner, frame, W - corner.width, H - corner.height, {
    flip_x: true,
    flip_y: true,
  });
  blit(corner, frame, 0, H - corner.height, { flip_x: false, flip_y: true });

  return frame;
};
Blitting frames
Blitting frames

Of course the big assumption here is to have the same dimensions for height and width in edges and corners. With some modifications the code also works for tiles that are not perfectly square, but for our use case this is good enough.

From noise to design

We have our base framework to build frames now, but we keep using the hash function to generate random tiles, which are cool in a way, but they’re not really what we want. We can reduce the amount of randomness by generating fixed shapes (for corners) or patterns (for edges) and adding a bit of randomness to them.

Constraints

Before going there we should set up some constraints to make our implementation easier and move towards the GB-like structure we seek. Some of these are inspired by the Pan Docs documentation:

javascript
const TILE = 8;
const PALETTE = ["#9bbc0f", "#8bac0f", "#306230", "#0f380f"];

and modify the print_grid function a bit to improve our debugging process:

javascript
const print_grid = (grid, name) => {
  console.log("\n");
  if (name) {
    console.log("⬇️⬇️⬇️" + name + "⬇️⬇️⬇️");
  }
  for (let y = 0; y < grid.height; y++) {
    let row = "";
    for (let x = 0; x < grid.width; x++) {
      const hex = PALETTE[grid.get(x, y)];
      const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
      row += `\x1b[48;2;${r};${g};${b}m  \x1b[0m`;
    }
    console.log(row);
  }
};

Corners

Let’s start with corners. We would like to create some basic shapes, like a circle, a square, a pokeball.

We can use basic math in order to be able to create the pattern we like. The circle is the easiest one: we loop over each pixel, calculate its distance from the center and, based on that, decide what color the pixel should be. Let’s look at the code:

javascript
const makeOrnament = (shape) => {
  const g = new Grid(TILE, TILE);
  for (let y = 0; y < TILE; y++) {
    for (let x = 0; x < TILE; x++) {
      const dx = x - 3.5;
      const dy = y - 3.5;
      const dist = Math.hypot(dx, dy);

      let color;
      if (shape === "circle") {
        if (dist < 1) {
          color = 1; // Center
        } else if (dist < 3) {
          color = 2; // Fill
        } else if (dist < 4) {
          color = 3; // Outline
        }
      }

      if (color !== undefined) {
        g.set(x, y, color);
      }
    }
  }
  return g;
};

The distance from the center in a circle is “easy” to calculate with the Euclidean distance Math.hypot(dx, dy). We can use a similar concept for the square by using the so-called Chebyshev distance, which is essentially the same concept, but its “circles” are squares. Let’s update the code:

javascript
const makeOrnament = (shape) => {
  const g = new Grid(TILE, TILE);
  for (let y = 0; y < TILE; y++) {
    for (let x = 0; x < TILE; x++) {
      const dx = x - 3.5;
      const dy = y - 3.5;
      const dist = Math.hypot(dx, dy);

      let color;
      if (shape === "circle") {
        if (dist < 1) {
          color = 1; // Center
        } else if (dist < 3) {
          color = 2; // Fill
        } else if (dist < 4) {
          color = 3; // Outline
        }
      }

      if (shape === "square") {
        if (Math.abs(dx) === 3.5 || Math.abs(dy) === 3.5) {
          color = 2; // Border
        } else if (Math.abs(dx) < 1 && Math.abs(dy) < 1) {
          color = 3; // 2×2 centre dot
        }
      }

      if (color !== undefined) {
        g.set(x, y, color);
      }
    }
  }
  return g;
};

The last shape we would like to have is the pokeball-like shape. Here we are going to reuse the same concepts as the square and the circle; the only thing to watch out for is applying the checks in the right order. Here’s the code:

javascript
const makeOrnament = (shape) => {
  const g = new Grid(TILE, TILE);
  for (let y = 0; y < TILE; y++) {
    for (let x = 0; x < TILE; x++) {
      const dx = x - 3.5;
      const dy = y - 3.5;
      const dist = Math.hypot(dx, dy);

      let color;
      if (shape === "circle") {
        if (dist < 1) {
          color = 1; // Center
        } else if (dist < 3) {
          color = 2; // Fill
        } else if (dist < 4) {
          color = 3; // Outline
        }
      }

      if (shape === "square") {
        if (Math.abs(dx) === 3.5 || Math.abs(dy) === 3.5) {
          color = 2; // Border
        }
        if (Math.abs(dx) < 1 && Math.abs(dy) < 1) {
          color = 3; // 2×2 centre dot
        }
      }

      if (shape === "pokeball") {
        if (dist >= 4) {
          color = undefined;
        } else if (dist < 1) {
          color = 0; // Button
        } else if (Math.abs(dy) < 1) {
          color = 3; // Band
        } else if (dist >= 3) {
          color = 3; // Outline
        } else {
          color = dy < 0 ? 2 : 1; // Dark top half, light bottom half
        }
      }

      if (color !== undefined) {
        g.set(x, y, color);
      }
    }
  }
  return g;
};

Here are the results:

Ornaments
Ornaments

Edges

For edges we are going to introduce an array of Profiles, which serves as a pool of possible edge types from which we pick one “profile” at a time.

The idea is more or less the same as for the corners: we always use a distance function to determine the color of the pixel, but in only one dimension.

It’s simpler to look at the code:

javascript
const PROFILES = [
  [0, 3, 3, 3, 3, 1, 1, 3],
  [0, 0, 3, 1, 2, 3, 0, 0],
  [0, 1, 3, 1, 2, 3, 0, 3],
];

const makeEdge = () => {
  const g = new Grid(TILE, TILE);
  const profile = PROFILES[Math.floor(Math.random() * 3)];
  for (let y = 0; y < TILE; y++) {
    for (let x = 0; x < TILE; x++) {
      g.set(x, y, profile[y]);
    }
  }
  return g;
};

We can run it multiple times and see the results:

Now let’s add a bit of controlled randomness to this implementation. We are going to use some simple math: periodic functions, so that the pattern repeats regularly. Their period should be related to the tile size, so that the pattern is not broken between one tile and another.

Nothing scary, let’s look at the code:

javascript
const PROFILES = [
  [0, 3, "rand", "rand", "rand", 3, 0, 3],
  [0, 0, 2, "rand", 2, 3, 0, 3],
  [0, 0, 3, 1, 2, 3, 0, 0],
];

const patternColor = (pattern, x, y) => {
  let is_it_colored = false;
  if (pattern === "dots") {
    is_it_colored = x % 2 === 0;
  }
  return is_it_colored ? 3 : 0;
};

const makeEdge = (pattern) => {
  const g = new Grid(TILE, TILE);
  const profile = PROFILES[Math.floor(Math.random() * 3)];
  for (let y = 0; y < TILE; y++) {
    for (let x = 0; x < TILE; x++) {
      g.set(
        x,
        y,
        profile[y] === "rand" ? patternColor(pattern, x, y) : profile[y],
      );
    }
  }
  return g;
};

and here are the results:

So dots are quite easy: we simply color the pixel when its x coordinate is even. The next pattern is the natural evolution, i.e. the dashes. We can use a mathematical (and very abused in computer science) trick, i.e. the modulo operator %, and color only half of the pixels in a period. To have 2 dashes in a single tile we can use a period of 4, since the tile is 8. We could also use a period of 8, and each tile would have only one dash. If we choose a period of 2 we end up with the dots. But again, looking at the code is simpler than explaining the concept:

javascript
const patternColor = (pattern, x, y) => {
  let is_it_colored = false;
  if (pattern === "dots") {
    is_it_colored = x % 2 === 0;
  }
  if (pattern === "dashes") {
    is_it_colored = x % 4 < 2;
  }
  return is_it_colored ? 3 : 0;
};

let’s look at the results:

Let’s go into something a bit more advanced: the zigzag pattern. Let’s imagine an empty band 3 pixels high where we want to draw a zigzag. We start at x=0 and draw the first pixel at y=0 (the top row). At x=1 the pixel goes to y=1, at x=2 to y=2, the bottom of the band. There we turn back: at x=3 the pixel is at y=1, and so on and so forth.

As before, reading the code is easier than explaining it:

javascript
const patternColor = (pattern, x, y) => {
  let is_it_colored = false;
  if (pattern === "dots") {
    is_it_colored = x % 2 === 0;
  }
  if (pattern === "dashes") {
    is_it_colored = x % 4 < 2;
  }
  if (pattern === "zigzag") {
    is_it_colored = y === [0, 1, 2, 1][x % 4];
  }
  return is_it_colored ? 3 : 0;
};

const makeEdge = (pattern) => {
  const g = new Grid(TILE, TILE);
  const profile = PROFILES[Math.floor(Math.random() * 3)];

  const band = profile.indexOf("rand");
  for (let y = 0; y < TILE; y++) {
    for (let x = 0; x < TILE; x++) {
      g.set(
        x,
        y,
        profile[y] === "rand" ? patternColor(pattern, x, y - band) : profile[y],
      );
    }
  }
  return g;
};

But there is a catch here: to see the pattern properly we need profiles with the rand rows next to each other, like [0, 3, "rand", "rand", "rand", 3, 0, 3]. We also have to make sure that the pattern starts exactly at the first rand row, to avoid weird behaviour between tiles; that’s why we added the band variable. (Other implementations were possible, but this is by far the simplest.)

Let’s have a look at the results:

Edge with zigzag
Edge with zigzag

Conclusions

This is quite a long article. The final code adds a few more fancy bits and tweaks which are not really important. The purpose was to learn by doing, explore new concepts and have fun. I had the chance to explore how simple it can be to do some pixel art with code. I had a taste of how Hash functions are built, how basic math can be turned into cool images, and of the amazing world of shaders, which is going to be my next step. Hopefully reading the article was also fun, that’s all I got for now. Bye.