Esempio n. 1
0
func (a *aiAdapter) TakeTurn(call botapi.Ai_takeTurn) error {
	ib, err := call.Params.Board()
	if err != nil {
		return err
	}
	board, err := ib.Board()
	if err != nil {
		return err
	}
	gameID, err := board.GameId()
	if err != nil {
		return err
	}

	// Convert the board to the game representation
	b, robots, err := convertBoard(board)
	if err != nil {
		return err
	}

	// Load the AI for this game, or create a new one
	ai := a.games[gameID].ai
	if ai == nil {
		ai = a.factory(gameID)

		// Load the cells for the board
		cells, err := ib.Cells()
		if err != nil {
			return nil
		}
		locs := convertLocs(cells, len(b.Cells), len(b.Cells[0]))
		a.games[gameID] = gameState{
			ai:   ai,
			locs: locs,
		}
	}
	b.LType = a.games[gameID].locs
	turns, err := botapi.NewTurn_List(call.Results.Segment(), int32(len(robots)))
	if err != nil {
		return err
	}
	for i, r := range robots {
		t := ai.Act(b, r)
		t.ToWire(r.ID, turns.At(i))
	}
	call.Results.SetTurns(turns)
	return nil
}
Esempio n. 2
0
func runMatch(gidCh chan<- gameID, ctx gocontext.Context, ds datastore, aiA, aiB *onlineAI, bc engine.BoardConfig) error {
	sTime := time.Now()
	// Create new board and store it.
	b := engine.EmptyBoard(bc)
	b.InitBoard(bc)
	_, seg, _ := capnp.NewMessage(capnp.SingleSegment(nil))
	wb, _ := botapi.NewRootInitialBoard(seg)
	b.ToWireWithInitial(wb, engine.P1Faction)
	gid, err := ds.startGame(aiA.Info.ID, aiB.Info.ID, wb)
	if err != nil {
		return err
	}
	gidCh <- gid

	// Run the game
	for !b.IsFinished() {
		turnCtx, _ := gocontext.WithTimeout(ctx, 30*time.Second)
		chA, chB := make(chan turnResult), make(chan turnResult)
		go aiA.takeTurn(turnCtx, gid, b, engine.P1Faction, chA)
		go aiB.takeTurn(turnCtx, gid, b, engine.P2Faction, chB)
		ra, rb := <-chA, <-chB
		if ra.err.HasError() {
			log.Printf("Errors from AI ID %s: %v", aiA.Info.ID, ra.err)
		}
		if rb.err.HasError() {
			log.Printf("Errors from AI ID %s: %v", aiB.Info.ID, rb.err)
		}
		b.Update(ra.results, rb.results)
		_, s, err := capnp.NewMessage(capnp.SingleSegment(nil))
		if err != nil {
			return err
		}
		r, err := botapi.NewRootReplay_Round(s)
		if err != nil {
			return err
		}

		wireBoard, err := r.NewEndBoard()
		if err != nil {
			return err
		}
		b.ToWire(wireBoard, engine.P1Faction)

		ral, rbl := ra.results.Len(), rb.results.Len()
		turns, err := botapi.NewTurn_List(r.Segment(), int32(ral+rbl))
		if err != nil {
			return err
		}
		for i := 0; i < ral; i++ {
			t := ra.results.At(i)
			if err := turns.Set(i, t); err != nil {
				return err
			}
		}
		for i := 0; i < rbl; i++ {
			t := rb.results.At(i)
			if err := turns.Set(i+ral, t); err != nil {
				return err
			}
		}
		r.SetMoves(turns)
		db.addRound(gid, r)
	}

	gInfo := &gameInfo{
		ID:        gid,
		AI1:       &aiA.Info,
		AI2:       &aiB.Info,
		AI1Score:  b.BotCount(1),
		AI2Score:  b.BotCount(2),
		StartTime: sTime,
		EndTime:   time.Now(),
	}
	return db.finishGame(gid, &aiA.Info, &aiB.Info, gInfo)
}