snakesimulator.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. package snakesimulator
  2. import (
  3. context "context"
  4. fmt "fmt"
  5. math "math"
  6. "math/rand"
  7. "net"
  8. "sort"
  9. "time"
  10. "gonum.org/v1/gonum/mat"
  11. genetic "../genetic"
  12. neuralnetwork "../neuralnetwork"
  13. grpc "google.golang.org/grpc"
  14. )
  15. type SnakeSimulator struct {
  16. field *Field
  17. snake *Snake
  18. stats *Stats
  19. speed uint32
  20. fieldUpdateQueue chan bool
  21. snakeUpdateQueue chan bool
  22. statsUpdateQueue chan bool
  23. speedQueue chan uint32
  24. }
  25. func NewSnakeSimulator() (s *SnakeSimulator) {
  26. s = &SnakeSimulator{
  27. field: &Field{
  28. Food: &Point{},
  29. Width: 40,
  30. Height: 40,
  31. },
  32. snake: &Snake{
  33. Points: []*Point{
  34. &Point{X: 20, Y: 20},
  35. &Point{X: 21, Y: 20},
  36. &Point{X: 22, Y: 20},
  37. },
  38. },
  39. stats: &Stats{},
  40. fieldUpdateQueue: make(chan bool, 2),
  41. snakeUpdateQueue: make(chan bool, 2),
  42. statsUpdateQueue: make(chan bool, 2),
  43. speedQueue: make(chan uint32, 1),
  44. speed: 10,
  45. }
  46. return
  47. }
  48. func (s *SnakeSimulator) Verify(population *genetic.Population) (fitnesses []*genetic.IndividalFitness) {
  49. s.stats.Generation++
  50. s.statsUpdateQueue <- true
  51. s.field.GenerateNextFood()
  52. fitnesses = make([]*genetic.IndividalFitness, len(population.Networks))
  53. for index, inidividual := range population.Networks {
  54. s.stats.Individual = uint32(index)
  55. s.statsUpdateQueue <- true
  56. s.runSnake(inidividual, false)
  57. fitnesses[index] = &genetic.IndividalFitness{
  58. // Fitness: float64(len(s.snake.Points)-2) * float64(s.stats.Move),
  59. Fitness: float64(s.stats.Move),
  60. Index: index,
  61. }
  62. }
  63. //This is duplication of crossbreedPopulation functionality.
  64. sort.Slice(fitnesses, func(i, j int) bool {
  65. return fitnesses[i].Fitness > fitnesses[j].Fitness //Descent order best will be on top, worst in the bottom
  66. })
  67. //Best snake showtime!
  68. prevSpeed := s.speed
  69. s.speed = 2
  70. s.runSnake(population.Networks[fitnesses[0].Index], false)
  71. s.speed = prevSpeed
  72. return
  73. }
  74. func (s *SnakeSimulator) runSnake(inidividual *neuralnetwork.NeuralNetwork, randomStart bool) {
  75. if randomStart {
  76. rand.Seed(time.Now().UnixNano())
  77. switch rand.Uint32() % 4 {
  78. case 1:
  79. s.snake = &Snake{
  80. Points: []*Point{
  81. &Point{X: 20, Y: 20},
  82. &Point{X: 21, Y: 20},
  83. &Point{X: 22, Y: 20},
  84. },
  85. }
  86. case 2:
  87. s.snake = &Snake{
  88. Points: []*Point{
  89. &Point{X: 22, Y: 20},
  90. &Point{X: 21, Y: 20},
  91. &Point{X: 20, Y: 20},
  92. },
  93. }
  94. case 3:
  95. s.snake = &Snake{
  96. Points: []*Point{
  97. &Point{X: 20, Y: 20},
  98. &Point{X: 20, Y: 21},
  99. &Point{X: 20, Y: 22},
  100. },
  101. }
  102. default:
  103. s.snake = &Snake{
  104. Points: []*Point{
  105. &Point{X: 20, Y: 22},
  106. &Point{X: 20, Y: 21},
  107. &Point{X: 20, Y: 20},
  108. },
  109. }
  110. }
  111. } else {
  112. s.snake = &Snake{
  113. Points: []*Point{
  114. &Point{X: 19, Y: 20},
  115. &Point{X: 20, Y: 20},
  116. &Point{X: 21, Y: 20},
  117. },
  118. }
  119. }
  120. i := 0
  121. s.stats.Move = 0
  122. for i < 300 {
  123. if s.speed > 0 {
  124. s.statsUpdateQueue <- true
  125. }
  126. //Read speed from client
  127. select {
  128. case newSpeed := <-s.speedQueue:
  129. fmt.Printf("Apply new speed: %v\n", newSpeed)
  130. if newSpeed < 10 {
  131. if newSpeed > 0 {
  132. s.speed = newSpeed
  133. } else {
  134. s.speed = 0
  135. }
  136. }
  137. default:
  138. }
  139. i++
  140. if s.speed > 0 {
  141. s.snakeUpdateQueue <- true
  142. }
  143. direction, _ := inidividual.Predict(mat.NewDense(inidividual.Sizes[0], 1, s.GetHeadState()))
  144. newHead := s.snake.NewHead(Direction(direction + 1))
  145. if selfCollisionIndex := s.snake.SelfCollision(newHead); selfCollisionIndex > 0 {
  146. if selfCollisionIndex == 1 {
  147. // switch Direction(direction + 1) {
  148. // case Direction_Up:
  149. // newHead = s.snake.NewHead(Direction_Down)
  150. // case Direction_Down:
  151. // newHead = s.snake.NewHead(Direction_Up)
  152. // case Direction_Left:
  153. // newHead = s.snake.NewHead(Direction_Right)
  154. // default:
  155. // newHead = s.snake.NewHead(Direction_Left)
  156. // }
  157. continue
  158. } else {
  159. fmt.Printf("Game over self collision\n")
  160. break
  161. }
  162. }
  163. if newHead.X == s.field.Food.X && newHead.Y == s.field.Food.Y {
  164. s.snake.Feed(newHead)
  165. s.field.GenerateNextFood()
  166. if s.speed > 0 {
  167. s.fieldUpdateQueue <- true
  168. }
  169. } else if newHead.X >= s.field.Width || newHead.Y >= s.field.Height {
  170. // fmt.Printf("Game over\n")
  171. // time.Sleep(1000 * time.Millisecond)
  172. break
  173. } else {
  174. s.snake.Move(newHead)
  175. }
  176. if s.speed > 0 {
  177. time.Sleep(100 / time.Duration(s.speed) * time.Millisecond)
  178. }
  179. s.stats.Move++
  180. }
  181. }
  182. func (s *SnakeSimulator) GetHeadState() []float64 {
  183. headX := float64(s.snake.Points[0].X)
  184. headY := float64(s.snake.Points[0].Y)
  185. tailX := float64(s.snake.Points[len(s.snake.Points)-1].X)
  186. tailY := float64(s.snake.Points[len(s.snake.Points)-1].Y)
  187. // prevX := float64(s.snake.Points[1].X)
  188. // prevY := float64(s.snake.Points[1].Y)
  189. foodX := float64(s.field.Food.X)
  190. foodY := float64(s.field.Food.Y)
  191. width := float64(s.field.Width)
  192. height := float64(s.field.Height)
  193. diag := float64(width) * math.Sqrt2
  194. lWall := headX
  195. rWall := (width - headX)
  196. tWall := headY
  197. bWall := (height - headY)
  198. lFood := float64(width)
  199. rFood := float64(width)
  200. tFood := float64(height)
  201. bFood := float64(height)
  202. if headX == foodX {
  203. tFood = headY - foodY
  204. if tFood < 0 {
  205. tFood = height
  206. }
  207. bFood = foodY - headY
  208. if bFood < 0 {
  209. bFood = height
  210. }
  211. }
  212. if headY == foodY {
  213. rFood = foodX - headX
  214. if rFood < 0 {
  215. rFood = width
  216. }
  217. lFood = headX - foodX
  218. if lFood < 0 {
  219. lFood = width
  220. }
  221. }
  222. tlFood := float64(diag)
  223. trFood := float64(diag)
  224. blFood := float64(diag)
  225. brFood := float64(diag)
  226. if math.Abs(foodY-headY) == math.Abs(foodX-headX) {
  227. if foodX > headX {
  228. if foodY > headY {
  229. trFood = math.Abs(foodX-headX) * math.Sqrt2
  230. } else {
  231. brFood = math.Abs(foodX-headX) * math.Sqrt2
  232. }
  233. } else {
  234. if foodY > headY {
  235. tlFood = math.Abs(foodX-headX) * math.Sqrt2
  236. } else {
  237. blFood = math.Abs(foodX-headX) * math.Sqrt2
  238. }
  239. }
  240. }
  241. tlWall := float64(0)
  242. trWall := float64(0)
  243. blWall := float64(0)
  244. brWall := float64(0)
  245. if lWall > tWall {
  246. tlWall = float64(tWall) * math.Sqrt2
  247. } else {
  248. tlWall = float64(lWall) * math.Sqrt2
  249. }
  250. if rWall > tWall {
  251. trWall = float64(tWall) * math.Sqrt2
  252. } else {
  253. trWall = float64(rWall) * math.Sqrt2
  254. }
  255. if lWall > bWall {
  256. blWall = float64(bWall) * math.Sqrt2
  257. } else {
  258. blWall = float64(lWall) * math.Sqrt2
  259. }
  260. if rWall > bWall {
  261. blWall = float64(bWall) * math.Sqrt2
  262. } else {
  263. brWall = float64(rWall) * math.Sqrt2
  264. }
  265. if lWall > tWall {
  266. tlWall = float64(tWall) * math.Sqrt2
  267. } else {
  268. tlWall = float64(lWall) * math.Sqrt2
  269. }
  270. if rWall > tWall {
  271. trWall = float64(tWall) * math.Sqrt2
  272. } else {
  273. trWall = float64(rWall) * math.Sqrt2
  274. }
  275. if lWall > bWall {
  276. blWall = float64(bWall) * math.Sqrt2
  277. } else {
  278. blWall = float64(lWall) * math.Sqrt2
  279. }
  280. if rWall > bWall {
  281. blWall = float64(bWall) * math.Sqrt2
  282. } else {
  283. brWall = float64(rWall) * math.Sqrt2
  284. }
  285. tTail := (headY - tailY)
  286. if tTail < 0 {
  287. tTail = height
  288. }
  289. bTail := (tailY - headY)
  290. if bTail < 0 {
  291. bTail = height
  292. }
  293. lTail := (headX - tailX)
  294. if lTail < 0 {
  295. tTail = width
  296. }
  297. rTail := (tailX - headX)
  298. if lTail < 0 {
  299. tTail = width
  300. }
  301. tlTail := float64(diag)
  302. trTail := float64(diag)
  303. blTail := float64(diag)
  304. brTail := float64(diag)
  305. if math.Abs(headY-tailY) == math.Abs(headX-tailX) {
  306. if tailY > headY {
  307. if tailX > headX {
  308. trTail = math.Abs(tailX-headX) * math.Sqrt2
  309. } else {
  310. tlTail = math.Abs(tailX-headX) * math.Sqrt2
  311. }
  312. } else {
  313. if tailX > headX {
  314. brTail = math.Abs(tailX-headX) * math.Sqrt2
  315. } else {
  316. blTail = math.Abs(tailX-headX) * math.Sqrt2
  317. }
  318. }
  319. }
  320. return []float64{
  321. lWall / width,
  322. rWall / width,
  323. tWall / height,
  324. bWall / height,
  325. (1.0 - lFood/width),
  326. (1.0 - rFood/width),
  327. (1.0 - tFood/height),
  328. (1.0 - bFood/height),
  329. tlWall / diag,
  330. trWall / diag,
  331. blWall / diag,
  332. brWall / diag,
  333. (1.0 - tlFood/diag),
  334. (1.0 - trFood/diag),
  335. (1.0 - blFood/diag),
  336. (1.0 - brFood/diag),
  337. tTail / height,
  338. bTail / height,
  339. lTail / width,
  340. rTail / width,
  341. tlTail / diag,
  342. trTail / diag,
  343. blTail / diag,
  344. brTail / diag,
  345. }
  346. }
  347. func (s *SnakeSimulator) StartServer() {
  348. go func() {
  349. grpcServer := grpc.NewServer()
  350. RegisterSnakeSimulatorServer(grpcServer, s)
  351. lis, err := net.Listen("tcp", "localhost:65002")
  352. if err != nil {
  353. fmt.Printf("Failed to listen: %v\n", err)
  354. }
  355. fmt.Printf("Listen SnakeSimulator localhost:65002\n")
  356. if err := grpcServer.Serve(lis); err != nil {
  357. fmt.Printf("Failed to serve: %v\n", err)
  358. }
  359. }()
  360. }
  361. func (s *SnakeSimulator) Run() {
  362. s.field.GenerateNextFood()
  363. for true {
  364. direction := rand.Int31()%4 + 1
  365. newHead := s.snake.NewHead(Direction(direction))
  366. if newHead.X == s.field.Food.X && newHead.Y == s.field.Food.Y {
  367. s.snake.Feed(newHead)
  368. s.field.GenerateNextFood()
  369. s.fieldUpdateQueue <- true
  370. } else if newHead.X > s.field.Width || newHead.Y > s.field.Height {
  371. fmt.Printf("Game over\n")
  372. break
  373. } else if selfCollisionIndex := s.snake.SelfCollision(newHead); selfCollisionIndex > 0 {
  374. if selfCollisionIndex == 1 {
  375. fmt.Printf("Step backward, skip\n")
  376. continue
  377. }
  378. fmt.Printf("Game over self collision\n")
  379. break
  380. } else {
  381. s.snake.Move(newHead)
  382. }
  383. s.snakeUpdateQueue <- true
  384. time.Sleep(50 * time.Millisecond)
  385. }
  386. }
  387. func (s *SnakeSimulator) Field(_ *None, srv SnakeSimulator_FieldServer) error {
  388. ctx := srv.Context()
  389. for {
  390. select {
  391. case <-ctx.Done():
  392. return ctx.Err()
  393. default:
  394. }
  395. srv.Send(s.field)
  396. <-s.fieldUpdateQueue
  397. }
  398. }
  399. func (s *SnakeSimulator) Snake(_ *None, srv SnakeSimulator_SnakeServer) error {
  400. ctx := srv.Context()
  401. for {
  402. select {
  403. case <-ctx.Done():
  404. return ctx.Err()
  405. default:
  406. }
  407. srv.Send(s.snake)
  408. <-s.snakeUpdateQueue
  409. }
  410. }
  411. func (s *SnakeSimulator) Stats(_ *None, srv SnakeSimulator_StatsServer) error {
  412. ctx := srv.Context()
  413. for {
  414. select {
  415. case <-ctx.Done():
  416. return ctx.Err()
  417. default:
  418. }
  419. srv.Send(s.stats)
  420. <-s.statsUpdateQueue
  421. }
  422. }
  423. func (s *SnakeSimulator) SetSpeed(ctx context.Context, speed *Speed) (*None, error) {
  424. s.speedQueue <- speed.Speed
  425. return &None{}, nil
  426. }