######################################################################### # # # gameoflife.R - an R script to implement Conway's Game of Life # # # # The starting matrix is created as a size*size matrix with elements # # picked randomly from [0,1]. If grid is set to TRUE, cells will # # be represented by boxes, filled or unfilled for populated or # # retrospectively. If grid is set to FALSE, only populated cells will # # be shown. # # # # Luke Jostins, 13/10/07 # # # ######################################################################### # set initial conditions size <- 150 grid <- FALSE # create a random matrix (TODO: change to a more interesting one) M <- matrix(round(c(runif((size^2)))),nrow=size) # calculate dimensions, and thus the size of the cells nrows <- dim(M)[1] ncols <- dim(M)[2] squaresize <- 60/max(c(nrows+1,ncols+1)) # create vectors for all movememnts left = c(2:nrows,1) right = c(nrows,1:nrows-1) up = c(2:ncols,1) down = c(ncols,1:ncols-1) # run the game until something is typed k = "" while (nchar(k) == 0){ # create the neighbour matrix (shifting toroidally) M.neigh <- M[,up] + M[left,] + M[,down] + M[right,] + M[left,up] + M[left,down] + M[right,up] + M[right,down] # implement rules Mnew = M Mnew[(M==1 & M.neigh <= 1) | (M==1 & M.neigh >= 4)] <- 0 # kill if alone or crowded Mnew[M==0 & M.neigh==3] <- 1 # revive if 3 neighbours M = Mnew # find co-ordinates of ones (and zeros if asked for) M1s <- which((M==1),arr.ind=TRUE) if (grid == TRUE) M0s <- which((M==0),arr.ind=TRUE) #plot the ones (#and zeroes) plot(NA,xlim=c(0,ncols+1),ylim=c(nrows+1,0),axes=FALSE,xlab="",ylab="") points(M1s[,c(2,1)],pch=22,cex=squaresize,bg="black") if (grid == TRUE) points(M0s[,c(2,1)],pch=22,cex=squaresize) # give a prompt, and store result (ensure not NULL) k <- scan(what = "character",nmax = 1,blank.lines.skip=TRUE,quiet=TRUE) k <- paste(k,"",sep="") }