Got the maze algorithm to work. Turns out Go considers a change in type as meaning to make a new variable.

master
Zed A. Shaw 1 week ago
parent 49f2c0fe34
commit 306fe54a87
  1. 41
      main.go

@ -4,14 +4,14 @@ package main
import (
"os"
"log"
"fmt"
"time"
"math/rand"
"strings"
"github.com/gdamore/tcell/v2"
"github.com/gdamore/tcell/v2/encoding"
)
var dbg *log.Logger
const (
WALL = '#'
SPACE = '.'
@ -133,7 +133,7 @@ func (game *Game) Inbounds(pos Position) bool {
}
func (game *Game) Neighbors(near Position) []Position {
result := make([]Position, 0)
result := make([]Position, 0, 4)
points := compass(near.x, near.y, 2)
for _, pos := range points {
@ -149,16 +149,18 @@ func (game *Game) NeighborWalls(pos Position) []Position {
neighbors := game.Neighbors(pos)
result := make([]Position, 0)
for _, pos := range neighbors {
if game.level[pos.y][pos.x] == WALL {
result = append(result, pos)
for _, at := range neighbors {
cell := game.level[at.y][at.x]
if cell == WALL {
result = append(result, at)
}
}
return result
}
func (game *Game) FindCoord() (*Position, *Position) {
func (game *Game) FindCoord() []Position {
for y := 1; y < game.height ; y += 2 {
for x := 1; x < game.width ; x += 2 {
if game.level[y][x] != WALL {
@ -169,13 +171,13 @@ func (game *Game) FindCoord() (*Position, *Position) {
for _, pos := range found {
if game.level[pos.y][pos.x] == SPACE {
return &Position{x, y}, &pos
return []Position{Position{x, y}, pos}
}
}
}
}
return nil, nil
return nil
}
func (game *Game) HuntAndKill() []Position {
@ -187,25 +189,26 @@ func (game *Game) HuntAndKill() []Position {
if len(neighbors) == 0 {
dead_ends = append(dead_ends, on)
on, found := game.FindCoord()
if on == nil { break }
next_guess := game.FindCoord()
if next_guess == nil { break }
on = next_guess[0]
found := next_guess[1]
game.level[on.y][on.x] = SPACE
row := (on.y + found.y) / 2
col := (on.x + found.x) / 2
game.level[row][col] = SPACE
game.status = fmt.Sprintf("DEAD END %d,%d", row, col)
} else {
nb := neighbors[rand.Int() % len(neighbors)]
rand_neighbor := rand.Int() % len(neighbors)
nb := neighbors[rand_neighbor]
game.level[nb.y][nb.x] = SPACE
row := (nb.y + on.y) / 2
col := (nb.x + on.x) / 2
game.level[row][col] = SPACE
on = nb
game.status = "HUNTING!"
}
game.Render()
time.Sleep(200 * time.Millisecond)
}
game.status = "FINISHED"
@ -229,6 +232,10 @@ func (game *Game) MakeMap(width int, height int) {
// This program just prints "Hello, World!". Press ESC to exit.
func main() {
out, err := os.Create("debug.log")
if err != nil { log.Fatal(err) }
dbg = log.New(out, "", log.LstdFlags)
game := MakeGame()
game.MakeMap(27,17)
game.Render()

Loading…
Cancel
Save