My Attempt at Running a Gameboy Emulator in Google Sheets
Tags: javascript, webdev, opensource, html
Published: 2022-09-26 07:44:03

## Table Of Contents
<ul>
  <li><a href="#howdy-reader">Howdy Reader</a></li>
  <li><a href="#demo">Demo</a></li>
  <li><a href="#what-is-an-emulator">What is an emulator</a></li>
  <li><a href="#shallow-dive-into-the-gameboy">Shallow Dive into the Gameboy</a></li>
  <ul>
<li><a href="#the-cpu">The CPU</a></li>
<li><a href="#keeping-components-in-sync">Keeping Components in Sync</a></li>
</ul>
<li><a href="#enter-google-sheets">Enter Google Sheets</a></li>
<li><a href="#the-first-road-block">The First Road Block</a></li>
<li><a href="#creating-the-sidebar">Creating the Sidebar</a></li>
<li><a href="#integrating-the-gameboy">Integrating the Gameboy</a></li>
<li><a href="#final-thoughts">Final Thoughts</a></li>
<li><a href="#about-the-author">About the Author</a></li>
</ul>

---

[Demo](https://docs.google.com/spreadsheets/d/1W0f9jmZixQqK2EMZImZoIlqF-MXp1-Ek6mDdX2gfmWo)
[Source](https://github.com/gregorygaines/GameboySheets)

## Howdy Reader 👋🏽

You must be thinking `"only an idiot would try to run a Gameboy emulator in Google Sheets"?` And you'd be right! My favorite programming projects have always been emulators. I was on Google Sheets one day and thought this is boring, and you know what's not boring? Gameboys! It shouldn't be too hard, after all, I've already [written one in Java](https://github.com/gregorygaines/gBoy).

We are gonna go over what an emulator is, the basics of the Gameboy, and then the steps to running it in Google Sheets. Let's dive in.

## Demo 🎮

[Click here](https://docs.google.com/spreadsheets/d/1W0f9jmZixQqK2EMZImZoIlqF-MXp1-Ek6mDdX2gfmWo) for the sheet. Be sure to make a copy or else your sheet won't render. You can do this by clicking "File" then "Make a copy". After copying, you will have to wait a couple seconds for the script to activate which will reveal a new tab in the toolbar named "Gameboy Emulator". Click on the "Gameboy Emulator" tab then click "Show dialog". The script should automatically switch to the "GameboyScreen" sheet, if not switch to it manually.

![Make a copy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a04xxmacotol2lw18nc.png)

You may be greeted with an error about not being safe or needing permission. Click yes / proceed on both. And if you are not sure, here is the [source](https://github.com/gregorygaines/GameboySheets).

You can view the code by clicking "Extensions" in the toolbar and click "Apps Script".


![Apps Script](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xy0vfykvchmw303m8nwl.png)

## What is an emulator 🕹️

<img width="100%" style="width:100%" src="https://media.giphy.com/media/1a9qiEcQNAlhs4KyVN/giphy.gif">

An emulator can be summed up as hardware or software that allows a computer system (aka your laptop) to run software meant for another computer system (aka Gameboy ROMs).

> A general rule of thumb is the computer system that's emulating another computer system needs to be at-least 3-4x more powerful than the original because of the extra layer's introduced through emulation.

That's how you're able to download Gameboy / PSX ROMs and run them on phones/computers or any device that can download the appropriate emulator.

## Shallow Dive into the Gameboy 🥽

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

The Gameboy is a relatively simple system running a modified 8-bit Z80 Cpu and 64 KB of addressable memory. It also has multiple accompanying sub-components:

- LCD
- Timers
- APU
- Serial Port
- Gamepad Buttons

When a computer system starts up it runs on a finite loop called the fetch-decode-execute loop.


![Fetch Decode Execute](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1l7m9kzwghd9iyg3gfu4.png)


### The CPU

The CPU functions as the brain on a computer and orchestrates the fetch, decode, and execute cycle. It contains 8, 8-bit registers `A, B, C, D, E, F, H, and L` and can combine them to make 4, 16-bit registers `AF, BC, DE, and HL` along with the other 16-bit registers `SP` and `PC`. Let's see how the cycle looks inside the CPU.

```js
const runCycle = () => {
  // Fetch
  const opcode = memory.read8(pc++);
  // Decode
  const instruction = decode(opcode);
  // Execute
  const elapsedCycles = instruction();

  return elapsedCycles;
}
```

### Keeping Components in Sync

After executing an instruction, a certain amount of CPU cycles have elapsed and we have to keep the entire system in sync. We do this by extracting each component into a class and expose a `update` function that progresses the component based on how many cycles have passed.

```js
let currCycles = 0;

const runFrame = () => {
  while (currCycles < CYCLES_PER_FRAME) {
    const elapsedCycles = cpu.runCycle();
    lcd.update(elapsedCycles);
    apu.update(elapsedCycles);
    timers.update(elapsedCycles);
  }
}
```

## Enter Google Sheets 📊

That's all I'm going to say for the Gameboy. If you want to know more, [read here](https://gbdev.io/pandocs/). Knowing how to start, the next step was writing the code for Google Sheets. Google Sheets runs code using [Apps Script](https://developers.google.com/apps-script) which is Google's custom server-side JavaScript runtime made for their web apps.

Diving into the docs nothing seem too different from regular JavaScript so I started writing! The plan was simple. Write the emulator using Apps Script, then display the frames on the sheet.

Simple enough, so I started writing the code and performed simple operations.

```js
// Get sheet meta
const sheet = SpreadsheetApp.getActiveSheet();
const maxCols = sheet.getMaxColumns();
const maxRows = sheet.getMaxRows();

// Resize grid to gameboy dims
resizeSheetToGameboyDims(sheet, maxRows, maxCols);

// Set the size of rows and cols to a gameboy pixel
setSheetRowAndColsToSizeOfPixel(sheet, maxRows, maxCols);

// Clear sheet
clearSheet(sheet);

// Start emulator
startEmulator();
```

### The First Road Block
After a while, my code would automatically fail with no warning. That's when I noticed a major flaw in my plan.

![Custom Function Limit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3y48cndwdfzw6gz3mbc.png)

Google only allows 30 seconds of runtime for custom scripts! That means my emulator couldn't run long enough to be useful or debuggable! All was lost until I realized you can [create sidebars](https://developers.google.com/apps-script/guides/dialogs#custom_sidebars) with JavaScript and HTML.

The plan shifted from running the emulator on the server to creating a client-side sidebar that will contain the context of our emulator and send a draw command to the server to draw the current frame on the sheet.

### Creating the Sidebar

An interesting feature of Apps Scripts HTML is that it cannot import JavaScript files, everything must be a .html file. The workaround is to wrap all client-side JavaScript within an HTML file in a `<script>` tag.

HTML files can be linked using an import function inside `<?!= ?>` scriptlets which allows you to execute code within HTML. Inside, we run the client-side Apps Script function to load HTML from another file.

```html
<!-- Outputs the Gameboy file inside the current html file -->
<?!= HtmlService.createHtmlOutputFromFile('gameboy.html')
    .getContent(); ?>
```

### Integrating the Gameboy

After some writing, I realized I'm not that good at writing JavaScript so I opted to modify an existing [Gameboy core](https://github.com/juchi/gameboy.js).

Since the emulation logic is already there, all that needs to be done is modify the core's drawing function to send the frame data to the server and draw it to the sheet.

I started by defining logic to draw a 2d array of image data to the sheet.

```js
const drawGrid = (colors) => {
  try {
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = ss.getSheets()[1];
    const range = sheet.getRange("1:144");
    range.setBackgrounds(colors);
    SpreadsheetApp.flush();
  } catch (e) {
    Logger.log(e);
  }
}
```

Now the emulator on the client calls the draw function using the `google.script.run.[SERVER_FUNCTION_NAME]` [function](https://developers.google.com/apps-script/guides/html/reference/run).

```js
google.script.run.drawGrid(frame);
```

After connecting the functions we got a Gameboy emulator that draws to Google sheets!

![Gameboy Sheets](https://media.giphy.com/media/xZNXXfigx3OJWbxyxZ/giphy.gif)


## Limitations 🚫

### It's Super Slow

Turns out the Apps Script API is not that fast. The server commands are slow and drawing is slower. Maybe one of you could experiment and find a speedup solution.

### No way to queue commands

Draw commands sent to the server are drawn out of order so you keep seeing frames that were executed in the past. To mitigate, the client queues draw commands and sends the next one only when the previous command finishes.

---

## Final Thoughts 💭

This was an interesting yet disappointing journey. I wish that the Google Sheets API had higher script limits. I did enjoy revisiting the Gameboy and learning about Apps Script even though it's limited.

Even though I didn't get the exact effect I wanted, I got it to draw so I guess that counts as something. Next time, I'll drop a banger project for sure!

[Demo](https://docs.google.com/spreadsheets/d/1W0f9jmZixQqK2EMZImZoIlqF-MXp1-Ek6mDdX2gfmWo)
[Source](https://github.com/gregorygaines/GameboySheets)

## About the Author 👨🏾‍💻

I'm Gregory Gaines, a simple software engineer @Google who's trying to write good articles. If you want more content, follow me on Twitter at <a href="https://twitter.com/GregoryAGaines" target="_blank">@GregoryAGaines</a>.

Now go create something great! If you have any questions, hit me up on Twitter (<a href="https://twitter.com/GregoryAGaines" target="_blank">@GregoryAGaines</a>); we can talk about it.

Thanks for reading!