snakesimulator.go 10 KB

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