github.com/korsakjakub/snk@v0.0.0-20230625212658-1d6c119c67ee/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "unicode/utf8" 8 ) 9 10 var conf Config 11 12 func main() { 13 14 conf = loadConfig("..") 15 snake := actor{s: shape{{x: 0, y: 0}, {x: 1, y: 0}, {x: 2, y: 0}}, r: '#'} 16 fruit := actor{s: shape{{x: 0, y: 1}}, r: '*'} 17 if conf.Width*conf.Height == 0 { 18 return 19 } 20 s := screen{ 21 s: nil, 22 width: conf.Width, 23 height: conf.Height, 24 } 25 _ = s.drawScreen(snake, fruit) 26 points := 0 27 game := game{snake: snake, fruit: fruit, screen: s, points: points} 28 move := zero 29 30 for { 31 fmt.Printf("Points: %d\n\n", game.points) 32 fmt.Print(game.drawScreen()) 33 input := getChar() 34 switch input { 35 case 'w': 36 move = up 37 case 's': 38 move = down 39 case 'd': 40 move = right 41 case 'a': 42 move = left 43 } 44 game = game.move(move) 45 clearCommand() 46 } 47 } 48 49 func getChar() rune { 50 // disable input buffering 51 err := exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run() 52 if err != nil { 53 return 0 54 } 55 // do not display entered characters on the screen 56 err = exec.Command("stty", "-F", "/dev/tty", "-echo").Run() 57 if err != nil { 58 return 0 59 } 60 // restore the echoing state when exiting 61 defer func(command *exec.Cmd) { 62 err := command.Run() 63 if err != nil { 64 65 } 66 }(exec.Command("stty", "-F", "/dev/tty", "echo")) 67 68 b := make([]byte, 1) 69 _, err = os.Stdin.Read(b) 70 if err != nil { 71 return 0 72 } 73 r, _ := utf8.DecodeRune(b) 74 return r 75 } 76 func clearCommand() { 77 cmd := exec.Command("clear") 78 cmd.Stdout = os.Stdout 79 err := cmd.Run() 80 if err != nil { 81 return 82 } 83 }