Skip to content

Instantly share code, notes, and snippets.

@nekename
Created July 10, 2025 12:14
Show Gist options
  • Save nekename/1f37d860c59b278d7b40dddabc238d43 to your computer and use it in GitHub Desktop.
Save nekename/1f37d860c59b278d7b40dddabc238d43 to your computer and use it in GitHub Desktop.

Revisions

  1. nekename created this gist Jul 10, 2025.
    90 changes: 90 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,90 @@
    package main

    import (
    "fmt"
    "math/rand"
    "os"
    "slices"
    "time"

    "github.com/eiannone/keyboard"
    )

    const WALL = "\u001b[45m "
    const BG = "\u001b[102m "
    const SNAKE = "\u001b[44m "
    const HEAD = "\u001b[104m "
    const APPLE = "\u001b[41m "
    const RESET = "\u001b[0m "

    const SIZE = 25

    func main() {
    keysEvents, _ := keyboard.GetKeys(16)

    snake := [][2]int{{2, SIZE / 2}, {3, SIZE / 2}, {4, SIZE / 2}}
    apple := [2]int{rand.Intn(SIZE-3) + 1, rand.Intn(SIZE-3) + 1}
    direction := [2]int{1, 0}

    for {
    for len(keysEvents) > 0 {
    switch (<-keysEvents).Key {
    case keyboard.KeyArrowUp:
    if direction[1] == 0 {
    direction = [2]int{0, -1}
    }
    case keyboard.KeyArrowDown:
    if direction[1] == 0 {
    direction = [2]int{0, 1}
    }
    case keyboard.KeyArrowLeft:
    if direction[0] == 0 {
    direction = [2]int{-1, 0}
    }
    case keyboard.KeyArrowRight:
    if direction[0] == 0 {
    direction = [2]int{1, 0}
    }
    case keyboard.KeyCtrlC:
    os.Exit(0)
    }
    }

    new := snake[len(snake)-1]
    new[0] += direction[0]
    new[1] += direction[1]

    if slices.Contains(snake, new) || new[0] == 0 || new[0] == SIZE-1 || new[1] == 0 || new[1] == SIZE-1 {
    os.Exit(0)
    }

    if new == apple {
    apple = [2]int{rand.Intn(SIZE-3) + 1, rand.Intn(SIZE-3) + 1}
    } else {
    snake = snake[1:]
    }
    snake = append(snake, new)

    for y := range SIZE {
    for x := range SIZE {
    if slices.Contains(snake, [2]int{x, y}) {
    if [2]int{x, y} == snake[len(snake)-1] {
    fmt.Print(HEAD)
    } else {
    fmt.Print(SNAKE)
    }
    } else if [2]int{x, y} == apple {
    fmt.Print(APPLE)
    } else if x == 0 || x == SIZE-1 || y == 0 || y == SIZE-1 {
    fmt.Print(WALL)
    } else {
    fmt.Print(BG)
    }
    }
    fmt.Println(RESET)
    }
    time.Sleep(time.Second / 5)
    fmt.Println("\033[H\033[2J")
    fmt.Println(len(snake) - 3)
    }
    }