Created
October 13, 2009 16:58
-
-
Save itsthomson/209371 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# conway.r | |
# Thomson Nguyen | |
# tn248@cam.ac.uk | |
# Simulates Conway's Game of Life | |
# size: the length of our starting matrix (a size^2 square) | |
# | |
# MIT License blah blah blah | |
# | |
# Directions: | |
# 1. Run script | |
# 2. Press enter to timestep | |
# 3. Breaks on non-blank input. | |
size <- 200 | |
grid <- FALSE | |
matrix <- matrix(round(c(runif((size^2)))),nrow=size) | |
nrows <- dim(matrix)[1] | |
ncols <- dim(matrix)[2] | |
squaresize <- 60/max(c(nrows+1,ncols+1)) | |
left = c(2:nrows,1) | |
right = c(nrows,1:nrows-1) | |
up = c(2:ncols,1) | |
down = c(ncols,1:ncols-1) | |
k = "" | |
# stop on keypress | |
while (nchar(k) == 0){ | |
matrix.neigh <- matrix[,up] + matrix[left,] + matrix[,down] + matrix[right,] + matrix[left,up] + matrix[left,down] + matrix[right,up] + matrix[right,down] | |
# Conway's rules | |
mnew = matrix | |
mnew[(matrix==1 & matrix.neigh <= 1) | (matrix==1 & matrix.neigh >= 4)] <- 0 | |
mnew[matrix==0 & matrix.neigh==3] <- 1 | |
matrix = mnew | |
m1 <- which((matrix==1),arr.ind=TRUE) | |
if (grid == TRUE) m0 <- which((matrix==0),arr.ind=TRUE) | |
# plot time | |
plot(NA,xlim=c(0,ncols),ylim=c(nrows,0),xlab="",ylab="") | |
points(m1[,c(2,1)],cex=squaresize,bg="blue") | |
if (grid == TRUE) points(m0[,c(2,1)],pch=22,cex=squaresize) | |
k <- scan(what = "character",nmax = 1,quiet=TRUE) | |
k <- paste(k,"",sep="") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment