Created
February 14, 2025 19:12
-
-
Save nullset2/860c1fa88133645a05a3e75d252f09ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"time" | |
"math/rand" | |
) | |
var N = 4 | |
func main() { | |
grid := make([][]int, N) | |
sequence := make([]int, N*N) | |
for i, _ := range grid { | |
grid[i] = make([]int, N) | |
} | |
for i := 0; i < N*N; i++ { | |
sequence[i] = i | |
} | |
rand.Seed(time.Now().UnixNano()) | |
rand.Shuffle(len(sequence), func(i, j int) { | |
sequence[i], sequence[j] = sequence[j], sequence[i] | |
}) | |
var si, sj int | |
for i := 0; i < N; i++ { | |
for j := 0; j < N; j++ { | |
if sequence[N*i+j] == 0 { | |
si = i | |
sj = j | |
} | |
grid[i][j] = sequence[N*i+j] | |
} | |
} | |
// grid := [][]int{[]int{1, 2, 3, 4}, | |
// []int{5, 6, 7, 8}, | |
// []int{9, 10, 11, 12}, | |
// []int{13, 15, 14, 0}, | |
// } | |
// si := 3 | |
// sj := 3 | |
reader := bufio.NewReader(os.Stdin) | |
for { | |
fmt.Print("\033[H\033[2J") | |
for _, row := range grid { | |
fmt.Print("[") | |
for _, cell := range row { | |
if cell == 0 { | |
fmt.Printf(" ") | |
continue | |
} | |
fmt.Printf("%4d ", cell) | |
} | |
fmt.Printf("]\n") | |
} | |
if won(grid) { | |
fmt.Println("Congratulations!") | |
os.Exit(0) | |
} | |
input, _ := reader.ReadByte() | |
switch input { | |
case '\033': | |
next, _ := reader.ReadByte() | |
if next == '[' { | |
code, _ := reader.ReadByte() | |
switch code { | |
case 'A': | |
fmt.Println("Up arrow") | |
if si-1 >= 0 { | |
tmp := grid[si-1][sj] | |
grid[si-1][sj] = grid[si][sj] | |
grid[si][sj] = tmp | |
si = si - 1 | |
} | |
case 'B': | |
fmt.Println("Down arrow") | |
if si+1 < N { | |
tmp := grid[si+1][sj] | |
grid[si+1][sj] = grid[si][sj] | |
grid[si][sj] = tmp | |
si = si + 1 | |
} | |
case 'C': | |
fmt.Println("Right arrow") | |
if sj+1 < N { | |
tmp := grid[si][sj+1] | |
grid[si][sj+1] = grid[si][sj] | |
grid[si][sj] = tmp | |
sj = sj + 1 | |
} | |
case 'D': | |
fmt.Println("Left arrow") | |
if sj-1 >= 0 { | |
tmp := grid[si][sj-1] | |
grid[si][sj-1] = grid[si][sj] | |
grid[si][sj] = tmp | |
sj = sj - 1 | |
} | |
} | |
} | |
} | |
} | |
} | |
// 1, 2, 3... 15 | |
func won(grid [][]int) bool { | |
for i := 0; i < N; i++ { | |
for j := 0; j < N; j++ { | |
if j == N-1 && i == N-1 { | |
continue | |
} else if grid[i][j] != N*i+j+1 { | |
return false | |
} | |
} | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment