snakesimulator.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. s.snake.Feed(newHead)
  166. s.field.GenerateNextFood()
  167. s.fieldUpdateQueue <- true
  168. } else if newHead.X >= s.field.Width || newHead.Y >= s.field.Height || newHead.X < 0 || newHead.Y < 0 {
  169. // fmt.Printf("Game over\n")
  170. // time.Sleep(1000 * time.Millisecond)
  171. break
  172. } else {
  173. s.snake.Move(newHead)
  174. }
  175. if s.speed > 0 {
  176. time.Sleep(100 / time.Duration(s.speed) * time.Millisecond)
  177. }
  178. s.stats.Move++
  179. }
  180. }
  181. func (s *SnakeSimulator) GetHeadState() []float64 {
  182. headX := float64(s.snake.Points[0].X)
  183. headY := float64(s.snake.Points[0].Y)
  184. tailX := float64(s.snake.Points[len(s.snake.Points)-1].X)
  185. tailY := float64(s.snake.Points[len(s.snake.Points)-1].Y)
  186. // prevX := float64(s.snake.Points[1].X)
  187. // prevY := float64(s.snake.Points[1].Y)
  188. foodX := float64(s.field.Food.X)
  189. foodY := float64(s.field.Food.Y)
  190. width := float64(s.field.Width)
  191. height := float64(s.field.Height)
  192. diag := float64(width) * math.Sqrt2
  193. lWall := headX
  194. rWall := (width - headX)
  195. tWall := headY
  196. bWall := (height - headY)
  197. lFood := float64(width)
  198. rFood := float64(width)
  199. tFood := float64(height)
  200. bFood := float64(height)
  201. if headX == foodX {
  202. tFood = headY - foodY
  203. if tFood < 0 {
  204. tFood = height
  205. } else {
  206. tFood = 0
  207. }
  208. bFood = foodY - headY
  209. if bFood < 0 {
  210. bFood = height
  211. } else {
  212. bFood = 0
  213. }
  214. }
  215. if headY == foodY {
  216. rFood = foodX - headX
  217. if rFood < 0 {
  218. rFood = width
  219. } else {
  220. rFood = 0
  221. }
  222. lFood = headX - foodX
  223. if lFood < 0 {
  224. lFood = width
  225. } else {
  226. lFood = 0
  227. }
  228. }
  229. tlFood := float64(diag)
  230. trFood := float64(diag)
  231. blFood := float64(diag)
  232. brFood := float64(diag)
  233. if math.Abs(foodY-headY) == math.Abs(foodX-headX) {
  234. if foodX > headX {
  235. if foodY > headY {
  236. trFood = 0 //math.Abs(foodX-headX) * math.Sqrt2
  237. } else {
  238. brFood = 0 //math.Abs(foodX-headX) * math.Sqrt2
  239. }
  240. } else {
  241. if foodY > headY {
  242. tlFood = 0 //math.Abs(foodX-headX) * math.Sqrt2
  243. } else {
  244. blFood = 0 //math.Abs(foodX-headX) * math.Sqrt2
  245. }
  246. }
  247. }
  248. tlWall := float64(0)
  249. trWall := float64(0)
  250. blWall := float64(0)
  251. brWall := float64(0)
  252. if lWall > tWall {
  253. tlWall = float64(tWall) * math.Sqrt2
  254. } else {
  255. tlWall = float64(lWall) * math.Sqrt2
  256. }
  257. if rWall > tWall {
  258. trWall = float64(tWall) * math.Sqrt2
  259. } else {
  260. trWall = float64(rWall) * math.Sqrt2
  261. }
  262. if lWall > bWall {
  263. blWall = float64(bWall) * math.Sqrt2
  264. } else {
  265. blWall = float64(lWall) * math.Sqrt2
  266. }
  267. if rWall > bWall {
  268. blWall = float64(bWall) * math.Sqrt2
  269. } else {
  270. brWall = float64(rWall) * math.Sqrt2
  271. }
  272. if lWall > tWall {
  273. tlWall = float64(tWall) * math.Sqrt2
  274. } else {
  275. tlWall = float64(lWall) * math.Sqrt2
  276. }
  277. if rWall > tWall {
  278. trWall = float64(tWall) * math.Sqrt2
  279. } else {
  280. trWall = float64(rWall) * math.Sqrt2
  281. }
  282. if lWall > bWall {
  283. blWall = float64(bWall) * math.Sqrt2
  284. } else {
  285. blWall = float64(lWall) * math.Sqrt2
  286. }
  287. if rWall > bWall {
  288. blWall = float64(bWall) * math.Sqrt2
  289. } else {
  290. brWall = float64(rWall) * math.Sqrt2
  291. }
  292. tTail := float64(0)
  293. bTail := float64(0)
  294. if headX == tailX {
  295. tTail = (headY - tailY)
  296. if tTail < 0 {
  297. tTail = height
  298. } else {
  299. tTail = 0
  300. }
  301. bTail = (tailY - headY)
  302. if bTail < 0 {
  303. bTail = height
  304. } else {
  305. bTail = 0
  306. }
  307. }
  308. lTail := float64(0)
  309. rTail := float64(0)
  310. if headY == tailY {
  311. lTail = (headX - tailX)
  312. if lTail < 0 {
  313. tTail = width
  314. } else {
  315. tTail = 0
  316. }
  317. rTail = (tailX - headX)
  318. if lTail < 0 {
  319. tTail = width
  320. } else {
  321. tTail = 0
  322. }
  323. }
  324. tlTail := float64(0)
  325. trTail := float64(0)
  326. blTail := float64(0)
  327. brTail := float64(0)
  328. if math.Abs(headY-tailY) == math.Abs(headX-tailX) {
  329. if tailY > headY {
  330. if tailX > headX {
  331. trTail = diag //math.Abs(tailX-headX) * math.Sqrt2
  332. } else {
  333. tlTail = diag //math.Abs(tailX-headX) * math.Sqrt2
  334. }
  335. } else {
  336. if tailX > headX {
  337. brTail = diag //math.Abs(tailX-headX) * math.Sqrt2
  338. } else {
  339. blTail = diag //math.Abs(tailX-headX) * math.Sqrt2
  340. }
  341. }
  342. }
  343. return []float64{
  344. lWall / width,
  345. rWall / width,
  346. tWall / height,
  347. bWall / height,
  348. (1.0 - lFood/width),
  349. (1.0 - rFood/width),
  350. (1.0 - tFood/height),
  351. (1.0 - bFood/height),
  352. tlWall / diag,
  353. trWall / diag,
  354. blWall / diag,
  355. brWall / diag,
  356. (1.0 - tlFood/diag),
  357. (1.0 - trFood/diag),
  358. (1.0 - blFood/diag),
  359. (1.0 - brFood/diag),
  360. tTail / height,
  361. bTail / height,
  362. lTail / width,
  363. rTail / width,
  364. tlTail / diag,
  365. trTail / diag,
  366. blTail / diag,
  367. brTail / diag,
  368. }
  369. }
  370. func (s *SnakeSimulator) StartServer() {
  371. go func() {
  372. grpcServer := grpc.NewServer()
  373. RegisterSnakeSimulatorServer(grpcServer, s)
  374. lis, err := net.Listen("tcp", "localhost:65002")
  375. if err != nil {
  376. fmt.Printf("Failed to listen: %v\n", err)
  377. }
  378. fmt.Printf("Listen SnakeSimulator localhost:65002\n")
  379. if err := grpcServer.Serve(lis); err != nil {
  380. fmt.Printf("Failed to serve: %v\n", err)
  381. }
  382. }()
  383. }
  384. // func (s *SnakeSimulator) Run() {
  385. // s.field.GenerateNextFood()
  386. // for true {
  387. // direction := rand.Int31()%4 + 1
  388. // newHead := s.snake.NewHead(Direction(direction))
  389. // if newHead.X == s.field.Food.X && newHead.Y == s.field.Food.Y {
  390. // s.snake.Feed(newHead)
  391. // s.field.GenerateNextFood()
  392. // } else if newHead.X > s.field.Width || newHead.Y > s.field.Height {
  393. // fmt.Printf("Game over\n")
  394. // break
  395. // } else if selfCollisionIndex := s.snake.SelfCollision(newHead); selfCollisionIndex > 0 {
  396. // if selfCollisionIndex == 1 {
  397. // fmt.Printf("Step backward, skip\n")
  398. // continue
  399. // }
  400. // fmt.Printf("Game over self collision\n")
  401. // break
  402. // } else {
  403. // s.snake.Move(newHead)
  404. // }
  405. // s.snakeUpdateQueue <- true
  406. // time.Sleep(50 * time.Millisecond)
  407. // }
  408. // }
  409. func (s *SnakeSimulator) Field(_ *None, srv SnakeSimulator_FieldServer) error {
  410. ctx := srv.Context()
  411. for {
  412. select {
  413. case <-ctx.Done():
  414. return ctx.Err()
  415. default:
  416. }
  417. srv.Send(s.field)
  418. <-s.fieldUpdateQueue
  419. }
  420. }
  421. func (s *SnakeSimulator) Snake(_ *None, srv SnakeSimulator_SnakeServer) error {
  422. ctx := srv.Context()
  423. for {
  424. select {
  425. case <-ctx.Done():
  426. return ctx.Err()
  427. default:
  428. }
  429. srv.Send(s.snake)
  430. <-s.snakeUpdateQueue
  431. }
  432. }
  433. func (s *SnakeSimulator) Stats(_ *None, srv SnakeSimulator_StatsServer) error {
  434. ctx := srv.Context()
  435. for {
  436. select {
  437. case <-ctx.Done():
  438. return ctx.Err()
  439. default:
  440. }
  441. srv.Send(s.stats)
  442. <-s.statsUpdateQueue
  443. }
  444. }
  445. func (s *SnakeSimulator) SetSpeed(ctx context.Context, speed *Speed) (*None, error) {
  446. s.speedQueue <- speed.Speed
  447. return &None{}, nil
  448. }