
% Homework 4
% gameOfLife.m
% CS 1109, Summer 2011
% July 18

% This is the main script for our Game of Life simulator. It initializes
% the matrices containing the life data, draws the GUI and then runs loop
% updating the state of the simulation. We are listening to user inputs all
% the time via the GUI buttons

% Clean up things before we start
clf
clc
clear all

% Default starting pattern
startingPattern = 'glider';

% Size of the drawing grid (n x n)
gridSize = 90;

% Set up the initial pattern
[blueCells redCells] = initPattern(startingPattern);

% Use current bitmap to create an image and display it
z = zeros(gridSize, gridSize);
imageHandle = image(cat(3, redCells, z, blueCells));
set(imageHandle, 'erasemode', 'none')

% Draw the rest of the GUI
setupGUI;

% Flags to control simulation
quit = false;   % flag to indicate a quit
run = false;    % flag to indicate we are running
freeze = false; % flag to indicate a pause
generation = 0; % generation #

% Run simulation for as long as the user doesn't hit the quit button
while (~quit)
    
    % If we are running the simulation, then compute the next state of all
    % the cells based on the current state of the cells
    if (run)
        
        % Compute the next state of the cells
        [blueCells redCells] = nextState(blueCells, redCells);
        
        % Refresh the image
        set(imageHandle, imgType, cat(3, redCells, z, blueCells));
        
        % Update generation count
        generation = generation + 1;
        set(stepNumberHandle, 'string', ...
            sprintf('Generation: %d', generation));
        
    end
    
    % If the user hit the freeze button, then we pause the animation
    if (freeze)
        run = false;
        freeze = false;
    end
    
    % Flush draw buffer
    drawnow;
    
end


