1 / 33

Lab 9a – The Game of Life

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.

baby
Download Presentation

Lab 9a – The Game of Life

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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. 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." The Game of Life

  2. 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. The Game of Life

  3. Questions… • What is the RAM size of the MSP430F2274? • How many Life cells in an 80 x 80 array? • What is the smallest data type required to store a Life cell? • 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. The Game of Life

  4. 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. The Game of Life

  5. 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. 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.. life[row][col/8] |= (0x80 >> (col%8)); • life[row][col/8] &= ~(0x80 >> (col%8)); The Game of Life

  7. 160 x 160 x 5 pixels display RBX430-1 LCD col (0-79) life[row][col/8] & (0x80 >> (col%8)) row (0-79) lcd_point(col*2, row*2, 7); uint8 life[80][10]; The Game of Life

  8. 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) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 0000 0000 0000 0000 0000 0000 Life_row[0] Life_row[2] Life_row[1] 0100 0000 To test logical column 17, we need to find the physical bit corresponding to this value First, 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 = 1 0x80 >> 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) = 1011 1111

  9. Life Array 80 40,63 11 1 0001 0011 40,60 40 0 80 40 0 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,63 Then add the 4 rows of entries specified in the beacon description. The last row should start at 40,60

  10. C Pre-processor • C Pre-processor macros • Simplify coding • Make program more readable • Helps avoid errors from repetition. #define MASK(col) (0x80 >> (col%8)) #define SET_CELL(a2d,row,col) a2d[row][col/8] |= MASK(col) #define CLEAR_CELL(a2d,row,col) a2d[row][col/8] &= ~ MASK(col) #define TOGGLE_CELL(a2d,row,col) a2d[row][col/8] ^= MASK(col) #define CELL_VALUE(a1d,col) ((a1d[col/8] & MASK(col)) ? 1 : 0) SET_CELL(life,row,col); CLEAR_CELL(life,row,col); TOGGLE_CELL(life,row,col); if (CELL_VALUE(temp,col) == 0) { ... }; The Game of Life

  11. “Sliding” Window into life 1. Initpr, cr, nr from life array. 1 neighbor Cell dies 2. Use pr, cr, nr to update current row in life array. 3. Copy cr to pr, nr to cr, and current row+1 to nr from life array. The Game of Life

  12. “Sliding” Window into life 3 neighbors Cell birth 4. Use pr, cr, nr to update current row in life array. 2 neighbors Cell survives 3 neighbors Cell birth 5. Copy cr to pr, nr to cr, and current row+1 to nr from life array. 1 neighbor Cell death 6. Use pr, cr, nr to update current row in life array. The Game of Life

  13. 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 The Game of Life

  14. Parsing String Parsing • What is the value of X? char str[] = "Point X = 100"; Walk the array until token or NULL terminator. (Token must be unique) • Find token: char* ptr = str; int number = 0; while (*ptr && (*ptr++ != 'X')); • Find beginning of number: while (*ptr && !isdigit(*ptr)) ++ptr; • Convert to decimal: while (isdigit(*ptr)) number = number * 10 + (*ptr++ - '0'); isdigit returns 0 or 1 • Proceed with parsing of line. Return result in number The Game of Life

  15. 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 BIRD seed for the 60-second club.) The Game of Life

  16. Life Patterns Gosper Glider Gun The Game of Life

  17. 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_resultsafter every generation. The simulation will stop and display the average generations per second immediately after seconds equals 60. Your goal should be to make the top 10 list of the 60 Second Club. The Game of Life

  18. Life Requirements 1 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. 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.) 4 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. 1 point Each successive generation takes no longer than 1/5 of a second to create and display. The Game of Life

  19. 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! The Game of Life

  20. 60 Second Club Rules Rules will be used in determining the top 10 submissions: • Your Life program is written in C (no assembly please!) • Set both your CCS project Optimization level and Control speed vs. size trade-offs to 1. (Project->Properties->Build->MSP430 Compiler->Optimization) • Use the "BIRD" set of patterns as the Life seed to determine placement in the top 10 rankings. • Clear the generation and seconds counter at the beginning of the game. • The function display_results is called for every generation. The simulation will stop and display the average generations per second immediately after seconds equals 60. • Use any C library function (without modification) in your implementation. • Submit your source to a TA for verification. If your speed is faster than any in the following list, you will be added! The Game of Life

  21. 60 Second Club The Game of Life

  22. 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. The Game of Life

  23. How to Proceed • Do a thorough design – use systematic decomposition. • Verify demo Life works correctly. • Add a simple pattern (ie. Blinker) to your life grid. • Add B3/S23 logic and test. • Program RLE loader and test. • Optimize and use regression tests. • Test, test, test. The Game of Life

  24. 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 “Life is governed by 4 simple rules!” The Game of Life

  25. The Game of Life

  26. #includes needed for Life lab Bit Life grid array Previous, current, and next row life.c // includes ----------------------------------------------------------- #include "msp430.h" #include <stdlib.h> #include "RBX430-1.h" #include "RBX430_lcd.h" #include "life.h" // global variables --------------------------------------------------- extern volatile uint16 WDT_Sec_Cnt; // WDT second counter extern volatile uint16 seconds; // # of seconds extern volatile uint16 switches; // debounced switch values uint8 life[NUM_ROWS][NUM_COLS/8]; // 80 x 80 life grid uint8 life_pr[NUM_COLS/8]; // previous row uint8 life_cr[NUM_COLS/8]; // current row uint8 life_nr[NUM_COLS/8]; // next row enum { BIRTH = 1, DEATH = 3 }; The Game of Life

  27. life.c Initialize RBX430 and LCD // main ---------------------------------------------------------------- void main(void) { RBX430_init(_16MHZ); // init board ERROR2(lcd_init()); // init LCD //lcd_volume(360); // 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 generation; // generation counter uint16 row, col; uint16 neighbors = BIRTH; // cell neighbors // setup beginning life generation init_life(BIRD); // load a new life seed into LCD WDT_Sec_Cnt= WDT_1SEC_CNT; // reset WD 1 second counter seconds = 0; // clear second counter switches = 0; // clear switch variable generation = 0; // start generation counter Setup switches and Watchdog as timer Splash screen Wait for switch The Game of Life

  28. 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() Real-time Stats For each column For each row The Game of Life

  29. life.h Life value, birth and death macros #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 lifes extern const uint8 block[]; extern const uint8 beehive[]; extern const uint8 loaf[]; extern const uint8 boat[]; // oscillators extern const uint8 blinker[]; extern const uint8 toad[]; extern const uint8 beacon[]; extern const uint8 by_flop[]; extern const uint8 hexapole[]; extern const uint8 pulsar[]; ... Seed enums Life Patterns The Game of Life

  30. lifelib.c //************************************************************************* // includes #include "msp430x22x4.h" #include "RBX430-1.h" // still lifes const 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!" }; // oscillators const 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 pattern Upper left corner 3 dead cells, 1 live cell, and next row The Game of Life

  31. 160 x 160 x 5 pixels display RBX430-1 LCD col (0-79) life[row][col/8] & 0x01 << (col%8) lcd_point(col*2, row*2, 7); row (0-79) uint8 life[80][10]; The Game of Life

  32. 160 x 160 x 5 pixels display RBX430-1 LCD col (0-79) life[row][col/8] & 0x80 >> (col%8) lcd_point(col*2, row*2, 7); row (0-79) uint8 life[80][10]; The Game of Life

  33. C Pre-processor • C Pre-processor macros • Simplify coding • Make program more readable • Helps avoid errors from repetition. #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)) { ... }; The Game of Life

More Related