Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions 26-tui/05-snake-GAME/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Snake GAME

**ANSI escape codes**

- hide cursor `\033[?25l`
- show cursor `\033[?25h`
- clear `\033[2J`
- move cursor `\033[1;1H`

### Debugging

sending messages to stderr

```go
fmt.Fprintf(os.Stderr, "snake after: %v\n", g.snake)
```

send stderr to file

```sh
go run . 2> demo.txt
```

## References

[[00] I will teach you how to make games in your terminal 👾](https://www.youtube.com/watch?v=Fyf-Wh4ckDk)
199 changes: 199 additions & 0 deletions 26-tui/05-snake-GAME/game.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package main

import (
"fmt"
"log"
"math/rand"
"os"
"os/signal"
"strconv"
"time"

"github.com/mattn/go-tty"
)

const (
snakeSprite = "█"
foodSprite = "◆"
)

type game struct {
score int
snake *snake
food position
pause bool

x, y int
}

func newGame(x, y int) *game {
rand.Seed(time.Now().UnixNano())

game := &game{
score: 0,
snake: newSnake(x, y),
food: randomPosition(),
pause: false,
x: x,
y: y,
}

go game.listenForKeyPress()

return game
}

func (g *game) listenForKeyPress() {
tty, err := tty.Open()
if err != nil {
log.Fatal(err)
}
defer tty.Close()

for {
char, err := tty.ReadRune()
if err != nil {
panic(err)
}

switch char {
case 'w':
if g.snake.direction != south {
g.snake.direction = north
}

case 'a':
if g.snake.direction != east {
g.snake.direction = west
}

case 's':
if g.snake.direction != north {
g.snake.direction = south
}

case 'd':
if g.snake.direction != west {
g.snake.direction = east
}

case ' ':
g.pause = g.pause != true

// up arrow \x1b[A
case 'A':
increaseSpeed()

// down arrow \x1b[B
case 'B':
decreaseSpeed()
}
}
}

func (g *game) beforeGame() {
hideCursor(screen)

// handle CTRL C
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)

go func() {
for range c {
g.over()
}
}()
}

func (g *game) over() {
g.pause = true
time.Sleep(2 * time.Second)

clear(screen)
showCursor(screen)

moveCursor(screen, 1, 1)
draw(screen, "game over. score: "+strconv.Itoa(g.score))

render()

os.Exit(0)
}

func (g *game) placeNewFood() {
for {
newFoodPosition := randomPosition()

if sameSpot(newFoodPosition, g.food) {
continue
}

for _, pos := range g.snake.body {
if sameSpot(newFoodPosition, pos) {
continue
}
}

g.food = newFoodPosition

break
}
}

func (g *game) nextStep() {
if g.pause {
return
}

maxX, maxY := getSize()
sLen := len(g.snake.body)

oldTail := g.snake.body[sLen-1]

fmt.Fprintf(os.Stderr, "snake before: %v\n", g.snake)

if g.snake.moveAndEat(g.snake.direction, g.food) {
g.score += 1

moveCursor(screen, g.food.x, g.food.y)
draw(screen, snakeSprite)

g.placeNewFood()
moveCursor(screen, g.food.x, g.food.y)
draw(screen, foodSprite)
} else {
moveCursor(screen, oldTail.x, oldTail.y)
draw(screen, " ")

fmt.Fprintf(os.Stderr, "snake else: %v\n", g.snake)
moveCursor(screen, g.snake.body[0].x, g.snake.body[0].y)
draw(screen, snakeSprite)
}

fmt.Fprintf(os.Stderr, "snake after: %v\n", g.snake)

if g.snake.hitWall(maxX, maxY) || g.snake.ateItself() {
g.over()
}

render()
}

func (g *game) draw() {
maxX, maxY := getSize()
g.snake.teleport(maxX, maxY)
g.food = teleport(g.x, g.y, maxX, maxY, g.food)
g.x = maxX
g.y = maxY
// food
moveCursor(screen, g.food.x, g.food.y)
draw(screen, foodSprite)

// snake
for _, pos := range g.snake.body {
moveCursor(screen, pos.x, pos.y)
draw(screen, snakeSprite)
}

render()
}
10 changes: 10 additions & 0 deletions 26-tui/05-snake-GAME/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/pskp-95/snake-game

go 1.25.4

require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-tty v0.0.7 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/term v0.40.0 // indirect
)
9 changes: 9 additions & 0 deletions 26-tui/05-snake-GAME/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-tty v0.0.7 h1:KJ486B6qI8+wBO7kQxYgmmEFDaFEE96JMBQ7h400N8Q=
github.com/mattn/go-tty v0.0.7/go.mod h1:f2i5ZOvXBU/tCABmLmOfzLz9azMo5wdAaElRNnJKr+k=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
110 changes: 110 additions & 0 deletions 26-tui/05-snake-GAME/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package main

import (
"bufio"
"fmt"
"io"
"math/rand"
"os"
"time"

"golang.org/x/term"
)

var screen = bufio.NewWriter(os.Stdout)
var sleepTime time.Duration = 100

func hideCursor(w io.Writer) {
fmt.Fprintf(w, "\033[?25l")
}

func showCursor(w io.Writer) {
fmt.Fprintf(w, "\033[?25h")
}

func moveCursor(w io.Writer, x, y int) {
fmt.Fprintf(w, "\033[%d;%dH", y, x)
}

func clear(w io.Writer) {
fmt.Fprintf(w, "\033[2J")
}

func draw(w io.Writer, str string) {
fmt.Fprint(w, str)
}

func render() {
screen.Flush()
}

func getSize() (int, int) {
w, h, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
panic(err)
}

return w, h
}

func sameSpot(a, b position) bool {
return a.x == b.x && a.y == b.y
}

func randomPosition() position {
width, height := getSize()
x := rand.Intn(width-2) + 2
y := rand.Intn(height-2) + 2

return position{x: x, y: y}
}

func drawBox(maxX, maxY int) {
for i := 1; i <= maxX; i++ {
moveCursor(screen, i, 1)
draw(screen, "─")

moveCursor(screen, i, maxY)
draw(screen, "─")
}

for i := 1; i <= maxY; i++ {
moveCursor(screen, 1, i)
draw(screen, "│")

moveCursor(screen, maxX, i)
draw(screen, "│")
}
moveCursor(screen, 1, 1)
draw(screen, "┌")
moveCursor(screen, 1, maxY)
draw(screen, "└")
moveCursor(screen, maxX, 1)
draw(screen, "┐")
moveCursor(screen, maxX, maxY)
draw(screen, "┘")
}

func increaseSpeed() {
sleepTime -= 10
if sleepTime < 30 {
sleepTime = 30
}
}

func decreaseSpeed() {
sleepTime += 10
if sleepTime > 200 {
sleepTime = 200
}
}

func teleport(w1, h1, w2, h2 int, pos position) position {
np := position{
x: 1 + ((pos.x * w2) / w1),
y: 1 + ((pos.y * h2) / h1),
}

fmt.Fprintf(os.Stderr, "w1: %d, h1: %d, w2: %d, h2: %d, pos: %v, np: %v\n", w1, h1, w2, h2, pos, np)
return np
}
Loading