main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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/board/" + strconv.FormatInt(gameId, 10) + "?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)-1
  182. if bs.Finish.Y < viewPort.y {
  183. //iglo ten noorden van viewport
  184. fmt.Println("iglo Y boven")
  185. igloY = 0
  186. /*for viewPort.Get(viewPort.x+viewPortWidth, igloY) == board.Rock && igloY <= viewPort.y+viewPortHeight {
  187. igloY++
  188. }*/
  189. } else if bs.Finish.Y > viewPort.y+viewPort.Board.Height {
  190. //iglo ten zuiden van viewport
  191. fmt.Println("iglo Y onder")
  192. igloY = viewPort.Board.Height - 1
  193. /*for viewPort.Get(viewPort.x+viewPortWidth, igloY) == board.Rock && igloY >= viewPort.y+viewPortHeight {
  194. igloY--
  195. }*/
  196. }
  197. igloX := viewPort.Board.Width - 1
  198. if bs.Finish.X < viewPort.x {
  199. //iglo links
  200. fmt.Println("iglo X links")
  201. igloX = 0
  202. } else if bs.Finish.X > viewPort.x+viewPort.Board.Width {
  203. //iglo rechts
  204. fmt.Println("iglo X rechts")
  205. igloX = viewPort.Board.Width - 1
  206. } else if viewPort.x < bs.Finish.X && viewPort.x+viewPort.Board.Width > bs.Finish.X {
  207. // iglo in range
  208. igloX = (bs.Finish.X - viewPort.x)
  209. }
  210. fmt.Printf("Virtuele iglo geplaast op x %v y %v\n", igloX, igloY)
  211. dist := calcDist(igloX, igloY, viewPort)
  212. for igloX > 100 && dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)] == 0 {
  213. igloX--
  214. fmt.Printf("replaced iglo to %v x %v\n", igloX, igloY)
  215. dist = calcDist(igloX, igloY, viewPort)
  216. /*
  217. for i := 0; i < viewPort.Board.Height; i++ {
  218. for j := 0; j < viewPort.Board.Width; j++ {
  219. if j == p.Pos.X-viewPort.x && i == p.Pos.Y-viewPort.y {
  220. fmt.Printf("X")
  221. }
  222. if j == igloX && i == igloY {
  223. fmt.Printf("I")
  224. }
  225. if dist[(i*viewPort.Board.Width)+j] < 10 {
  226. fmt.Printf("0")
  227. }
  228. fmt.Printf("%v ", dist[(i*viewPort.Board.Width)+j])
  229. }
  230. fmt.Printf("\n")
  231. }
  232. time.Sleep(1 * time.Second)*/
  233. }
  234. smallestDist := math.MaxInt32
  235. 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 {
  236. direction = "E"
  237. smallestDist = dist[toIndex(p.Pos.X+1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)]
  238. }
  239. 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)] {
  240. direction = "W"
  241. smallestDist = dist[toIndex(p.Pos.X-1-viewPort.x, p.Pos.Y-viewPort.y, viewPort.Board.Width)]
  242. }
  243. 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)] {
  244. direction = "S"
  245. smallestDist = dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y+1-viewPort.y, viewPort.Board.Width)]
  246. }
  247. 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)] {
  248. direction = "N"
  249. smallestDist = dist[toIndex(p.Pos.X-viewPort.x, p.Pos.Y-1-viewPort.y, viewPort.Board.Width)]
  250. }
  251. if smallestDist == math.MaxInt32 {
  252. validMoves := make([]string, 0)
  253. 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 {
  254. validMoves = append(validMoves, "E")
  255. validMoves = append(validMoves, "E")
  256. }
  257. if p.Pos.X-1-viewPort.x >= 0 && viewPort.Board.Get(p.Pos.X-1-viewPort.x, p.Pos.Y-viewPort.y) != board.Rock {
  258. validMoves = append(validMoves, "W")
  259. }
  260. 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 {
  261. validMoves = append(validMoves, "S")
  262. validMoves = append(validMoves, "S")
  263. validMoves = append(validMoves, "S")
  264. }
  265. if p.Pos.Y-1-viewPort.y >= 0 && viewPort.Board.Get(p.Pos.X-viewPort.x, p.Pos.Y-1-viewPort.y) != board.Rock {
  266. validMoves = append(validMoves, "N")
  267. validMoves = append(validMoves, "N")
  268. validMoves = append(validMoves, "N")
  269. }
  270. rInt := r.Intn(len(validMoves))
  271. direction = validMoves[rInt]
  272. }
  273. //send move
  274. url := "http://localhost:8080/games/" + strconv.FormatInt(gameId, 10) + "/move/" + p.Id + "/" + direction
  275. fmt.Println("move:>", url, smallestDist, p.Pos.X, p.Pos.Y)
  276. resp, _ := http.Post(url, "text/plain", nil)
  277. resp.Body.Close()
  278. //update x,y
  279. switch direction {
  280. case "N":
  281. p.Pos.Y--
  282. case "E":
  283. p.Pos.X++
  284. case "S":
  285. p.Pos.Y++
  286. case "W":
  287. p.Pos.X--
  288. }
  289. fmt.Printf("new pos x=%v y=%v\n", p.Pos.X, p.Pos.Y)
  290. return true
  291. }
  292. func toXy(index, boardWidth int) (x, y int) {
  293. x = index % boardWidth
  294. y = (index - x) / boardWidth
  295. return x, y
  296. }
  297. func toIndex(x, y, boardWidth int) (index int) {
  298. return y*boardWidth + x
  299. }
  300. func calcDist(igloX, igloY int, viewPort *viewport) map[int]int {
  301. distance := make(map[int]int)
  302. s := NewQueue()
  303. index := toIndex(igloX, igloY, viewPort.Board.Width)
  304. s.Push(index)
  305. distance[index] = -1
  306. for s.Len() != 0 {
  307. i := s.Poll()
  308. x, y := toXy(i, viewPort.Board.Width)
  309. if x+1 < viewPort.Board.Width {
  310. newI := toIndex(x+1, y, viewPort.Board.Width)
  311. if distance[newI] == 0 && viewPort.Board.Get(x+1, y) != board.Rock {
  312. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  313. s.Push(newI)
  314. }
  315. }
  316. if x-1 >= 0 {
  317. newI := toIndex(x-1, y, viewPort.Board.Width)
  318. if distance[newI] == 0 && viewPort.Board.Get(x-1, y) != board.Rock {
  319. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  320. s.Push(newI)
  321. }
  322. }
  323. if y+1 < viewPort.Board.Height {
  324. newI := toIndex(x, y+1, viewPort.Board.Width)
  325. if distance[newI] == 0 && viewPort.Board.Get(x, y+1) != board.Rock {
  326. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  327. s.Push(newI)
  328. }
  329. }
  330. if y-1 >= 0 {
  331. newI := toIndex(x, y-1, viewPort.Board.Width)
  332. if distance[newI] == 0 && viewPort.Board.Get(x, y-1) != board.Rock {
  333. distance[newI] = max(distance[toIndex(x, y, viewPort.Board.Width)], 0) + 1
  334. s.Push(newI)
  335. }
  336. }
  337. }
  338. return distance
  339. }
  340. /*
  341. type stack []int
  342. func (s stack) Empty() bool { return len(s) == 0 }
  343. func (s stack) Peek() int { return s[len(s)-1] }
  344. func (s *stack) Put(i int) { (*s) = append((*s), i) }
  345. func (s *stack) Pop() int {
  346. d := (*s)[len(*s)-1]
  347. (*s) = (*s)[:len(*s)-1]
  348. return d
  349. }
  350. */
  351. type queuenode struct {
  352. data int
  353. next *queuenode
  354. }
  355. // A go-routine safe FIFO (first in first out) data stucture.
  356. type Queue struct {
  357. head *queuenode
  358. tail *queuenode
  359. count int
  360. }
  361. // Creates a new pointer to a new queue.
  362. func NewQueue() *Queue {
  363. q := &Queue{}
  364. return q
  365. }
  366. // Returns the number of elements in the queue (i.e. size/length)
  367. // go-routine safe.
  368. func (q *Queue) Len() int {
  369. return q.count
  370. }
  371. // Pushes/inserts a value at the end/tail of the queue.
  372. // Note: this function does mutate the queue.
  373. // go-routine safe.
  374. func (q *Queue) Push(item int) {
  375. n := &queuenode{data: item}
  376. if q.tail == nil {
  377. q.tail = n
  378. q.head = n
  379. } else {
  380. q.tail.next = n
  381. q.tail = n
  382. }
  383. q.count++
  384. }
  385. // Returns the value at the front of the queue.
  386. // i.e. the oldest value in the queue.
  387. // Note: this function does mutate the queue.
  388. // go-routine safe.
  389. func (q *Queue) Poll() int {
  390. n := q.head
  391. q.head = n.next
  392. if q.head == nil {
  393. q.tail = nil
  394. }
  395. q.count--
  396. return n.data
  397. }
  398. // Returns a read value at the front of the queue.
  399. // i.e. the oldest value in the queue.
  400. // Note: this function does NOT mutate the queue.
  401. // go-routine safe.
  402. func (q *Queue) Peek() int {
  403. n := q.head
  404. return n.data
  405. }
  406. func playerJoin(p *player.Player) {
  407. }
  408. func initLogging() {
  409. logFile, err := os.Create("server.log")
  410. if err == nil {
  411. log.SetOutput(logFile)
  412. } else {
  413. log.Println("ERROR: Cannot open log file, using console.")
  414. log.Printf("%v=n", err)
  415. }
  416. }