main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "math"
  9. "math/rand"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "time"
  14. "battlecamp-go/board"
  15. "battlecamp-go/events"
  16. "battlecamp-go/flag"
  17. "battlecamp-go/game"
  18. "battlecamp-go/player"
  19. "battlecamp-go/stomp"
  20. )
  21. func main() {
  22. initLogging()
  23. log.Println("Game bot version 0.1")
  24. flag.ParseFlags()
  25. pu := make(chan *events.PlayerUpdate)
  26. go subscribeToUpdate(pu)
  27. for {
  28. subscribeToGame(pu)
  29. }
  30. }
  31. func subscribeToGame(pu chan *events.PlayerUpdate) {
  32. sub := stomp.Subscribe("game")
  33. gameEndChannels := make(map[int]*[]chan bool)
  34. for {
  35. announcement := <-sub
  36. gs := new(events.GameStart)
  37. json.Unmarshal(announcement.Body, &gs)
  38. fmt.Printf("announcement type: %v for game %v\n", gs.Type, strconv.FormatInt(gs.GameId, 10))
  39. if "GAME_START" == gs.Type {
  40. names := []string{"Zeus"}
  41. tmp := make([]chan bool, 0, len(names))
  42. gameEndChannels[int(gs.GameId)] = &tmp
  43. for _, name := range names {
  44. gameEndChan := make(chan bool)
  45. tmp := append(*gameEndChannels[int(gs.GameId)], gameEndChan)
  46. gameEndChannels[int(gs.GameId)] = &tmp
  47. go joinGame(gs.GameId, gameEndChan, pu, name)
  48. }
  49. } else {
  50. chans := gameEndChannels[int(gs.GameId)]
  51. for _, channel := range *chans {
  52. channel <- true
  53. }
  54. }
  55. }
  56. }
  57. func subscribeToUpdate(pu chan *events.PlayerUpdate) {
  58. sub := stomp.Subscribe("update")
  59. for {
  60. announcement := <-sub
  61. if "vnd.battlecamp.player" == announcement.ContentType {
  62. p := new(player.Player)
  63. json.Unmarshal(announcement.Body, &p)
  64. playerJoin(p)
  65. } else {
  66. pue := new(events.PlayerUpdate)
  67. json.Unmarshal(announcement.Body, &pue)
  68. pu <- pue
  69. }
  70. }
  71. }
  72. func joinGame(gameId int64, gameEndChan chan bool, pu chan *events.PlayerUpdate, name string) {
  73. //join game
  74. p := &player.Player{
  75. Id: name,
  76. Color: "#238b02",
  77. Type: 1,
  78. }
  79. players := make([]*player.Player, 5)
  80. //retrieve finish
  81. gameUrl := "http://localhost:8080/games/" + strconv.FormatInt(gameId, 10)
  82. fmt.Println("getGame:>", gameUrl)
  83. resp, _ := http.Get(gameUrl)
  84. g := new(game.Game)
  85. b, _ := ioutil.ReadAll(resp.Body)
  86. resp.Body.Close()
  87. json.Unmarshal(b, &g)
  88. boardSummery := g.Board
  89. fmt.Printf("Finish x=%v y=%v\n", boardSummery.Finish.X, boardSummery.Finish.Y)
  90. //join the game
  91. url := "http://localhost:8080/games/" + strconv.FormatInt(gameId, 10) + "/join"
  92. jsonStr, _ := json.Marshal(p)
  93. req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  94. req.Header.Set("Content-Type", "application/json")
  95. client := &http.Client{}
  96. resp, err := client.Do(req)
  97. if err != nil {
  98. panic(err)
  99. }
  100. v, _ := ioutil.ReadAll(resp.Body)
  101. json.Unmarshal(v, p) //Set my location in the player
  102. fmt.Printf("My start position x %v y %v\n", p.Pos.X, p.Pos.Y)
  103. resp.Body.Close()
  104. move(gameId, p, players, boardSummery)
  105. for {
  106. select {
  107. case <-gameEndChan:
  108. fmt.Println("Game ended returning")
  109. close(gameEndChan)
  110. return
  111. case playerUpdate := <-pu:
  112. if playerUpdate.GameId == gameId {
  113. players = playerUpdate.Players // TODO fix multi client
  114. for _, pup := range players {
  115. if pup.Id == p.Id {
  116. p.Pos.X = pup.Pos.X
  117. p.Pos.Y = pup.Pos.Y
  118. fmt.Printf("Set my position to x=%v y=%v\n", pup.Pos.X, pup.Pos.Y)
  119. time.Sleep(25 * time.Millisecond)
  120. fmt.Println("Allowed to make a new move")
  121. move(gameId, p, players, boardSummery)
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128. type viewport struct {
  129. x, y, width, height int
  130. Board *board.Board
  131. }
  132. func getViewPort(x, y, width, height int, gameId int64, bs *board.Board) *viewport {
  133. x, y, width, height = board.SanitizeViewPort(bs, x, y, width, height)
  134. url := "http://localhost:8080/games/" + strconv.FormatInt(gameId, 10) + "/board?x=" + strconv.Itoa(x) + "&y=" + strconv.Itoa(y) + "&rows=" + strconv.Itoa(height) + "&cols=" + strconv.Itoa(width)
  135. fmt.Println("getViewPort:>", url)
  136. resp, _ := http.Get(url)
  137. board := board.ReadJSON(x, y, resp.Body)
  138. resp.Body.Close()
  139. return &viewport{
  140. x: x,
  141. y: y,
  142. width: width,
  143. height: height,
  144. Board: board,
  145. }
  146. }
  147. func (v viewport) Get(x, y int) board.TileType {
  148. return v.Board.Get(x-v.x, y-v.y)
  149. }
  150. const viewPortWidth = 128
  151. const viewPortHeight = 128
  152. func max(a, b int) int {
  153. if a >= b {
  154. return a
  155. }
  156. return b
  157. }
  158. func min(a, b int) int {
  159. if a <= b {
  160. return a
  161. }
  162. return b
  163. }
  164. func move(gameId int64, p *player.Player, players []*player.Player, bs *board.Board) bool {
  165. fmt.Println("Lets move")
  166. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  167. if bs.Finish.X == p.Pos.X && p.Pos.Y == bs.Finish.Y {
  168. fmt.Println("HELP i'm finished stop me!!")
  169. return false
  170. }
  171. //determine move
  172. viewPortX := 0
  173. viewPortY := 0
  174. if viewPortHeight <= bs.Height || viewPortWidth <= bs.Width {
  175. viewPortX = p.Pos.X - viewPortWidth/2
  176. viewPortY = p.Pos.Y - viewPortHeight/2
  177. }
  178. viewPort := getViewPort(viewPortX, viewPortY, viewPortWidth, viewPortHeight, gameId, bs)
  179. //fmt.Printf("viewport x=%v y=%v width %v height %v viewport board width %v height %v\n", viewPort.x, viewPort.y, viewPort.width, viewPort.height, viewPort.Board.Width, viewPort.Board.Height)
  180. direction := "E"
  181. igloY := bs.Finish.Y - viewPort.y
  182. igloYInRange := true
  183. if bs.Finish.Y < viewPort.y {
  184. //iglo ten noorden van viewport
  185. fmt.Println("iglo Y boven")
  186. igloY = 0
  187. igloYInRange = false
  188. /*for viewPort.Get(viewPort.x+viewPortWidth, igloY) == board.Rock && igloY <= viewPort.y+viewPortHeight {
  189. igloY++
  190. }*/
  191. } else if bs.Finish.Y > viewPort.y+viewPort.Board.Height {
  192. //iglo ten zuiden van viewport
  193. fmt.Println("iglo Y onder")
  194. igloY = viewPort.Board.Height - 1
  195. igloYInRange = false
  196. /*for viewPort.Get(viewPort.x+viewPortWidth, igloY) == board.Rock && igloY >= viewPort.y+viewPortHeight {
  197. igloY--
  198. }*/
  199. }
  200. igloX := viewPort.Board.Width
  201. igloXInRange := true
  202. if bs.Finish.X < viewPort.x {
  203. //iglo links
  204. fmt.Println("iglo X links")
  205. igloX = 0
  206. igloXInRange = false
  207. } else if bs.Finish.X > viewPort.x+viewPort.Board.Width {
  208. //iglo rechts
  209. fmt.Println("iglo X rechts")
  210. igloX = viewPort.Board.Width - 1
  211. igloXInRange = false
  212. } else if viewPort.x < bs.Finish.X && viewPort.x+viewPort.Board.Width > bs.Finish.X {
  213. // iglo in range
  214. igloX = (bs.Finish.X - viewPort.x)
  215. }
  216. fmt.Printf("Virtuele iglo geplaast op x %v y %v\n", igloX, igloY)
  217. dist := calcDist(igloX, igloY, viewPort)
  218. if !igloXInRange || !igloYInRange {
  219. for igloX > 100 && dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)] == 0 {
  220. igloX--
  221. fmt.Printf("replaced iglo to %v x %v\n", igloX, igloY)
  222. dist = calcDist(igloX, igloY, viewPort)
  223. /*
  224. for i := 0; i < viewPort.Board.Height; i++ {
  225. for j := 0; j < viewPort.Board.Width; j++ {
  226. if j == p.Pos.X-viewPort.x && i == p.Pos.Y-viewPort.y {
  227. fmt.Printf("X")
  228. }
  229. if j == igloX && i == igloY {
  230. fmt.Printf("I")
  231. }
  232. if dist[(i*viewPort.Board.Width)+j] < 10 {
  233. fmt.Printf("0")
  234. }
  235. fmt.Printf("%v ", dist[(i*viewPort.Board.Width)+j])
  236. }
  237. fmt.Printf("\n")
  238. }
  239. time.Sleep(1 * time.Second)*/
  240. }
  241. } else {
  242. fmt.Println("Iglo in range lets go!!")
  243. }
  244. smallestDist := math.MaxInt32
  245. if p.Pos.X+1-viewPort.x < viewPort.width && dist[toIndex(p.Pos.X+1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)] != 0 {
  246. direction = "E"
  247. smallestDist = dist[toIndex(p.Pos.X+1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)]
  248. }
  249. if p.Pos.X-1-viewPort.x >= 0 && dist[toIndex(p.Pos.X-1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)] != 0 && smallestDist > dist[toIndex(p.Pos.X-1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)] {
  250. direction = "W"
  251. smallestDist = dist[toIndex(p.Pos.X-1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)]
  252. }
  253. if p.Pos.Y+1-viewPort.y < viewPort.height && dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y+1-viewPort.y, viewPort.Board.Width)] != 0 && smallestDist > dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y+1-viewPort.y, viewPort.Board.Width)] {
  254. direction = "S"
  255. smallestDist = dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y+1-viewPort.y, viewPort.Board.Width)]
  256. }
  257. if p.Pos.Y-1-viewPort.y >= 0 && dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y-1-viewPort.y, viewPort.Board.Width)] != 0 && smallestDist > dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y-1-viewPort.y, viewPort.Board.Width)] {
  258. direction = "N"
  259. smallestDist = dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y-1-viewPort.y, viewPort.Board.Width)]
  260. }
  261. if smallestDist == math.MaxInt32 {
  262. validMoves := make([]string, 0)
  263. if p.Pos.X+1-viewPort.x < viewPort.width && viewPort.Board.Get(p.Pos.X+1-viewPort.x, p.Pos.Y-viewPort.y) != board.Rock {
  264. validMoves = append(validMoves, "E")
  265. validMoves = append(validMoves, "E")
  266. }
  267. if p.Pos.X-1-viewPort.x >= 0 && viewPort.Board.Get(p.Pos.X-1-viewPort.x, p.Pos.Y-viewPort.y) != board.Rock {
  268. validMoves = append(validMoves, "W")
  269. }
  270. if p.Pos.Y+1-viewPort.y < viewPort.height && viewPort.Board.Get(p.Pos.X-viewPort.x, p.Pos.Y+1-viewPort.y) != board.Rock {
  271. validMoves = append(validMoves, "S")
  272. validMoves = append(validMoves, "S")
  273. validMoves = append(validMoves, "S")
  274. }
  275. if p.Pos.Y-1-viewPort.y >= 0 && viewPort.Board.Get(p.Pos.X-viewPort.x, p.Pos.Y-1-viewPort.y) != board.Rock {
  276. validMoves = append(validMoves, "N")
  277. validMoves = append(validMoves, "N")
  278. validMoves = append(validMoves, "N")
  279. }
  280. rInt := r.Intn(len(validMoves))
  281. direction = validMoves[rInt]
  282. }
  283. //send move
  284. url := "http://localhost:8080/games/" + strconv.FormatInt(gameId, 10) + "/move/" + p.Id + "/" + direction
  285. fmt.Println("move:>", url, smallestDist, p.Pos.X, p.Pos.Y)
  286. resp, _ := http.Post(url, "text/plain", nil)
  287. resp.Body.Close()
  288. //update x,y
  289. switch direction {
  290. case "N":
  291. p.Pos.Y--
  292. case "E":
  293. p.Pos.X++
  294. case "S":
  295. p.Pos.Y++
  296. case "W":
  297. p.Pos.X--
  298. }
  299. fmt.Printf("new pos x=%v y=%v\n", p.Pos.X, p.Pos.Y)
  300. return true
  301. }
  302. func toXy(index, boardWidth int) (x, y int) {
  303. x = index % boardWidth
  304. y = (index - x) / boardWidth
  305. return x, y
  306. }
  307. func toIndex(x, y, boardWidth int) (index int) {
  308. return y*boardWidth + x
  309. }
  310. func calcDist(igloX, igloY int, viewPort *viewport) map[int]int {
  311. distance := make(map[int]int)
  312. s := NewQueue()
  313. index := toIndex(igloX, igloY, viewPort.Board.Width)
  314. s.Push(index)
  315. distance[index] = -1
  316. for s.Len() != 0 {
  317. i := s.Poll()
  318. x, y := toXy(i, viewPort.Board.Width)
  319. if x+1 < viewPort.Board.Width {
  320. newI := toIndex(x+1, y, viewPort.Board.Width)
  321. if distance[newI] == 0 && viewPort.Board.Get(x+1, y) != board.Rock {
  322. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  323. s.Push(newI)
  324. }
  325. }
  326. if x-1 >= 0 {
  327. newI := toIndex(x-1, y, viewPort.Board.Width)
  328. if distance[newI] == 0 && viewPort.Board.Get(x-1, y) != board.Rock {
  329. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  330. s.Push(newI)
  331. }
  332. }
  333. if y+1 < viewPort.Board.Height {
  334. newI := toIndex(x, y+1, viewPort.Board.Width)
  335. if distance[newI] == 0 && viewPort.Board.Get(x, y+1) != board.Rock {
  336. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  337. s.Push(newI)
  338. }
  339. }
  340. if y-1 >= 0 {
  341. newI := toIndex(x, y-1, viewPort.Board.Width)
  342. if distance[newI] == 0 && viewPort.Board.Get(x, y-1) != board.Rock {
  343. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  344. s.Push(newI)
  345. }
  346. }
  347. }
  348. return distance
  349. }
  350. /*
  351. type stack []int
  352. func (s stack) Empty() bool { return len(s) == 0 }
  353. func (s stack) Peek() int { return s[len(s)-1] }
  354. func (s *stack) Put(i int) { (*s) = append((*s), i) }
  355. func (s *stack) Pop() int {
  356. d := (*s)[len(*s)-1]
  357. (*s) = (*s)[:len(*s)-1]
  358. return d
  359. }
  360. */
  361. type queuenode struct {
  362. data int
  363. next *queuenode
  364. }
  365. // A go-routine safe FIFO (first in first out) data stucture.
  366. type Queue struct {
  367. head *queuenode
  368. tail *queuenode
  369. count int
  370. }
  371. // Creates a new pointer to a new queue.
  372. func NewQueue() *Queue {
  373. q := &Queue{}
  374. return q
  375. }
  376. // Returns the number of elements in the queue (i.e. size/length)
  377. // go-routine safe.
  378. func (q *Queue) Len() int {
  379. return q.count
  380. }
  381. // Pushes/inserts a value at the end/tail of the queue.
  382. // Note: this function does mutate the queue.
  383. // go-routine safe.
  384. func (q *Queue) Push(item int) {
  385. n := &queuenode{data: item}
  386. if q.tail == nil {
  387. q.tail = n
  388. q.head = n
  389. } else {
  390. q.tail.next = n
  391. q.tail = n
  392. }
  393. q.count++
  394. }
  395. // Returns the value at the front of the queue.
  396. // i.e. the oldest value in the queue.
  397. // Note: this function does mutate the queue.
  398. // go-routine safe.
  399. func (q *Queue) Poll() int {
  400. n := q.head
  401. q.head = n.next
  402. if q.head == nil {
  403. q.tail = nil
  404. }
  405. q.count--
  406. return n.data
  407. }
  408. // Returns a read value at the front of the queue.
  409. // i.e. the oldest value in the queue.
  410. // Note: this function does NOT mutate the queue.
  411. // go-routine safe.
  412. func (q *Queue) Peek() int {
  413. n := q.head
  414. return n.data
  415. }
  416. func playerJoin(p *player.Player) {
  417. }
  418. func initLogging() {
  419. logFile, err := os.Create("server.log")
  420. if err == nil {
  421. log.SetOutput(logFile)
  422. } else {
  423. log.Println("ERROR: Cannot open log file, using console.")
  424. log.Printf("%v=n", err)
  425. }
  426. }