github.com/korsakjakub/snk@v0.0.0-20230625212658-1d6c119c67ee/screen.go (about) 1 package main 2 3 import "fmt" 4 5 type screen struct { 6 s [][]rune 7 width int 8 height int 9 } 10 11 func (s *screen) clear() *screen { 12 grid := make([][]rune, s.width) 13 for i := 0; i < s.width; i++ { 14 grid[i] = make([]rune, s.height) 15 } 16 s.s = grid 17 for i := 0; i < s.height; i += 1 { 18 for j := 0; j < s.width; j += 1 { 19 s.s[i][j] = '.' 20 } 21 } 22 return s 23 } 24 25 func (s *screen) drawScreen(snake actor, fruit actor) *screen { 26 s.clear() 27 for _, e := range snake.s { 28 s.s[e.y][e.x] = snake.r 29 } 30 for _, e := range fruit.s { 31 s.s[e.y][e.x] = fruit.r 32 } 33 return s 34 } 35 36 func (s *screen) String() string { 37 str := "" 38 for _, e := range s.s { 39 for _, f := range e { 40 str += fmt.Sprintf("%c ", f) 41 } 42 str += fmt.Sprintf("\n") 43 } 44 return str 45 } 46 47 type coord struct { 48 x int 49 y int 50 } 51 52 func (s shape) moduloAdd(direction coord) shape { 53 x := (s[len(s)-1].x + direction.x) % conf.Width 54 if x < 0 { 55 x += conf.Width 56 } 57 y := (s[len(s)-1].y + direction.y) % conf.Height 58 if y < 0 { 59 y += conf.Height 60 } 61 return append(s, coord{x: x, y: y}) 62 } 63 64 type shape []coord