Created
March 13, 2024 11:18
-
-
Save dfinke/852185fb1ab0d975cc687c3669b3eb84 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
param( | |
$Alive = 'O', | |
$Dead = ' ', | |
$SleepInSeconds = .5 | |
) | |
<# | |
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) # not needed - Get-Random is cryptographically random by default | |
$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 -Seconds $SleepInSeconds | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment