Guest User

Untitled

a guest
Mar 14th, 2018
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. # conway.r
  2. # Thomson Nguyen
  3. # tn248@cam.ac.uk
  4.  
  5. # Simulates Conway's Game of Life
  6. # size: the length of our starting matrix (a size^2 square)
  7. #
  8. # MIT License blah blah blah
  9. #
  10. # Directions:
  11. # 1. Run script
  12. # 2. Press enter to timestep
  13. # 3. Breaks on non-blank input.
  14.  
  15. size <- 200
  16. grid <- FALSE
  17.  
  18. matrix <- matrix(round(c(runif((size^2)))),nrow=size)
  19.  
  20. nrows <- dim(matrix)[1]
  21. ncols <- dim(matrix)[2]
  22.  
  23. squaresize <- 60/max(c(nrows+1,ncols+1))
  24.  
  25. left = c(2:nrows,1)
  26. right = c(nrows,1:nrows-1)
  27. up = c(2:ncols,1)
  28. down = c(ncols,1:ncols-1)
  29.  
  30. k = ""
  31. # stop on keypress
  32. while (nchar(k) == 0){
  33. matrix.neigh <- matrix[,up] + matrix[left,] + matrix[,down] + matrix[right,] + matrix[left,up] + matrix[left,down] + matrix[right,up] + matrix[right,down]
  34.  
  35. # Conway's rules
  36. mnew = matrix
  37. mnew[(matrix==1 & matrix.neigh <= 1) | (matrix==1 & matrix.neigh >= 4)] <- 0
  38. mnew[matrix==0 & matrix.neigh==3] <- 1
  39. matrix = mnew
  40.  
  41. m1 <- which((matrix==1),arr.ind=TRUE)
  42. if (grid == TRUE) m0 <- which((matrix==0),arr.ind=TRUE)
  43.  
  44. # plot time
  45. plot(NA,xlim=c(0,ncols),ylim=c(nrows,0),xlab="",ylab="")
  46. points(m1[,c(2,1)],cex=squaresize,bg="blue")
  47. if (grid == TRUE) points(m0[,c(2,1)],pch=22,cex=squaresize)
  48. k <- scan(what = "character",nmax = 1,quiet=TRUE)
  49. k <- paste(k,"",sep="")
  50. }
Add Comment
Please, Sign In to add comment