Game of Life

The questions below are due on Sunday November 08, 2026; 11:59:00 PM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.

1) Attendance

Make sure to scan a QR code from the front and then sign in. You must sign in before proceeding (so resolve any WiFi-related issues now before moving on).

No check in recorded! Lateness Multiplier: 0.5

Did you make sure to scan your QR code? If you did, the box above should be blue and say you checked in.

2) The Game of Life

For lab today we're going to implement Conway's Game of Life, often just called "The Game of Life." This isn't really a "game" in the Fortnite sense of the word, or even in the board game1 sense of the word, but rather a type of computer simulation that has really interesting implications and results, to the point where it is still actively studied even 53 years after its creation. The "game" consists of a two-dimensional field of cells that can either be occupied ("live") or not occupied ("dead"). The field of cells evolve over time with the new state of each individual cells being based only on their previous state and the previous states of their eight neighbor cells.

In the Game of Life (GOL), the rules are as follows:

  1. Any live cell with fewer than two live neighbours dies, as if by underpopulation.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

When taken all together these rules can be reduced to the following three:

  • Any live cell with two or three live neighbours survives.
  • Any dead cell with three live neighbours becomes a live cell.
  • All other live cells die in the next generation. Similarly, all other dead cells stay dead.

The state of the game board on time step n+1 is based solely on the state of the game board in step n, and the state of the game board at step n+2 is based solely on what it was at n+1, and it keeps going like that forever. Surprisingly, these simple "update" rules in conjunction with the iterative nature of the game can result in extremely2 complex patterns from very simple starting states. An example of the GOL running is shown in the GIF below:

Game of Life

2.1) Spice up your (Game of) Life

Normally the GOL is run on a very large board (100's or 1000's of pixels in each dimension). In addition, in most instances of the GOL (including the GIF above), the pixels on the edge handle the "out-of-bounds" pixels by assuming they are empty and any "beings"/patterns that move offscreen disappear. For our class, we're going to deploy the GOL on our little 8\times 32 LED display and this is actually too small to keep things interesting so we're going to have our game board "wrap" in the x and y dimensions. The result will be the video shown below which shows a "glider" marching across our display (compare this glider to the gliders being emitted downwards in the GIF above on a regular board):

3) The Assignment

The code for today is found here. The src/ folder contains two files:

  • main.c: Your entry point.
  • updateBoard.S: assembly file where the magic (Game of Life) happens.

Download the zip and extract the project folder as you've done previous weeks. Also, bring in your gpio_asm.S and 6190.h files from Lab04! At the end of the setup,

  • main.c, gpio_asm.S, and updateBoard.S, and 6190.h should be in the project's src folder.
  • Make sure your 6190.h is the lab4 version!

Let's look at the code in main.c. We start with this top-level C function that takes care of setting up the board and iterating through the game.

void app_main() {
    timerSetup();
    setupRandom();
    setupDisplay();
    eraseBuffer(screen_buffer);
    const int TIME = 100; //loop time.
    // Choose an initializer:
    initializeLoaf(screen_buffer);
    // initializeGlider(screen_buffer);
    // initializePentadecathalon(screen_buffer);
    // initializeWick(screen_buffer);
    // initializeRandom(screen_buffer);
    while(1){
        long start = millis();
        while(millis()-start < TIME); //wait for TIME milliseconds
        drawBuffer();
        updateBoard(screen_buffer, temp_buffer);

        // copy game_board back into screen_buffer
        for (int i=0; i<8;i++){
           screen_buffer[i] = temp_buffer[i];
        }
    }
}

All of the Game of Life logic will happen in the updateBoard function that you'll write in assembly in a little bit.

3.1) In the Beginning...

Our GOL data structure is represented by the 8-element uint32_t array (our screen buffer) with each bit representing a cell. This array will evolve over time (this will be our responsibility!). For example, if the game board started as shown below, it would cyclically behave as shown below (in this case the board has a lone period-2 "blinker" pattern in it.)

Game of Life

It is important to "seed" the game board so that the game starts doing stuff. An empty board will stay empty (life does not arise from nothing), but the other 2^{256}-1 possible starting game boards can have some pretty wonky behaviors. For testing, it'll be good to have some consistent ones as well as some random ones to work with. We've created five for you -- once you have the game working, feel free to do some research and create others!

3.1.1) Loaf

Look at initializeLoaf() in your main.c file. This one sets our board with a pattern called a "loaf". The "loaf" should stay stationary and not move nor die nor expand. It just sits on the board like a loaf.

Game of Life

If there was a Buzzfeed quiz for "What Game of Life Initialization are You?", I would probably be a loaf. It is what it is.

3.1.2) Glider

Next in main.c, we have initalizeGlider(). A glider is more exciting than a loaf. It is a pattern that continuously moves:

Game of Life

In motion:

3.1.3) Wick

Next, we have initializePentadecathalon() and initializeWick(). These are periodic patterns that we will leave these as surprises for after you complete your Game of Life implementation ^w^

3.1.4) Random

Next, in initializeRandom(), we initialize the screen buffer to random values. This can have some really interesting behavior, depending on the random configuration you get.

3.2) The Assembly

Today, the rest of your job is to write a full RISC_V assembly procedure called updateBoard.

  • It has two arguments:
    • uint32_t *current_board: a pointer to an 8-element array of 32 bit words representing the current game board
    • uint32_t *new_board: a pointer to an 8-element array of 32 bit words representing the game board at the next time step
  • Based on the values in current_board, use the GOL (Game of Life) rules, with our additional 8\times 32 wrapping modifier, to generate the next state of the game
  • Store the next state of the game in new_board.

The general structure of the GOL as implemented with updateBoard is shown below. The algorithm is presented in C since that is much easier to read than assembly.3

void updateBoard(uint32_t *current_board, uint32_t *new_board){

  eraseBuffer(new_board); // Clear the new board buffer.

  // For each cell in the board...
  for (int y = 0; y < 8; y++){
    for (int x = 0; x < 32; x++){
      int neighbor_tally = checkNeighbors(current_board,x,y); // Tally its living neighbors.
      int current_cell = getPixel(current_board,x,y); // Get the cell's current value.

      // If three neighbors...
      if (neighbor_tally==3){
        setPixel(new_board,x,y,1); // ...the cell should become occupied.
      }
      // If two neightbors and current cell is occupied...
      else if(current_cell && neighbor_tally==2){
        setPixel(new_board,x,y,1); //... the cell should stay occupied.
      }
      // Else, do nothing (since we emptied all cells using the eraseBuffer call)
    }
  }
}

3.3) Helper Procedures

You can use your eraseBuffer from gpio_asm.S.

3.3.1) getPixel

In updateBoard.S, we have given you a procedure named getPixel that, when handed a game board array, an x, coordinate, and a y coordinate, returns a 1 if the cell is occupied or 0 if it's not. See the implementation below:

# getPixel
# ARGUMENTS a0: screen_buffer, a1: x, a2: y
# RETURNS: 1 if cell occupied, 0 otherwise
getPixel:
    slli a2, a2, 2  # a2: 4 * y for address
    add a2, a2, a0  # a2: screen_buffer + 4*y
    lw a3, 0(a2)    # a3: screen_buffer[y]
    srl a3, a3, a1  # a3: screen_buffer[y] >>_l x
    andi a0, a3, 1  # a0: a3 & 1
    ret

3.4) Registers and Calling Convention

3.4.1) Registers

Last week, we discussed how registers allow us to easily move and manipulate data on the computer. They can all be referred to by a x nomenclature (so like registers x1 and x7). More often, however, we'll refer to these registers by their aliased names that reveal their particular purposes in life. The register groups we mostly care about in this class are as follows:

  • zero (x0): Always holds the value 0. Even if you write to it, it will still have the value 0. ALWAYS ZERO.

What value is always stored in register zero?

Ok, now onto the rest of the registers:

  • ra: Holds the return address (important when calling a procedure in Assembly since it lets you know where to return to)
  • sp: Points to the top of the stack (a region of memory we hold variables in!)
  • t0-t6: These registers can be used for whatever but MAY NOT persist after function calls
  • s0-s11: These registers can be used for whatever but MUST persist after function calls
  • a0-a1: Hold first two arguments of function call and return values (if needed)
  • a2-a7: Hold other arguments for function call (if needed)

3.4.2) Calling Convention

We must make sure that our procedures adheres to our RISC-V calling conventions. There are two main players when it comes to calling conventions: the caller and the callee.

  • Procedures that are called by another function are callees. We can treat all procedures that we write as callees (since something calls them in order for them to run).
  • Procedures that call other procedures are callers.

Procedures can be both caller and callee. It is all relative. Let's say we have a procedure F that calls procedure G. F is the caller to G and G is the callee to F. Then, if G calls H, then G is the caller to H and H is the callee to G.

caller and callee

The responsibilities of a callee are:

  1. To make sure sp has the exact same value when exiting the procedure as when it was entered it. This ensures that the stack is in the same state when leaving a function as it was when entering (kind of like the whole thing where you should leave a room as tidy as you found it).
  2. Every single s register must have the exact same value when exiting the procedure as it did when it entered the procedure. So, if a callee is going to use an s register, it must first save it onto the stack. Then, when the callee is done using that s register, it must restore it with it's original value by getting it from that place on the stack.

The responsibilities of a caller are:

  1. The a and t registers may not be conserved after a procedure call (the procedure that we call may end up using them). So, the caller cannot expect them to still hold the same values as they did before the procedure call. If you don't want to lose what is currently in them (like if you need them after the procedure call), you need to store them on the stack, and then restore them after the call. Something like:
  addi    sp, sp, -4    # make space on the stack
  sw      t1, 0(sp)     # save t1 on the stack
  call    someProcedure
  lw      t1, 0(sp)     # get t1 from the stack
  addi    sp, sp, 4     # remove that slot from the stack

Note that calling convention allows us to be confident that someProcedure kept sp the same value for us.

  1. ra is automatically updated when a function is called (jal ra, somewhere, which is equivalent to call somewhere, updates ra). So, any procedure that calls procedures must save ra onto the stack. That way, before returning, it can restore ra and return to the correct place in the program.

3.5) Visualizing Stack

In addition to showing register values, csbreak can also display the contents of the stack, which is very helpful for understanding and debugging stack operations.

You don't need to add or modify the next codeblock. The result will always show 0% and will not affect your lab grade.

Run the following code and open the debugger. In the debugger view, the Stack section shows a visualization of the stack. The address marked with (sp) indicates the current address that the stack pointer sp is pointing to.

Just in case you mess up the starter code while working on this task, we provide an additional copy here.

  addi    sp, sp, -8
  sw      a0, 0(sp)
  sw      s0, 4(sp)
  li      s0, 1
  csbreak
  lw      a0, 0(sp)
  lw      s0, 4(sp)
  addi    sp, sp, 8

Click continue to run the code which will modify the stack and answer the following questions.

Value of sp: 0x

Address where s0 is stored in the stack: 0x

Value of s0 from the stack: 0x

Which register's value was saved to the stack at the current stack pointer

4) checkNeighbors

The next task is to write the checkNeighbors procedure. It takes in three arguments:

  • a0: A pointer to the current game board
  • a1: x coordinate of a cell
  • a2: y coordinate of a cell

The procedure should return the tally of occupied cells in the eight surrounding cells.

We will break this into two tasks:

  1. Writing checkNeighbors, the main function.
  2. Writing tallyNeighbors, the procedure that tallies the occupied neighbors.

4.1) Task 1: Get Neighboring Indices and Return Result

The starter code skeleton is provided below for convenience.

# checkNeighbors
# ARGUMENTS a0: game_board, a1: x index, a2: y index
# RETURNS: total occupied cells in the eight surrounding cells of (x,y)
# (game board wraps in x and y)
checkNeighbors:
    # TODO: Determine left, right, up, and down indices for neighbors.

    call tallyNeighbors # tallyNeighbors(game_board, x, y, left, right, up, down)

    # TODO: Return result of tallyNeighbors (where is this result located?)

    ret

Let's get to implementing this. Write checkNeighbors in the checker below.

  1. Calculate the left, right, up, and down indices for the neighbors of the current cell at coordinates (x, y). These are the four indices needed for tallyNeighbors to create all 8 neighbors to the current cell. The left/right indices will be x coordinates, and the up/down indices will be y coordinates. Our game board will wrap around in both the x and y directions. For example, the "down" neighbor to a pixel in the bottom row would be in the top row. Remember that the origin (0,0) of our LED display is at the top right.
  2. Pass those indices, as well as other arguments to tallyNeighbors(game_board, x, y, left, right, up, down). Take note of the order of the indices. For now, you can assume that tallyNeighbors has been implemented.
  3. Follow RISC-V calling convention when needed.

Like always with assembly programs, we strongly recommend that you comment your code well.

Once that's working, paste your implementation of checkNeighbors into your updateBoard.S file.

4.2) Task 2: Tally Neighbors

Tally neighbors goes through all 8 neighbors, tallying the neighbors that are occupied. To determine if a neighbor is occupied, it uses the procedure getPixel, which has been given to you.

Remember that getPixel takes 3 arguments:

  • a0 screen_buffer (your game board)
  • a1 x coordinate
  • a2 y coordinate

We have given you an implementation of tallyNeighbors that is almost correct. Specifically, the logic is correct, but it does not follow RISC-V calling convention. Fixing calling convention (and changing nothing else) will make the procedure work as expected.

So, your task is to add instructions to tallyNeighbors so that it follows RISC-V calling convention. Specifically, you may only add instructions that:

  1. Increment/decrement the stack pointer
  2. Put elements on the stack
  3. Read elements from the stack.

Do this in the checker below.

Just in case you mess up the starter code while working on this task, we provide an additional copy here.

tallyNeighbors:
    # TODO: This procedure is functionally correct, but doesn't follow
    # RISC-V calling convention.
    # Make this procedure follow calling convention. You may only add
    # instructions that:
    # 1. Increment/decrement the stack pointer
    # 2. Put elements on the stack
    # 3. Take elements off the stack

    mv s0, a0 # s0: game_board
    mv s1, a1 # a1: x
    mv s2, a2 # a2: y
    li s3, 0  # s3: tally

    mv a1, a4
    mv a2, a5
    call getPixel # getPixel(game_board, x-1, y-1)
    add s3, s3, a0

    mv a0, s0
    mv a1, a4
    mv a2, s2
    call getPixel # getPixel(game_board, x-1, y)
    add s3, s3, a0

    mv a0, s0
    mv a1, a4
    mv a2, a6
    call getPixel # getPixel(game_board, x-1, y+1)
    add s3, s3, a0

    mv a0, s0
    mv a1, s1
    mv a2, a5
    call getPixel # getPixel(game_board, x, y-1)
    add s3, s3, a0

    mv a0, s0
    mv a1, s1
    mv a2, a6
    call getPixel # getPixel(game_board, x, y+1)
    add s3, s3, a0

    mv a0, s0
    mv a1, a3
    mv a2, a5
    call getPixel # getPixel(game_board, x+1, y-1)
    add s3, s3, a0

    mv a0, s0
    mv a1, a3
    mv a2, s2
    call getPixel # getPixel(game_board, x+1, y)
    add s3, s3, a0

    mv a0, s0
    mv a1, a3
    mv a2, a6
    call getPixel # getPixel(game_board, x+1, y+1)
    add s3, s3, a0

    mv a0, s3

    ret

Once that's passing all test cases, paste it into your updateBoard.S file.

Checkoff 1:
Be prepared to explain (1) your implementations of checkNeighbors and (2) the changes you made to tallyNeighbors to a staff member. Make sure that you store and load from the stack as necessary.

5) The Actual Game of Life Logic

The only remaining thing to implement now is the logic inside updateBoard that takes care of determining whether or not a given cell will "live" in the next cycle.

We will iterate through every pixel, and determine if it should be alive (1) or dead (0) based on the following rules:

  • Any live cell with two or three live neighbours survives.
  • Any dead cell with three live neighbours becomes a live cell.
  • All other live cells die in the next generation. Similarly, all other dead cells stay dead.

The appropriate C for this is as follows:

void updateBoard(uint32_t *current_board, uint32_t *new_board){

  eraseBuffer(new_board); // Clear the new board buffer.

  // For each cell in the board...
  for (int y = 0; y < 8; y++){
    for (int x = 0; x < 32; x++){
      int neighbor_tally = checkNeighbors(current_board,x,y); // Tally its living neighbors.
      int current_cell = getPixel(current_board,x,y); // Get the cell's current value.

      // If three neighbors...
      if (neighbor_tally==3){
        setPixel(new_board,x,y,1); // ...the cell should become occupied.
      }
      // If two neightbors and current cell is occupied...
      else if(current_cell && neighbor_tally==2){
        setPixel(new_board,x,y,1); //... the cell should stay occupied.
      }
      // Else, do nothing (since we emptied all cells using the eraseBuffer call)
    }
  }
}

Using the C code above, implement updateBoard in the checker below. Make sure to follow calling convention! Remember that you have eraseBuffer implemented for you already in gpio_asm.S.


This might seem daunting. Let's break it into steps.

  1. Clear the board buffer.
  2. Implement the nested for loops to mimic this C code:
for (int y = 0; y < 8; y++){
  for (int x = 0; x < 32; x++){
    // game of life logic
  }
}
  1. Once the loops seem good, fill in the actual Game of Life logic in place of the comment // game of life logic:
int neighbor_tally = checkNeighbors(current_board,x,y); // Tally its living neighbors.
int current_cell = getPixel(current_board,x,y); // Get the cell's current value.

// If three neighbors...
if (neighbor_tally==3){
  setPixel(new_board,x,y,1); // ...the cell should become occupied.
}
// If two neightbors and current cell is occupied...
else if(current_cell && neighbor_tally==2){
  setPixel(new_board,x,y,1); //... the cell should stay occupied.
}
// Else, do nothing (since we emptied all cells using the eraseBuffer call)

Just in case you mess up the starter code while working on this task, we provide an additional copy here.

# updateBoard
# ARGUMENTS a0: screen buffer (current board),
# a1: temporary output buffer (for new board)
# RETURNS: Nothing
updateBoard:

    # TO-DO: Translate the C implementation of updateBoard to assembly.
    # Make sure to follow RISC-V calling convention!

    ret

When it is finally working, copy your implementation into updateBoard.S. Now you can try the game out!

First, try the Loaf, and make sure it stays put like a loaf does. Then, you can initialize the game board with a glider and make sure it runs like shown in the video at the top!

Feel free to try some other starting sequences (the random one is fun. You can also ask the staff for some other ones or Google some to try yourself if you're really feeling this whole Game of Life thing.)

Checkoff 2:
Show your working GOL to a staff member. Make sure that you store and load from the stack as necessary.

6) Code Submission

Please submit your updatedBoard.S file in a zip file named None_lab5.zip before asking for a checkoff.

Here's a command that you can run in your terminal:

zip None_lab5.zip src/updateBoard.S

or for Windows Powershell users,

Compress-Archive -Path src/updateBoard.S -DestinationPath None_lab5.zip

Submit updateBoard.S as a zip file: Name the file None_lab5.zip
 No file selected

Everything below this point on the page is optional. Make sure you've uploaded your lab 5 code and gotten the checkoff before further modifying the program.


7) [OPTIONAL] Clean It Up

The final portion of the lab is optional. You do not need to complete it.

Let's remember the overall code structure in your main.c file:

#include <stdio.h>
#include "6190.h"
#include <stdlib.h>

uint32_t temp_buffer[8]; //temporarily holds new board

void initializeLoaf(uint32_t* gb){
  gb[0] = 0;
  gb[1] = 0;
  gb[2] = 0x3 << 15;
  gb[3] = 0x9 << 14;
  gb[4] = 0x5 << 14;
  gb[5] = 0x1 << 15;
  gb[6] = 0;
  gb[7] = 0;
}

// ...

void updateBoard(uint32_t *current_board, uint32_t *new_board);

void app_main() {
    timerSetup();
    setupRandom();
    setupDisplay();
    eraseBuffer(screen_buffer);
    const int TIME = 100; //loop time.
    // Choose an initializer:
    initializeLoaf(screen_buffer);
    // initializeGlider(screen_buffer);
    // initializePentadecathalon(screen_buffer);
    // initializeWick(screen_buffer);
    // initializeRandom(screen_buffer);
    while(1){
        long start = millis();
        while(millis()-start < TIME);//wait for TIME milliseconds
        drawBuffer();
        updateBoard(screen_buffer,temp_buffer);

        // copy game_board back into screen_buffer
        for (int i=0; i<8;i++){
           screen_buffer[i] = temp_buffer[i];
        }
    }
}

One annoying thing about this code was the requirement to have that temp_buffer variable. All it did was temporarily hold the new state of the game board before copying it over into screen_buffer immediately afterwards. This is unnecessary and makes the code less modular/portable.

Your first task: go into your main.c, comment out the current declaration of updateBoard and paste in this new one:

void updateBoard(uint32_t *current_board);

No more new_board. Life just got a bit better.

So now, instead of putting the new game state into new_board, updateBoard will just put the new game state back into current_board. So now our overall main.c code can look like this:

Now app_main() can look like this:

void app_main() {
    timerSetup();
    setupDisplay();
    eraseBuffer(screen_buffer);
    const int TIME = 100; //loop time.
    // Choose an initializer:
    initializeLoaf(screen_buffer);
    // initializeGlider(screen_buffer);
    // initializePentadecathalon(screen_buffer);
    // initializeWick(screen_buffer);
    // initializeRandom(screen_buffer);
    while(1){
        long start = millis();
        while(millis()-start < TIME);//wait for TIME milliseconds
        drawBuffer();
        updateBoard(screen_buffer);
    }
}

So much cleaner. Once you've come down from cloud 9 delete your old app_main() and paste this one in.

7.1) Ok... but where will our new board go?

Ok, so we're over this whole temp_buffer thing, but we do need a place to write our new board while we're studying the old board. If we start writing to screen_buffer before we're done reading it, it would cause some issues.

What we'll do now is inside of updateBoard:

  1. create a local buffer that we'll work with
  2. then, when we're done, we'll copy it over to our screen_buffer.

In C, the code would look something like this.

void updateBoard(uint32_t *current_board) {
  // NEW: No more uint32_t *new_board argument!!

  uint32_t new_board[8]; // NEW: Make our new_board buffer.

  eraseBuffer(new_board); // Clear the new board buffer.

  // For each cell in the board...
  for (int y = 0; y < 8; y++){
    for (int x = 0; x < 32; x++){
      int neighbor_tally = checkNeighbors(current_board,x,y); // Tally its living neighbors.
      int current_cell = getPixel(current_board,x,y); // Get the cell's current value.

      // If three neighbors...
      if (neighbor_tally==3){
        setPixel(new_board,x,y,1); // ...the cell should become occupied.
      }
      // If two neightbors and current cell is occupied...
      else if(current_cell && neighbor_tally==2){
        setPixel(new_board,x,y,1); //... the cell should stay occupied.
      }
      // Else, do nothing (since we emptied all cells using the eraseBuffer call)
    }
  }

  // NEW: Copy over the buffer.
  for (int y = 0; y < 8; y++) {
    current_board[y] = new_board[y];
  }

}

Using Assembly, where do we create the local buffer? Let's do it on the stack!

Your task(s) here:

  • Allocate eight words of memory on the stack (enough for our 8 integers). One tricky thing here: by how much should you change the stack pointer in order to allocate enough stack space for one integer? Then how do you extend that to make enough space for 8 integers?
  • Now just treat those 8 words exactly as you would have treated the temp_buffer before. Just instead of having an argument value pointing to some temp_buffer, you now want a pointer to a buffer (that you made yourself!) on the stack. Do remember that eraseBuffer takes in an argument, which is a pointer to the buffer that should be cleared. You should have this pointer readily available!
  • When done, make sure to transfer the contents of your homemade temporary stack buffer over to the original array.
  • Restore the stack pointer so that those 8 integers are no longer allocated.

Copy over your updateBoard implementation from above into this code checker box, then modify your implementation as described above.

Once it's passing, paste updateBoard into your updateBoard.S. It should be business as usual for your Game of Life. Make sure it works on both the Loaf and the Glider (and any other initial configurations you'd like to use).


 
Footnotes

1that's Life (click to return to text)

2The GOL is capable of being Turing Complete, meaning with proper setup and initial patterns, it can perform any algorithmic computation needed. (click to return to text)

3Look how far you've come. You're reading C to understand an even lower-level language. Imagine that. (click to return to text)