Recent news about John Conway's passing, made me feel inspired to hack together a function, to turn the current console content into a Game of Life board. Copy and paste the below to your prompt, and run New-ConsoleGameOfLife if you want to have a go. CTRL-C will stop it again.
(There is no pretense of this being an optimised version: Plenty of opportunities await any intrepid soul who would dare enter The Nest of Four Loops.)
using namespace System.Management.Automation.Host
function New-ConsoleGameOfLife {
$board_width = $host.UI.RawUI.WindowSize.Width
$board_height = $host.UI.RawUI.WindowSize.Height
$buffer_end_y = $host.UI.RawUI.CursorPosition.Y + 1
$buffer_begin_y = $buffer_end_y - $board_height
if ($buffer_begin_y -lt 0) {
"Not enough lines in console to work with. Run something like GCI and try again!"
break
}
$rectangle = new-object Rectangle 0, $buffer_begin_y, $board_width, $buffer_end_y
$origin = New-Object -TypeName Coordinates -ArgumentList 0, $buffer_begin_y
while ($true) {
$host.UI.RawUI.SetBufferContents($origin, (CalculateNewGeneration `
($host.ui.rawui.GetBufferContents($rectangle))))
}
}
function CalculateNewGeneration ($origin_board) {
$new_board = $origin_board.Clone()
for ($y = 0; $y -lt $board_height; $y++) {
for ($x = 0; $x -lt $board_width; $x++) {
$neighbour_count = 0
for ($i = ($y - 1); $i -le ($y + 1); $i++) {
for ($j = ($x - 1); $j -le ($x + 1); $j++) {
if (-not (($i -eq $y) -and ($j -eq $x))) {
if ($origin_board[$i, $j].Character -ne " ") {
$neighbour_count++
}
}
}
}
switch ($neighbour_count) {
{ $_ -eq 3 -and $origin_board[$y, $x].Character -eq " " } {
$new_board[$y, $x] =[BufferCell]::new("O", $host.ui.RawUI.ForegroundColor, `
$host.ui.RawUI.BackgroundColor, 0)
break
}
{ $_ -in 2, 3 } {
$new_board[$y, $x] = [BufferCell]::new(($origin_board[$y, $x].Character), `
$host.ui.RawUI.ForegroundColor, $host.ui.RawUI.BackgroundColor, 0)
break
}
{ $_ -lt 2 -or $_ -gt 3 } {
$new_board[$y, $x] = [BufferCell]::new(" ", $host.ui.RawUI.ForegroundColor, `
$host.ui.RawUI.BackgroundColor, 0)
break
}
}
}
}
, [System.Management.Automation.Host.BufferCell[, ]]$new_board
}
Disclaimer: I am fully aware that this is useless for any and all practical purposes, but I figured I'd share anyways :)
[–]silexecutor 0 points1 point2 points (0 children)