123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 |
- package snakesimulator
- import (
- context "context"
- fmt "fmt"
- math "math"
- "math/rand"
- "net"
- "time"
- "gonum.org/v1/gonum/mat"
- genetic "../genetic"
- grpc "google.golang.org/grpc"
- )
- type SnakeSimulator struct {
- field *Field
- snake *Snake
- stats *Stats
- speed uint32
- fieldUpdateQueue chan bool
- snakeUpdateQueue chan bool
- statsUpdateQueue chan bool
- speedQueue chan uint32
- }
- func NewSnakeSimulator() (s *SnakeSimulator) {
- s = &SnakeSimulator{
- field: &Field{
- Food: &Point{},
- Width: 40,
- Height: 40,
- },
- snake: &Snake{
- Points: []*Point{
- &Point{X: 20, Y: 20},
- &Point{X: 21, Y: 20},
- &Point{X: 22, Y: 20},
- },
- },
- stats: &Stats{},
- fieldUpdateQueue: make(chan bool, 2),
- snakeUpdateQueue: make(chan bool, 2),
- statsUpdateQueue: make(chan bool, 2),
- speedQueue: make(chan uint32, 1),
- speed: 10,
- }
- return
- }
- func (s *SnakeSimulator) Verify(population *genetic.Population) (results []*genetic.IndividalResult) {
- s.stats.Generation++
- s.statsUpdateQueue <- true
- s.field.GenerateNextFood()
- results = make([]*genetic.IndividalResult, len(population.Networks))
- for index, inidividual := range population.Networks {
- s.stats.Individual = uint32(index)
- s.statsUpdateQueue <- true
- s.snake = &Snake{
- Points: []*Point{
- &Point{X: 19, Y: 20},
- &Point{X: 20, Y: 20},
- &Point{X: 21, Y: 20},
- },
- }
- // rand.Seed(time.Now().UnixNano())
- // switch rand.Uint32() % 4 {
- // case 1:
- // s.snake = &Snake{
- // Points: []*Point{
- // &Point{X: 20, Y: 20},
- // &Point{X: 21, Y: 20},
- // &Point{X: 22, Y: 20},
- // },
- // }
- // case 2:
- // s.snake = &Snake{
- // Points: []*Point{
- // &Point{X: 22, Y: 20},
- // &Point{X: 21, Y: 20},
- // &Point{X: 20, Y: 20},
- // },
- // }
- // case 3:
- // s.snake = &Snake{
- // Points: []*Point{
- // &Point{X: 20, Y: 20},
- // &Point{X: 20, Y: 21},
- // &Point{X: 20, Y: 22},
- // },
- // }
- // default:
- // s.snake = &Snake{
- // Points: []*Point{
- // &Point{X: 20, Y: 22},
- // &Point{X: 20, Y: 21},
- // &Point{X: 20, Y: 20},
- // },
- // }
- // }
- i := 0
- s.stats.Move = 0
- for i < 300 {
- if s.speed > 0 {
- s.statsUpdateQueue <- true
- }
- //Read speed from client
- select {
- case newSpeed := <-s.speedQueue:
- fmt.Printf("Apply new speed: %v\n", newSpeed)
- if newSpeed < 10 {
- if newSpeed > 0 {
- s.speed = newSpeed
- } else {
- s.speed = 0
- }
- }
- default:
- }
- i++
- if s.speed > 0 {
- s.snakeUpdateQueue <- true
- }
- direction, _ := inidividual.Predict(mat.NewDense(inidividual.Sizes[0], 1, s.GetHeadState()))
- newHead := s.snake.NewHead(Direction(direction + 1))
- if selfCollisionIndex := s.snake.SelfCollision(newHead); selfCollisionIndex > 0 {
- if selfCollisionIndex == 1 {
- // switch Direction(direction + 1) {
- // case Direction_Up:
- // newHead = s.snake.NewHead(Direction_Down)
- // case Direction_Down:
- // newHead = s.snake.NewHead(Direction_Up)
- // case Direction_Left:
- // newHead = s.snake.NewHead(Direction_Right)
- // default:
- // newHead = s.snake.NewHead(Direction_Left)
- // }
- continue
- } else {
- fmt.Printf("Game over self collision\n")
- break
- }
- }
- if newHead.X == s.field.Food.X && newHead.Y == s.field.Food.Y {
- s.snake.Feed(newHead)
- s.field.GenerateNextFood()
- if s.speed > 0 {
- s.fieldUpdateQueue <- true
- }
- } else if newHead.X >= s.field.Width || newHead.Y >= s.field.Height {
- // fmt.Printf("Game over\n")
- // time.Sleep(1000 * time.Millisecond)
- break
- } else {
- s.snake.Move(newHead)
- }
- if s.speed > 0 {
- time.Sleep(100 / time.Duration(s.speed) * time.Millisecond)
- }
- s.stats.Move++
- }
- results[index] = &genetic.IndividalResult{
- // Result: float64(len(s.snake.Points)-2) * float64(s.stats.Move),
- Result: float64(s.stats.Move),
- Index: index,
- }
- }
- return
- }
- func (s *SnakeSimulator) GetHeadState() []float64 {
- headX := float64(s.snake.Points[0].X)
- headY := float64(s.snake.Points[0].Y)
- // tailX := float64(s.snake.Points[len(s.snake.Points)-1].X)
- // tailY := float64(s.snake.Points[len(s.snake.Points)-1].Y)
- // prevX := float64(s.snake.Points[1].X)
- // prevY := float64(s.snake.Points[1].Y)
- foodX := float64(s.field.Food.X)
- foodY := float64(s.field.Food.Y)
- width := float64(s.field.Width)
- height := float64(s.field.Height)
- diag := float64(width) * math.Sqrt2
- // tBack := float64(0.0)
- // bBack := float64(0.0)
- // lBack := float64(0.0)
- // rBack := float64(0.0)
- // if prevX == headX {
- // if prevY > headY {
- // bBack = 1.0
- // } else {
- // tBack = 1.0
- // }
- // }
- // if prevY == headY {
- // if prevX > headX {
- // lBack = 1.0
- // } else {
- // rBack = 1.0
- // }
- // }
- lWall := headX
- rWall := (width - headX)
- tWall := headY
- bWall := (height - headY)
- lFood := float64(width)
- rFood := float64(width)
- tFood := float64(height)
- bFood := float64(height)
- // tlFood := float64(diag)
- // trFood := float64(diag)
- // blFood := float64(diag)
- // brFood := float64(diag)
- tlWall := float64(0)
- trWall := float64(0)
- blWall := float64(0)
- brWall := float64(0)
- if headX == foodX {
- tFood = headY - foodY
- if tFood < 0 {
- tFood = height
- }
- bFood = foodY - headY
- if bFood < 0 {
- bFood = height
- }
- }
- if headY == foodY {
- rFood = foodX - headX
- if rFood < 0 {
- rFood = width
- }
- lFood = headX - foodX
- if lFood < 0 {
- lFood = width
- }
- }
- // if math.Abs(foodY-headY) == math.Abs(foodX-headX) {
- // if foodX > headX {
- // if foodY > headY {
- // trFood = math.Abs(foodX-headX) * math.Sqrt2
- // } else {
- // brFood = math.Abs(foodX-headX) * math.Sqrt2
- // }
- // } else {
- // if foodY > headY {
- // tlFood = math.Abs(foodX-headX) * math.Sqrt2
- // } else {
- // blFood = math.Abs(foodX-headX) * math.Sqrt2
- // }
- // }
- // }
- if lWall > tWall {
- tlWall = float64(tWall) * math.Sqrt2
- } else {
- tlWall = float64(lWall) * math.Sqrt2
- }
- if rWall > tWall {
- trWall = float64(tWall) * math.Sqrt2
- } else {
- trWall = float64(rWall) * math.Sqrt2
- }
- if lWall > bWall {
- blWall = float64(bWall) * math.Sqrt2
- } else {
- blWall = float64(lWall) * math.Sqrt2
- }
- if rWall > bWall {
- blWall = float64(bWall) * math.Sqrt2
- } else {
- brWall = float64(rWall) * math.Sqrt2
- }
- if lWall > tWall {
- tlWall = float64(tWall) * math.Sqrt2
- } else {
- tlWall = float64(lWall) * math.Sqrt2
- }
- if rWall > tWall {
- trWall = float64(tWall) * math.Sqrt2
- } else {
- trWall = float64(rWall) * math.Sqrt2
- }
- if lWall > bWall {
- blWall = float64(bWall) * math.Sqrt2
- } else {
- blWall = float64(lWall) * math.Sqrt2
- }
- if rWall > bWall {
- blWall = float64(bWall) * math.Sqrt2
- } else {
- brWall = float64(rWall) * math.Sqrt2
- }
- // tTail := (headY - tailY)
- // if tTail < 0 {
- // tTail = height
- // }
- // bTail := (tailY - headY)
- // if bTail < 0 {
- // bTail = height
- // }
- // lTail := (headX - tailX)
- // if lTail < 0 {
- // tTail = width
- // }
- // rTail := (tailX - headX)
- // if lTail < 0 {
- // tTail = width
- // }
- // tlTail := float64(diag)
- // trTail := float64(diag)
- // blTail := float64(diag)
- // brTail := float64(diag)
- // if math.Abs(headY-tailY) == math.Abs(headX-tailX) {
- // if tailY > headY {
- // if tailX > headX {
- // trTail = math.Abs(tailX-headX) * math.Sqrt2
- // } else {
- // tlTail = math.Abs(tailX-headX) * math.Sqrt2
- // }
- // } else {
- // if tailX > headX {
- // brTail = math.Abs(tailX-headX) * math.Sqrt2
- // } else {
- // blTail = math.Abs(tailX-headX) * math.Sqrt2
- // }
- // }
- // }
- return []float64{
- lWall / width,
- rWall / width,
- tWall / height,
- bWall / height,
- // (1.0 - lFood/width),
- // (1.0 - rFood/width),
- // (1.0 - tFood/height),
- // (1.0 - bFood/height),
- tlWall / diag,
- trWall / diag,
- blWall / diag,
- brWall / diag,
- // (1.0 - tlFood/diag),
- // (1.0 - trFood/diag),
- // (1.0 - blFood/diag),
- // (1.0 - brFood/diag),
- // tTail / height,
- // bTail / height,
- // lTail / width,
- // rTail / width,
- // tlTail / diag,
- // trTail / diag,
- // blTail / diag,
- // brTail / diag,
- }
- }
- func (s *SnakeSimulator) StartServer() {
- go func() {
- grpcServer := grpc.NewServer()
- RegisterSnakeSimulatorServer(grpcServer, s)
- lis, err := net.Listen("tcp", "localhost:65002")
- if err != nil {
- fmt.Printf("Failed to listen: %v\n", err)
- }
- fmt.Printf("Listen SnakeSimulator localhost:65002\n")
- if err := grpcServer.Serve(lis); err != nil {
- fmt.Printf("Failed to serve: %v\n", err)
- }
- }()
- }
- func (s *SnakeSimulator) Run() {
- s.field.GenerateNextFood()
- for true {
- direction := rand.Int31()%4 + 1
- newHead := s.snake.NewHead(Direction(direction))
- if newHead.X == s.field.Food.X && newHead.Y == s.field.Food.Y {
- s.snake.Feed(newHead)
- s.field.GenerateNextFood()
- s.fieldUpdateQueue <- true
- } else if newHead.X > s.field.Width || newHead.Y > s.field.Height {
- fmt.Printf("Game over\n")
- break
- } else if selfCollisionIndex := s.snake.SelfCollision(newHead); selfCollisionIndex > 0 {
- if selfCollisionIndex == 1 {
- fmt.Printf("Step backward, skip\n")
- continue
- }
- fmt.Printf("Game over self collision\n")
- break
- } else {
- s.snake.Move(newHead)
- }
- s.snakeUpdateQueue <- true
- time.Sleep(50 * time.Millisecond)
- }
- }
- func (s *SnakeSimulator) Field(_ *None, srv SnakeSimulator_FieldServer) error {
- ctx := srv.Context()
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- }
- srv.Send(s.field)
- <-s.fieldUpdateQueue
- }
- }
- func (s *SnakeSimulator) Snake(_ *None, srv SnakeSimulator_SnakeServer) error {
- ctx := srv.Context()
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- }
- srv.Send(s.snake)
- <-s.snakeUpdateQueue
- }
- }
- func (s *SnakeSimulator) Stats(_ *None, srv SnakeSimulator_StatsServer) error {
- ctx := srv.Context()
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- }
- srv.Send(s.stats)
- <-s.statsUpdateQueue
- }
- }
- func (s *SnakeSimulator) SetSpeed(ctx context.Context, speed *Speed) (*None, error) {
- s.speedQueue <- speed.Speed
- return &None{}, nil
- }
|