- commit
- 2badc47c5b27b61a1978885d84508f33a9ad06df
- parent
- 64cd54b239ed7a90aa04a398eadb015ce10b7fbb
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2024-09-20 20:41
generate random map
Diffstat
| M | laneya.go | 63 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- |
1 files changed, 58 insertions, 5 deletions
diff --git a/laneya.go b/laneya.go
@@ -6,6 +6,7 @@ import ( 6 6 "flag" 7 7 "fmt" 8 8 "log" -1 9 "math/rand" 9 10 "net" 10 11 "net/http" 11 12 "os" @@ -70,6 +71,51 @@ type Game struct { 70 71 var mux = &sync.RWMutex{} 71 72 var games = make(map[string]*Game) 72 73 -1 74 func makeRect(x1 int, y1 int, x2 int, y2 int) Rect { -1 75 if x1 > x2 { -1 76 x1, x2 = x2, x1 -1 77 } -1 78 if y1 > y2 { -1 79 y1, y2 = y2, y1 -1 80 } -1 81 return Rect{x1, y1, x2, y2} -1 82 } -1 83 -1 84 func randomRect(n int) Rect { -1 85 x1 := rand.Intn(2*n) - n -1 86 x2 := rand.Intn(2*n) - n -1 87 y1 := rand.Intn(2*n) - n -1 88 y2 := rand.Intn(2*n) - n -1 89 return makeRect(x1, y1, x2, y2) -1 90 } -1 91 -1 92 func (game *Game) generateMap() { -1 93 prev := Rect{-5, -5, 5, 5} -1 94 -1 95 game.Rects = []Rect{prev} -1 96 lines := []Rect{} -1 97 -1 98 for i := 1; i <= 12; i++ { -1 99 rect := randomRect(50) -1 100 if rect.Area() < 250 { -1 101 game.Rects = append(game.Rects, rect) -1 102 -1 103 p1 := prev.Center() -1 104 p2 := rect.Center() -1 105 -1 106 lines = append(lines, makeRect(p1.X, p1.Y, p2.X, p1.Y)) -1 107 lines = append(lines, makeRect(p2.X, p1.Y, p2.X, p2.Y)) -1 108 -1 109 prev = rect -1 110 } -1 111 } -1 112 -1 113 -1 114 for _, line := range lines { -1 115 game.Rects = append(game.Rects, line) -1 116 } -1 117 } -1 118 73 119 func getGame(id string) *Game { 74 120 mux.RLock() 75 121 game, ok := games[id] @@ -83,12 +129,8 @@ func getGame(id string) *Game { 83 129 register: make(chan *Player), 84 130 unregister: make(chan *Player), 85 131 lastId: 0,86 -1 Rects: []Rect{87 -1 Rect{-10, -10, 10, 10},88 -1 Rect{-19, 0, -9, 0},89 -1 Rect{-19, 0, -19, 10},90 -1 },91 132 } -1 133 game.generateMap() 92 134 mux.Lock() 93 135 games[id] = game 94 136 mux.Unlock() @@ -103,6 +145,17 @@ func (rect *Rect) Contains(x int, y int) bool { 103 145 return x >= rect.X1 && x <= rect.X2 && y >= rect.Y1 && y <= rect.Y2 104 146 } 105 147 -1 148 func (rect *Rect) Area() int { -1 149 return (rect.X2 - rect.X1) * (rect.Y2 - rect.Y1) -1 150 } -1 151 -1 152 func (rect *Rect) Center() Point { -1 153 return Point{ -1 154 (rect.X2 + rect.X1) / 2, -1 155 (rect.Y2 + rect.Y1) / 2, -1 156 } -1 157 } -1 158 106 159 func (game *Game) broadcast(msgs []Message) { 107 160 for player, _ := range game.Players { 108 161 player.Send <- msgs