Narktor
Narktor

Reputation: 1037

How to deal with "distorted" array-output

I'm trying to build a "connect four" in , usable via console commands, without any GUI.

I've written the code to initialize the gamefield via the output of an array. However, after the newline element in the array, after the very first line, the output gets moved a little to the left:

image of console output

The code i'm using that produces the error:

$initializegamefield = @()
$savedgamefield = @()

for ($i = 0; $i -lt 48; $i++) {
    if (($i -eq 7 ) -or ($i -eq 15) -or ($i -eq 23) -or ($i -eq 31) -or ($i -eq 39) -or ($i -eq 47)) {
        $initializegamefield += "`n"
        Write-Host "$($initializegamefield)"
        $savedgamefield += $initializegamefield
        $initializegamefield = @()
    } else {
        $initializegamefield += "A"
    }
}
#Write-Host "$($initializegamefield)"
Write-Host "$($savedgamefield)"

Here I've basically initialized the gamefield two times for testing purposes.
The first time it is initialized, it is done via outputting the array $initializegamefield after it has been filled with ONE ROW including the newline element.

Afterwards $initializegamefield is emptied (see if structure).
In addition, before it is emptied, it is saved to $savedgamefield.

Whilst the formatting of the gamefield is okay with the way I do it with $initializegamefield it isn't okay anymore when doing it it with $savedgamefield.

How can I avoid having this distortion of $savedgamefield?

Upvotes: 2

Views: 107

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Since your game field is a 6x8 array I'd recommend actually initializing it as an 6x8 array:

$height = 6
$width  = 8

$gamefield = New-Object 'Object[,]' $height, $width
for ($i=0; $i -lt $height; $i++) {
    for ($j=0; $j -lt $width; $j++) {
        $gamefield[$i, $j] = 'A'
    }
}

or at least as a "jagged" array (an array of arrays):

$height = 6
$width  = 8

$gamefield = @()
for ($i=0; $i -lt $height; $i++) {
    $gamefield += ,@(1..$width | ForEach-Object { 'A' })
}

Upvotes: 1

Related Questions