lab 9a – the game of life

33
BYU CS 224 The Game of Life 1 Lab 8a – The Game of Life "Write a C program to display successive generations of the Game of Life using a 80 x 80 grid of square cells. Each new generation consists of births (an empty cell with exactly 3 neighbors), survivals (a filled cell with either 2 or 3 neighbors), and deaths by starvation (a filled cell with 0 or 1 neighbors) or over population (4 or more neighbors). Setup the initial generation or seed with Run Length Encoded (RLE) patterns of live and dead cells. Use the switches to restart/select new seed patterns. Generate and display at least five successive generations in one second."

Upload: baby

Post on 24-Feb-2016

43 views

Category:

Documents


0 download

DESCRIPTION

Lab 9a – The Game of Life. "Write a C program to display successive generations of the Game of Life using a 80 x 80 grid of square cells. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lab  9a – The Game of Life

The Game of Life 1BYU CS 224

Lab 8a – The Game of Life

"Write a C program to display successive generations of the Game of Life using a 80 x 80 grid of square cells.Each new generation consists of births (an empty cell with exactly 3 neighbors), survivals (a filled cell with either 2 or 3 neighbors), and deaths by starvation (a filled cell with 0 or 1 neighbors) or over population (4 or more neighbors).Setup the initial generation or seed with Run Length Encoded (RLE) patterns of live and dead cells. Use the switches to restart/select new seed patterns.Generate and display at least five successive generations in one second."

Page 2: Lab  9a – The Game of Life

The Game of Life 2BYU CS 224

The Game of Life By completing the Life Lab, a student will

have: Experienced dealing with limited system resources

(time and memory). Parsed a RLE string for numbers and tokens. Written time critical algorithms. Examined compiler generated code and optimized the

code for speed. Used C bit-arrays and pointers. Implemented C pre-processor macros. Learned techniques of computer simulations.

Page 3: Lab  9a – The Game of Life

The Game of Life 3BYU CS 224

Questions…

1. What is the RAM size of the MSP430F2274?

2. How many Life cells in an 80 x 80 array?

3. What is the smallest data type required to store a Life cell?

4. Why are two arrays needed to create successive generations of Life?

1024 bytes

80 80 = 6400 cells

Alive or dead = 2 (Boolean, bit)

The next generation is a function of only the current generation.

Page 4: Lab  9a – The Game of Life

The Game of Life 4BYU CS 224

Game of Life Rules

A live cell stays alive (survives) if it has 2 or 3 live neighbors, otherwise it dies.

A dead cell comes to life (birth) if it has exactly 3 live neighbors, otherwise it stays dead.

Page 5: Lab  9a – The Game of Life

The Game of Life 5BYU CS 224

The Game of Life Rules

The Game of Life is theoretically played on an infinite Cartesian grid of square cells; each cell is either "alive" or "dead". The state of each cell for successive generations of Life is determined by how the cell interacts with its eight neighboring cells using the following rules (referred to as B3/S23):

A live cell stays alive (survives) if it has 2 or 3 live neighbors, otherwise it dies. A dead cell comes to life (birth) if it has exactly 3 live neighbors, otherwise it stays dead.

Computer RAM memory and LCD display area are limited on our development boards. Therefore, restrict your Life simulation to an 80 x 80 grid of binary square cells with the outer cells always being dead.

Page 6: Lab  9a – The Game of Life

The Game of Life 6

C Bit Manipulation C language is very efficient in manipulating bits or other

pieces of data shorter than a byte..

BYU CS 224

Operator Description& Binary AND Operator copies a bit to the result if it exists in both operands.

| Binary OR Operator copies a bit if it exists in either operand.

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

life[row][col/8] |= (0x80 >> (col%8));life[row][col/8] &= ~(0x80 >> (col%8));

Page 7: Lab  9a – The Game of Life

BYU CS 224 The Game of Life 7

RBX430-1 LCD160 x 160 x 5pixels display

row

(0-

79)

col (0-79)

uint8 life[80][10];

life[row][col/8] & (0x80 >> (col%8))

lcd_point(col*2, row*2, 7);

Page 8: Lab  9a – The Game of Life

The Game of Life 8

C Pre-processor C Pre-processor macros

Simplify coding Make program more readable Helps avoid errors from repetition.

BYU CS 224

#define MASK(col) (0x80 >> ((col)%8))#define CELL_BIRTH(a2d,row,col) a2d[row][(col)/8] |= MASK(col)#define CELL_DEATH(a2d,row,col) a2d[row][(col)/8] &= ~ MASK(col)#define CELL_TOGGLE(a2d,row,col) a2d[row][(col)/8] ^= MASK(col)#define CELL_VALUE(a1d,col) ((a1d[(col)/8] & MASK(col)) ? 1 : 0)

CELL_BIRTH(life,row,col);CELL_DEATH(life,row,col);CELL_TOGGLE(life,row,col);if (CELL_VALUE(temp,col) == 0) { ... };

Page 9: Lab  9a – The Game of Life

The Game of Life 9

“Sliding” Window into life

BYU CS 224

life[79][0-9] …life[78][0-9] …life[77][0-9] …life[76][0-9] …life[75][0-9] …

… … …

pr[0-9] …cr[0-9] …nr[0-9] …

1. Init pr, cr, nr from life array.

life[79][0-9] …life[78][0-9] D …life[77][0-9] …life[76][0-9] …life[75][0-9] …

… … …

pr[0-9] …cr[0-9] …nr[0-9] …

2. Use pr, cr, nr to update current row in life array.

life[79][0-9] …life[78][0-9] …life[77][0-9] …life[76][0-9] …life[75][0-9] …

… … …

pr[0-9] …cr[0-9] …nr[0-9] …

3. Copy cr to pr, nr to cr, and current row+1 to nr from life array.

1 neighborCell dies

Page 10: Lab  9a – The Game of Life

The Game of Life 10

“Sliding” Window into life

BYU CS 224

life[79][0-9] …life[78][0-9] …life[77][0-9] B S B …life[76][0-9] …life[75][0-9] …

… … …

pr[0-9] …cr[0-9] …nr[0-9] …

4. Use pr, cr, nr to update current row in life array.

life[79][0-9] …life[78][0-9] …life[77][0-9] …life[76][0-9] …life[75][0-9] …

… … …

pr[0-9] …cr[0-9] …nr[0-9] …

5. Copy cr to pr, nr to cr, and current row+1 to nr from life array.

life[79][0-9] …life[78][0-9] …life[77][0-9] …life[76][0-9] D …life[75][0-9] …

… … …

pr[0-9] …cr[0-9] …nr[0-9] …

6. Use pr, cr, nr to update current row in life array.

3 neighborsCell birth

2 neighborsCell survives

1 neighborCell death

3 neighborsCell birth

Page 11: Lab  9a – The Game of Life

The Game of Life 11BYU CS 224

Life Patterns

Gosper Glider Gun

Page 12: Lab  9a – The Game of Life

The Game of Life 12BYU CS 224

Initial Game Seed

The initial Life generation or game seed is created from a set of Run Length Encoded patterns that are loaded by your program into the Life grid at the beginning of a new game. Thereafter, each successive generation is a new grid created by applying the above rules simultaneously to every cell in the previous generation (ie., births and deaths occur simultaneously).

Write a C function to parse an ASCII RLE pattern using the following function prototype:

void draw_rle_pattern(int row, int col, const uint8* pattern);

where: row = lower Life grid row (0-79) of the pattern col = left Life grid column (0-79) of the pattern pattern = byte pointer (const uint8*) to the RLE pattern

Page 13: Lab  9a – The Game of Life

5. Proceed with parsing of line.

BYU CS 224 The Game of Life 13

String Parsing1. What is the value of X?

char str[] = "Point X = 100";

Parsing

4. Convert to decimal:while (isdigit(*ptr)) number = number * 10 + (*ptr++ - '0');

Return result in number

Walk the array until token or NULL

terminator.(Token must be unique)

2. Find token: char* ptr = str;int number = 0;while (*ptr && (*ptr++ != 'X'));

isdigit returns 0 or 1

3. Find beginning of number:while (*ptr && !isdigit(*ptr)) ++ptr;

Page 14: Lab  9a – The Game of Life

The Game of Life 14BYU CS 224

Game Seed Selection

Use the four switches on the RBX430-1 development board to load/restart a new pre-set Life game seed. Write a C function to load a set of RLE patterns using a switch value to select either a LIFE, BIRD, OBJECTS, or set of patterns of your choice.

enum SEED { LIFE=0x01, BIRD=0x02, OBJECTS=0x04, YOURS=0x08 };

void init_life(enum SEED seed);

if (seed = (P1IN & 0x0f) ^ 0x0f) init_life(seed);

(Use the LIFE seed for the Millennial club.)

Page 15: Lab  9a – The Game of Life

The Game of Life 15BYU CS 224

Optimization

Each successive generation of Life should be created and displayed in one-fifth of a second or less. To reach this goal, you will need to choose an optional data structure for the Life grids as well as use appropriate algorithms and data derivations to efficiently generate successive generations.

Call the function display_results after every generation. The simulation will stop and display the average generations per second immediately after 1000 generations or 100 seconds (which ever occurs first).

Your goal should be to make the top 10 list of the Millennial Club.

Page 16: Lab  9a – The Game of Life

The Game of Life 16BYU CS 224

Life Requirements1 point Your source contains header comments with your name and a

declaration that the completed assignment is your own work. The red LED blinks for every new generation of Life. An unaltered display_results function is called for each generation to display the current generation, time in seconds, and the current number of generations per second on the LCD.

5 points Each generation of Life is correctly displayed (B3/S23) using an 80 x 80 grid (2x2 LCD pixels) with the outer cells always being dead. A 1 pixel border outlines the Life grid on the LCD.

2 points Encrypted Life patterns are correctly loaded from program memory into an 80 x 80 Life grid using the Life Run Length Encoded (RLE) Life format.

1 point Pressing a switch at any time loads a new generation seed from a set of pre-defined RLE patterns and restarts a new Life game. (Switch #4 loads a set of RLE patterns of your choice.) 1 point

1 point Each successive generation takes no longer than 1/5 of a second to create and display.

Page 17: Lab  9a – The Game of Life

The Game of Life 17BYU CS 224

Life Requirements+1 point Passed off with a TA at least one day early. (No timestamps please!) +1 point Your Life simulation runs faster than six generations per second. (+2

points if faster than 9 generations and +3 points if faster than 12 generations per second.)

+2 points Your Life grid is a toroid array where the left and right edges of the Life grid are "stitched" together as well as the top and bottom edges. The result is that active areas of Life generations move across a grid edge reappear at the opposite edge.

+1 point Use switch #4 to toggle your simulation between regular rules (B3/S23) and a HighLife rules variation (B36/S23) where a cell is born if it has 3 or 6 neighbors and survives if it has 2 or 3 neighbors. Add a RLE replicator pattern to your LIFE seed and observe what happens.

x = 4, y = 4, rule = B36/S23\nb3o$o3b$o3b$o!

-1 point For each school day late. (Timestamps may be used to verify completion time.)

Page 18: Lab  9a – The Game of Life

The Game of Life 18BYU CS 224

Millennial Club RulesRules will be used in determining the top 10 submissions:

1. Your Life program is written in C (no assembly please!)2. Set both your CCS project Optimization level and Control speed

vs. size trade-offs to 1. (Project->Properties->Build->MSP430 Compiler->Optimization)

3. Use the “LIFE" set of patterns as the Life seed to determine placement in the top 10 rankings.

4. Call init_life function at the beginning of the game.5. The function display_results is called for every generation. The

simulation will stop and display the average generations per second immediately after reaching 1000 generations (or seconds exceeds 100).

6. Use any C library function (without modification) in your implementation.

7. Submit your source to a TA for verification. If your speed is faster than any in the following list, you will be added!

Page 19: Lab  9a – The Game of Life

The Game of Life 19BYU CS 224

Millennial Club

Page 20: Lab  9a – The Game of Life

The Game of Life 20

Speed!!!! Increase processor speed to maximum (16MHz). Choose an efficient/fast method of storing the Life grids. Choices

could include: Use FRAM to store two life arrays. (Slowest approach) Use LCD RAM for current, FRAM for next. (A little faster.) Use RAM for current, FRAM for next. (Faster.) Using system RAM as a bit array and a smaller RAM window to

update next generation in system RAM. (Fastest solution!) Avoid copying data as much as possible. Remove redundant operations from loops. Use table lookups where possible instead of repeated calculations

such as when creating bit masks. Use local variables to remove repeated calculations.

BYU CS 224

Page 21: Lab  9a – The Game of Life

The Game of Life 21

How to Proceed

1. Do a thorough design – use systematic decomposition.2. Verify demo Life works correctly.3. Add a simple pattern (ie. Blinker) to your life grid.4. Add B3/S23 logic and test.5. Program RLE loader and test.6. Optimize and use regression tests.7. Test, test, test.

BYU CS 224

Page 22: Lab  9a – The Game of Life

The Game of Life 22

Links…

Game of Life http://www.youtube.com/watch?v=pWNq9iMxYZo

Life in Life http://www.youtube.com/watch?v=xP5-iIeKXE8

Epic Conway’s Game of Life http://www.youtube.com/watch?v=C2vgICfQawE

60 Second Club http://students.cs.byu.edu/~cs124ta/labs/L09a-life/life_60_sec_club.html

BYU CS 224

“Life is governed by 4 simple rules!”

Page 23: Lab  9a – The Game of Life

The Game of Life 23BYU CS 224

Page 24: Lab  9a – The Game of Life

The Game of Life 24BYU CS 224

life.c// includes -----------------------------------------------------------#include "msp430.h"#include <stdlib.h>#include "RBX430-1.h"#include "RBX430_lcd.h"#include "life.h"#include "lifelib.h"

// global variables ---------------------------------------------------extern volatile uint16 switches; // debounced switch valuesextern const uint16 life_image[]; // life image

uint8 life[NUM_ROWS][NUM_COLS/8]; // 80 x 80 life griduint8 life_pr[NUM_COLS/8]; // previous rowuint8 life_cr[NUM_COLS/8]; // current rowuint8 life_nr[NUM_COLS/8]; // next row

// draw RLE pattern --------------------------------------------------void draw_rle_pattern(int row, int col, const uint8* object){ life[75][4] = 0x07; // ** delete ** lcd_point(37 << 1, 75 << 1, 7); // ** delete ** lcd_point(38 << 1, 75 << 1, 7); // ** delete ** lcd_point(39 << 1, 75 << 1, 7); // ** delete ** return;} // end draw_rle_pattern

#includes needed for Life

lab

Bit Life grid arrayPrevious, current,

and next row

Insert Blinker

Page 25: Lab  9a – The Game of Life

The Game of Life 25BYU CS 224

life.c// main ----------------------------------------------------------------void main(void){ RBX430_init(CLOCK); // init board ERROR2(lcd_init()); // init LCD //lcd_volume(376); // ***increase LCD brightness*** watchdog_init(); // init watchdog port1_init(); // init P1.0-3 switches __bis_SR_register(GIE); // enable interrupts

while (1) // new pattern seed { uint16 row, col;

// >>>>>>>> DELETE vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv lcd_clear(); // clear LCD memset(life, 0, sizeof(life)); // clear life array lcd_backlight(ON); // turn on LCD backlight lcd_rectangle(0, 0, NUM_COLS*2, NUM_ROWS*2, 1); lcd_wordImage(life_image, 17, 50, 1); lcd_cursor(10, 20); printf("\b\tPress Any Key"); switches = 0; // clear switches flag while (!switches); // wait for any switch // >>>>>>>> DELETE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

// setup beginning life generation init_life(BIRD); // load a new life seed into LCD

Initialize RBX430 and

LCD

Splash screenWait for switch

Setup switches andWatchdog as timer

Page 26: Lab  9a – The Game of Life

The Game of Life 26BYU CS 224

life.c while (1) // next generation { // for each life row (78 down to 1) for (row = NUM_ROWS-2; row; --row) { // for each life column (78 down to 1) for (col = NUM_COLS-2; col; --col) { if (neighbors == BIRTH) { cell_birth(row, col); } else { cell_death(row, col); } } } lcd_wordImage(life_image, (HD_X_MAX - 126) / 2, 50, neighbors = (neighbors == BIRTH) ? DEATH : BIRTH);

// display life generation and generations/second on LCD if (display_results(++generation)) break; } }} // end main()

For each column

For each row

Real-time Stats

Page 27: Lab  9a – The Game of Life

The Game of Life 27BYU CS 224

life.h#define NUM_ROWS 80#define NUM_COLS 80

#define cell_value(life_row,col) (life_row[(col) >> 3] & (0x01 << ((col) & 0x07)) ? 1 : 0)#define cell_birth(row,col) { life[(row)][(col) >> 3] |= (0x01 << ((col) & 0x07)); \ lcd_point((col) << 1, (row) << 1, 7); }#define cell_death(row,col) { life[(row)][(col) >> 3] &= ~(0x01 << ((col) & 0x07)); \ lcd_point((col) << 1, (row) << 1, 6); }

enum SEED { LIFE=0x01, BIRD=0x02, OBJECTS=0x04, YOURS=0x08, RANDOM };enum { DEATH = 6, BIRTH };

void draw_rle_pattern(int row, int col, const uint8* object);void init_life(enum SEED seed);

//*******************************************************************************//*******************************************************************************// life rle patterns

// still lifesextern const uint8 block[];extern const uint8 beehive[];extern const uint8 loaf[];extern const uint8 boat[];

// oscillatorsextern const uint8 blinker[];extern const uint8 toad[];extern const uint8 beacon[];extern const uint8 by_flop[];extern const uint8 hexapole[];extern const uint8 pulsar[];...

Life value, birth and death macros

Seed enums

Life Patterns

Page 28: Lab  9a – The Game of Life

The Game of Life 28BYU CS 224

lifelib.c//*************************************************************************// includes#include "msp430x22x4.h"#include "RBX430-1.h"

// still lifesconst uint8 block[] = { "x = 2, y = 2, rule = B3/S23\n2o$2o!" };const uint8 beehive[] = { "x = 3, y = 4, rule = B3/S23\nbo$obo$obo$bo!" };const uint8 loaf[] = { "x = 4, y = 4, rule = B3/S23\nb2o$o2bo$obo$bo!" };const uint8 boat[] = { "x = 3, y = 3, rule = B3/S23\n2o$obo$bo!" };

// oscillatorsconst uint8 blinker[] = { "x = 3, y = 1, rule = B3/S23\n3o!" };const uint8 toad[] = { "x = 4, y = 2, rule = B3/S23\nb3o$3o!" };const uint8 beacon[] = { "x = 4, y = 4, rule = B3/S23\n2b2o$3bo$o$2o!" };

const uint8 by_flop[] = { "x = 6, y = 7, rule = B3/S23\n" "3bo$bobo$5bo$5o$5bo$bobo$3bo!" };

const uint8 hexapole[] = { "x = 9, y = 9, rule = B3/S23\n" "2o$obo2$2bobo2$4bobo2$6bobo$7b2o!" };

Size of patternUpper left corner

3 dead cells, 1 live cell, and next row

Page 29: Lab  9a – The Game of Life

BYU CS 224 The Game of Life 29

RBX430-1 LCD160 x 160 x 5pixels display

row

(0-

79)

col (0-79)

uint8 life[80][10];

life[row][col/8]& 0x01 << (col

%8)lcd_point(col*2, row*2, 7);

Page 30: Lab  9a – The Game of Life

BYU CS 224 The Game of Life 30

RBX430-1 LCD160 x 160 x 5pixels display

row

(0-

79)

col (0-79)

uint8 life[80][10];

life[row][col/8]& 0x80 >> (col

%8)lcd_point(col*2, row*2, 7);

Page 31: Lab  9a – The Game of Life

The Game of Life 31

C Pre-processor C Pre-processor macros

Simplify coding Make program more readable Helps avoid errors from repetition.

BYU CS 224

#define MASK(bit) (0x80 >> (bit%8))#define SET_CELL(byte,bit) byte |= MASK(bit);#define CLEAR_CELL(byte,bit) byte &= ~MASK(bit);#define TOGGLE_CELL(byte,bit) byte ^= MASK(bit);#define TEST_CELL(byte,bit) (byte & MASK(bit));

SET_CELL(life[row][col/8],col);CLEAR_CELL(life[row][col/8],col);TOGGLE_CELL(life[row][col/8],col);if (TEST_CELL(temp[col/8],col)) { ... };

Page 32: Lab  9a – The Game of Life

CELL BIRTH: Set cell bit in life array:life[(row)][(col) >> 3] |= (0x80 >> ((col) & 0x07));CELL DEATH: Clear cell bit in life array:life[(row)][(col) >> 3] &= ~(0x80 >> ((col) & 0x07));TEST CELL: Test cell bit in a specified single dimensioned row (alive or dead?):(life_row[(col) >> 3] & (0x80 >> ((col) & 0x07)) ? 1 : 0)

0000 0000 0000 0000 0000 0000Life_row[0] Life_row[1] Life_row[2]

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

To test logical column 17, we need to find the physical bit corresponding to this valueFirst, we find the byte in the row by dividing by 8 (col >> 3), this gives us 17/8=2 or Life_row[2]

Next we create a bit mask to select the correct bit in the physical byte. col&0x7 is the same as col%8 or 17&0x7 = 0x0001 0001 & 0x0000 0111 = 10x80 >> 1 = 1000 0000 >> 1 = 0100 0000, which is the mask we need to select bit 17.For cell birth we use |= to turn this bit on. For cell death we use &= with the ones complement of this value to turn the bit off.

0100 0000

~(0100 0000) = 1011 1111BYU CS 224 The Game of Life 32

Page 33: Lab  9a – The Game of Life

0 40 80

0

40

80

Life Array

In order to encode draw_rle_pattern(40,60,beacon) Given beacon[] = { "x = 4, y = 4, rule = B3/S23\n2o$o$3bo$2b2o!" };First go to location 40,60 and add (y-1)=3 to the y value for 40,63Then add the 4 rows of entries specified in the beacon description.The last row should start at 40,60

40,63

40,60

11100010011

BYU CS 224 The Game of Life 33