Flipping bits game: Difference between revisions

Content added Content deleted
(Category:Games)
(New Go code)
Line 888: Line 888:
Congratulations! You finished the game!
Congratulations! You finished the game!
3 moves were taken by you!!
3 moves were taken by you!!
</pre>

=={{header|Go}}==
<lang Go>
package main

import (
"fmt"
"math/rand"
"time"
"bufio"
"os"
"strconv"
)

type matrix [3][3]int

func main() {
var target, current matrix
var s,t string
var moves int
moves = 1
target = randMatrix()
current = randMatrix()
fmt.Println("Target:")
drawBoard(target)
fmt.Println("\nBoard:")
drawBoard(current)
if target == current {
fmt.Println("You win!")
} else {
fmt.Println("Go on, next move!")
}
for {
fmt.Print("Flip row (r) or column (c) 1 .. 3 (c1, r3, ...): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanBytes)
i := 0
for scanner.Scan () {
if i==0 {
s = scanner.Text()
}
if i==1 {
t = scanner.Text()
}
i++
if i>1 { break }
}
moves++
u, _ := strconv.ParseInt(t,0,64)
if u>3 {
fmt.Println("Wrong command!")
break
}
switch s {
case "c": {
fmt.Printf("Column %s will be flipped\n", t)
for i:=0;i<3;i++ {
if current[i][u-1]==0 {
current[i][u-1]=1
} else {
current[i][u-1]=0
}
}
}
case "r": {
fmt.Printf("Row %s will be flipped\n", t)
for i:=0;i<3;i++ {
if current[u-1][i]==0 {
current[u-1][i]=1
} else {
current[u-1][i]=0
}
}
}
default: {
fmt.Println("Wrong command!")
break
}
}
fmt.Println("\nMoves taken: ", moves)
fmt.Println("Target:")
drawBoard(target)
fmt.Println("Board:")
drawBoard(current)
if target == current {
fmt.Println("You win!")
break
} else {
continue
}
}
}

func drawBoard(todraw matrix) {
fmt.Println(" 1 2 3")
for i:=0;i<3;i++ {
fmt.Print(i+1, " ")
for j:=0;j<3;j++ {
fmt.Print(todraw[i][j], " ")
if j==2 { fmt.Print("\n") }
}
}
}

func randMatrix() matrix {
var randMat matrix
rand.Seed(time.Now().UTC().UnixNano())
for i:=0;i<3;i++ {
for j:=0;j<3;j++ {
randMat[i][j]=rand.Intn(2)
}
}
return randMat
}
</lang>

Example:

<pre>
Target:
1 2 3
1 1 0 1
2 0 0 1
3 0 1 0

Board:
1 2 3
1 0 0 1
2 1 0 0
3 1 0 1
Go on, next move!
Flip row (r) or column (c) 1 .. 3 (c1, r3, ...):
</pre>
</pre>