Skip to content

Instantly share code, notes, and snippets.

@dfinke
Last active July 24, 2021 18:26
Show Gist options
  • Save dfinke/a4e47bda65a3674c667fa8e61138d0fd to your computer and use it in GitHub Desktop.
Save dfinke/a4e47bda65a3674c667fa8e61138d0fd to your computer and use it in GitHub Desktop.
The classic cellular automata simulation
param(
$ALIVE = 'O',
$DEAD = ' '
)
# Conway's Game of Life
# The classic cellular automata simulation. Press Ctrl-C to stop.
# More info at: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
$WIDTH = 79 # The width of the cell grid.
$HEIGHT = 20 # The height of the cell grid.
$null = Get-Random -SetSeed ([Environment]::TickCount)
$nextCells = @{}
foreach ($x in 0..($WIDTH - 1)) {
foreach ($y in 0..($HEIGHT - 1)) {
if ((Get-Random -Minimum 0 -Maximum 8) -eq 0) {
$nextCells.$x += @{$y = $ALIVE }
}
else {
$nextCells.$x += @{$y = $DEAD }
}
}
}
while ($true) {
"`n" * ($HEIGHT - 7)
$Host.UI.RawUI.CursorSize = 0
$cells = $nextCells.Clone()
foreach ($y in 1..($HEIGHT - 1)) {
foreach ($x in 0..($WIDTH - 1)) {
$Host.UI.RawUI.CursorPosition = [System.Management.Automation.Host.Coordinates]::new($x, $y)
$Host.UI.Write($cells.$x.$y)
}
}
''
'Press Ctrl+C to quit.'
foreach ($x in 0..($WIDTH - 1)) {
foreach ($y in 0..($HEIGHT - 1)) {
$left = ($x - 1) % $WIDTH
$right = ($x + 1) % $WIDTH
$above = ($y - 1) % $HEIGHT
$below = ($y + 1) % $HEIGHT
$numNeighbors = 0
if ($cells.$left.$above -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$x.$above -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$right.$above -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$left.$y -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$right.$y -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$left.$below -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$x.$below -eq $ALIVE) {
$numNeighbors += 1
}
if ($cells.$right.$below -eq $ALIVE) {
$numNeighbors += 1
}
# Set cell based on Conway's Game of Life rules
if ($cells.$x.$y -eq $ALIVE -and ($numNeighbors -eq 2 -or $numNeighbors -eq 3)) {
# Living cells with 2 or 3 neighbors stay alive
$nextCells.$x.$y = $ALIVE
}
elseif ($cells.$x.$y -eq $DEAD -and $numNeighbors -eq 3) {
# Dead cells with 3 neighbors come to life
$nextCells.$x.$y = $ALIVE
}
else {
# All other cells die
$nextCells.$x.$y = $DEAD
}
}
}
Start-Sleep .5
}
@dfinke
Copy link
Author

dfinke commented Jul 16, 2021

ConwayGameOfLife

@sheldonhull
Copy link

So cool @dfinke! I'm been wanting to tackle this in Go and never even thought of it being done in PowerShell. Thanks for this, pinning this one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment