r/PowerShell • • 27d ago

Script Sharing Enjoy a,fun game of Minesweeper

I got bored the other night after work and killed the time making Minesweeper. There wasn't a lick of AI help here, just old man brain and an appreciation for bitwise operators. Fully functional Minesweeper in less than 200 lines of PowerShell. Enjoy!

Default board is 9x9 with 10 mines like classic minesweeper. You can change the size by updating the variables, but I don't have logic in there to make sure the board will work. That's on you.

Controls: Up/down/left/right arrows = move Spacebar = sweep the cell F = set flag

function CalculateProximity {
    for ($col = 0; $col -lt $Script:field.GetLength(0); $col++) {
        for ($row = 0; $row -lt $Script:field.GetLength(1); $row++) {
            #This is a mine. Set proximity to -1 and continue to next cell.
            if ($Script:BIT_MINE -eq ($Script:field[$col, $row] -band $Script:BIT_MINE)) {
                $Script:proximitymap[$col, $row] = -1
                continue
            }
            $proximity = 0
            for ($tempX = $col - 1; $tempX -le $col + 1; $tempX++) {
                for ($tempY = $row - 1; $tempY -le $row + 1; $tempY++) {
                    #out of bounds, skip
                    if ($tempX -lt 0 -or $tempY -lt 0) { continue }
                    if ($tempX -ge $Script:field.GetLength(0) -or $tempY -ge $Script:field.GetLength(1)) { continue }
                    #skip the current [col,row] cell itself, only calculate cells around it
                    if ($tempX -eq $col -and $tempY -eq $row) { continue }
                    if ($Script:BIT_MINE -eq ($Script:field[$tempX, $tempY] -band $Script:BIT_MINE)) { $proximity++ }
                }
            }
            $Script:proximitymap[$col, $row] = $proximity
        }
    }
}

function DrawFullField() {
    Clear-Host
    $text = [string]::new("#", $Script:field.GetLength(0))
    for ($i = 0; $i -lt $Script:field.GetLength(1); $i++) {
        $Host.UI.RawUI.CursorPosition = [System.Management.Automation.Host.Coordinates]::new(0, $i)
        $Host.UI.Write($text)
    }
    UpdateUI
}

function Sweep($CursorPos, [switch]$isRoot) {
    $Host.Ui.RawUI.CursorPosition = $CursorPos
    $val = $Script:field[$CursorPos.X, $CursorPos.Y]

    #swept previously or there is a flag set, exit
    if ($SCRIPT:BIT_SWEPT -eq ($val -band $SCRIPT:BIT_SWEPT)) { return $false }
    if ($Script:BIT_FLAG -eq ($val -band $Script:BIT_FLAG)) { return $false }

    #mine is here.
    if ($Script:BIT_MINE -eq ($val -band $Script:BIT_MINE) -and $isRoot.IsPresent) {
        $Host.UI.Write("*")
        $Host.UI.RawUI.CursorPosition = $CursorPos
        return $true
    }

    #Mark this cell as swept
    $Script:field[$CursorPos.X, $CursorPos.Y] = $Script:field[$CursorPos.X, $CursorPos.Y] -bor $SCRIPT:BIT_SWEPT    

    #Get the mine proximity on this cell. 0 = no mine. Positive = Mines Nearby. Negative = This cell is a mine.
    $proximity = $Script:proximitymap[$CursorPos.X, $CursorPos.Y]
    if ($proximity -ge 0) {
        $Script:UncheckedCells--
    }
    #Proximity > 0, write the number of nearby mines. 0, sweep through all adjacent cells that are also empty opening the field
    if ($proximity -gt 0) {
        $Host.UI.Write([System.ConsoleColor]::Yellow, [System.ConsoleColor]::Black, $proximity)
        $host.UI.RawUI.CursorPosition = $CursorPos
        return $false
    }
    elseif ($proximity -eq 0) {
        $Host.UI.Write(" ")
        $host.UI.RawUI.CursorPosition = $CursorPos
        for ($x = $CursorPos.X - 1; $x -le $CursorPos.X + 1; $x++) {
            for ($y = $CursorPos.Y - 1; $y -le $CursorPos.Y + 1; $y++) {
                #out of bounds, skip
                if ($x -lt 0 -or $y -lt 0) { continue }
                if ($x -ge $Script:field.GetLength(0) -or $y -ge $Script:field.GetLength(1)) { continue }
                #already swept or flag set, skip
                if ($SCRIPT:BIT_SWEPT -eq ($Script:field[$x, $y] -band $SCRIPT:BIT_SWEPT)) { continue }
                if ($Script:BIT_FLAG -eq ($Script:field[$x, $y] -band $Script:BIT_FLAG)) { continue }

                $null = Sweep -CursorPos ([System.Management.Automation.Host.Coordinates]::new($x, $y))
            }
        }
        $host.UI.RawUI.CursorPosition = $CursorPos
        return $false
    }
}

function UpdateUI {
    $Column = $Script:field.GetLength(0) + 3
    $UICoordinates = [System.Management.Automation.Host.Coordinates]::new($Column, 0)
    $Host.UI.RawUI.CursorPosition = $UICoordinates
    Write-Host ("Unchecked Cells: {0:D3}" -f $Script:UncheckedCells) -NoNewline
    $UICoordinates.Y++
    $Host.UI.RawUI.CursorPosition = $UICoordinates
    Write-Host ("      Flags Set: {0:D3}" -f $Script:FlagsSet) -NoNewline
    $UICoordinates.Y++
    $Host.UI.RawUI.CursorPosition = $UICoordinates
    Write-Host ("Remaining Mines: {0:D3}" -f $Script:RemainingMines) -NoNewline
}

function GameOver {
    for ($x = 0; $x -lt $Script:field.GetLength(0); $x++) {
        for ($y = 0; $y -lt $Script:field.GetLength(1); $y++) {
            $Host.UI.RawUI.CursorPosition = [System.Management.Automation.Host.Coordinates]::new($x, $y)
            switch (($Script:field[$x, $y] -band ($Script:BIT_MINE + $Script:BIT_FLAG))) {
                ($Script:BIT_MINE + $Script:BIT_FLAG) { $Host.UI.Write([System.ConsoleColor]::White, [System.ConsoleColor]::Green, 'F'); break; }
                ($Script:BIT_MINE) { $Host.UI.Write([System.ConsoleColor]::Black, [System.ConsoleColor]::Red, '*'); break; }
                ($Script:BIT_FLAG) { $Host.UI.Write([System.ConsoleColor]::Cyan, [System.ConsoleColor]::Magenta, 'X'); break; }
            }
        }
    }
}

#---Enter Script Here. Edit these three variables to change game size/difficulty
$columns = 9
$rows = 9
$mines = 10

$SCRIPT:BIT_MINE = 1
$SCRIPT:BIT_FLAG = 2
$SCRIPT:BIT_SWEPT = 4

$Script:field = [int[, ]]::new($columns, $rows)
$Script:proximitymap = [int[, ]]::new($columns, $rows)

$Script:UncheckedCells = $field.Length
$Script:RemainingMines = $mines
$Script:FlagsSet = 0
$filledMines = 0
while ($filledMines -lt $mines) {
    $posX = Get-Random -Maximum $columns
    $posY = Get-Random -Maximum $rows
    if ($Script:field[$posX, $posY] -ne 1) {
        $Script:field[$posX, $posY] = 1
        $filledMines++
    }
}
CalculateProximity
DrawFullField

$over = $false
$win = $false
$CursorPos = [System.Management.Automation.Host.Coordinates]::new(0, 0)
$Host.UI.RawUI.CursorPosition = $CursorPos
while (-not $over -and -not $win) {
    [Console]::CursorVisible = $true
    $nextKey = [Console]::ReadKey($true)
    [Console]::CursorVisible = $false
    switch ($nextKey.Key) {
        'RightArrow' { if ($CursorPos.X -lt $columns - 1) { $CursorPos.X++ }; $Host.UI.RawUI.CursorPosition = $CursorPos; break; }
        'LeftArrow' { if ($CursorPos.X -gt 0) { $CursorPos.X-- }; $Host.UI.RawUI.CursorPosition = $CursorPos; break; }
        'UpArrow' { if ($CursorPos.Y -gt 0) { $CursorPos.Y-- }; $Host.UI.RawUI.CursorPosition = $CursorPos; break; }
        'DownArrow' { if ($CursorPos.Y -lt $rows - 1) { $CursorPos.Y++ }; $Host.UI.RawUI.CursorPosition = $CursorPos; break; }
        'SpaceBar' { $over = Sweep -CursorPos $CursorPos -isRoot; break; }
        'F' {
            if (-not ($BIT_SWEPT -eq ($Script:field[$CursorPos.X, $CursorPos.Y] -band $Script:BIT_SWEPT))) {
                $Script:field[$CursorPos.X, $CursorPos.Y] = $Script:field[$CursorPos.X, $CursorPos.Y] -bxor $Script:BIT_FLAG
                if ($Script:BIT_FLAG -eq ($Script:field[$CursorPos.X, $CursorPos.Y] -band $Script:BIT_FLAG)) {
                    $Host.UI.Write([System.ConsoleColor]::Cyan, [System.ConsoleColor]::Black, "F")
                    $Script:FlagsSet++
                    $Script:UncheckedCells--
                    if ($Script:RemainingMines -gt 0) {
                        $Script:RemainingMines--
                    }
                }
                else {
                    $Host.UI.Write("#")
                    $Script:FlagsSet--
                    $Script:RemainingMines++
                    $Script:UncheckedCells++
                }
                $Host.UI.RawUI.CursorPosition = $CursorPos
            }
            break
        }
    }

    UpdateUI
    $Host.UI.RawUI.CursorPosition = $CursorPos

    if ($Script:UncheckedCells -eq $Script:RemainingMines) { $win = $true }
}

if ($win) {
    $Host.UI.RawUI.CursorPosition = [System.Management.Automation.Host.Coordinates]::new(0, $rows + 2)
    $Host.UI.Write("YOU WIN!")
}
elseif ($over) {
    GameOver
    $Host.UI.RawUI.CursorPosition = [System.Management.Automation.Host.Coordinates]::new(0, $rows + 2)
    $Host.UI.WriteLine("GAME OVER")
    [Console]::CursorVisible = $true
}
20 Upvotes

15 comments sorted by

4

u/I_see_farts 27d ago

Well, I'm impressed!

I had to play until I won and flagged all the mines. Fun game!

2

u/Ecrofirt 27d ago

Thanks!

1

u/hemping0 17d ago

haha yeah its weirdly addictive once you boot it up in the console

4

u/Icolan 27d ago

How do you ensure that the first square someone chooses does not have a mine in it? That was a problem in the classic minesweeper. Microsoft implemented a fix for it by not drawing the mines until the first square had been cleared, I think.

6

u/Ecrofirt 27d ago

I simply didn't :). Sometimes you just don't pick a lucky cell and you have to start over.

4

u/Icolan 27d ago

Nice, so true classic Minesweeper.

2

u/djmakcim 27d ago

but also, isn't that the way it goes? I mean the whole aspect is that bit of initial luck. That or I always assumed it was designed that way. 😂

2

u/Twist_and_pull 27d ago

This sub keeps impressing.

4

u/djmakcim 27d ago

with all the, "hey look at my latest (totally not Ai, but still Ai) built script for the community!"

1

u/Ecrofirt 26d ago

I really hope you aren't implying that I did any AI for this. 

It was possible for humans to land a man on the moon without AI. I think it's possible for a guy who's been doing some kind of programming for 2/3 of his life to make Minesweeper in Powershell with nothing more intelligent than his own brain 😂

2

u/djmakcim 26d ago

No, I didn't mean you sorry 😅 just that it has been showing up more and more. 

2

u/Ecrofirt 26d ago

Ah my apologies. I know what you mean by the ever growing amount of AI posts.

1

u/Twist_and_pull 24d ago

No, not those...

1

u/AGsec 23d ago

very nice, thank you OP! good job too, nice clean code and easy to read!

1

u/Ecrofirt 23d ago

Thanks!