Skip to content

Instantly share code, notes, and snippets.

@Pome-ro
Created February 2, 2023 01:44
Show Gist options
  • Save Pome-ro/53c8119e3119c87e9033402604e8ba27 to your computer and use it in GitHub Desktop.
Save Pome-ro/53c8119e3119c87e9033402604e8ba27 to your computer and use it in GitHub Desktop.
GPT Battle Ship PowerShell
# Function to display the game board
function DisplayBoard {
Write-Host " A B C D E F G H I J"
for ($i=0; $i -lt 10; $i++) {
Write-Host ($i + 1) " " $board[$i]
}
}
# Function to get user input for ship placement
function GetInput {
$input = Read-Host "Enter coordinate (e.g. A5): "
$column = [char]$input[0] - 65
$row = [int]$input[1] - 1
return ,$row, $column
}
# Function to place the ship on the board
function PlaceShip {
$shipCoordinates = @()
$shipLength = $args[0]
$start = GetInput
$row = $start[0]
$column = $start[1]
Write-Host "Enter direction (u, d, l, r): "
$direction = Read-Host
switch ($direction) {
"u" {for ($i=0; $i -lt $shipLength; $i++) {$shipCoordinates += ,$row--, $column}}
"d" {for ($i=0; $i -lt $shipLength; $i++) {$shipCoordinates += ,$row++, $column}}
"l" {for ($i=0; $i -lt $shipLength; $i++) {$shipCoordinates += ,$row, $column--}}
"r" {for ($i=0; $i -lt $shipLength; $i++) {$shipCoordinates += ,$row, $column++}}
}
foreach ($coordinate in $shipCoordinates) {
if ($coordinate[0] -lt 0 -or $coordinate[0] -ge 10 -or $coordinate[1] -lt 0 -or $coordinate[1] -ge 10) {
Write-Host "Invalid placement."
PlaceShip $shipLength
return
}
if ($board[$coordinate[0]][$coordinate[1]] -ne "~") {
Write-Host "Invalid placement."
PlaceShip $shipLength
return
}
}
foreach ($coordinate in $shipCoordinates) {
$board[$coordinate[0]][$coordinate[1]] = "X"
}
}
# Function to get user guess
function GetGuess {
$guess = Read-Host "Enter guess (e.g. A5): "
$column = [char]$guess[0] - 65
$row = [int]$guess[1] - 1
return ,$row, $column
}
# Function to play the game
function PlayGame {
$hits = 0
while ($hits -lt 17) {
DisplayBoard
$guess = GetGuess
if ($board[$guess[0]][$guess[1]] -eq "X") {
Write-Host "Hit!"
$board[$guess[0]][$guess[1]] = "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment