/// <summary> /// Creates the children of this node with a given new piece /// </summary> /// <param name="newCurrentPiece"></param> public void ExtendNode(PieceModel newCurrentPiece) { List <PieceAction> actions = state.GetActions(newCurrentPiece); foreach (PieceAction action in actions) //Each child is related with one of the possible actions for the newCurrentPiece played in the state of this node { TetrisState newState = state.CloneState(); newState.DoAction(newCurrentPiece, action); newCurrentPiece.ResetCoordinates(); MCTSNode newNode = new MCTSNode(MCTreeSearch.nNodes, this, newState, action, newCurrentPiece); children.Add(newNode); } }
/// <summary> /// Main bot method that searches for the best action to do with the current piece in the current state. /// It has a budget of time which is the max time it has to find that best action /// </summary> /// <param name="nextPieceType"></param> /// <param name="budget"></param> /// <returns></returns> public virtual IEnumerator ActCoroutine(PieceType nextPieceType, float budget) { float t0 = 0.0f; PieceModel nextPiece = new PieceModel(nextPieceType); List <PieceAction> possibleActions; //First of all, it gets the possible actions with the current piece in the current state if (!pieceActionDictionary.ContainsKey(nextPieceType)) { possibleActions = emptyTetrisState.GetActions(nextPiece); pieceActionDictionary.Add(nextPieceType, possibleActions); } else { possibleActions = pieceActionDictionary[nextPieceType]; } float bestScore = -float.MaxValue; PieceAction bestAction; int i = Random.Range(0, possibleActions.Count); //The first possible action to test is chosen randomly int initialIndex = i; bestAction = possibleActions[i]; yield return(null); t0 += Time.deltaTime; //In a while loop that goes until the time ends while (t0 < budget && i < possibleActions.Count) { if (!TBController.pausedGame) { t0 += Time.deltaTime; TetrisState newState = currentTetrisState.CloneState(); //The TetrisState is cloned newState.DoAction(nextPiece, possibleActions[i]); //One of the possible actions is played in the cloned state nextPiece.ResetCoordinates(); float score = newState.GetScore(); //And its score is got if (score > bestScore) { bestScore = score; bestAction = possibleActions[i]; } i++; if (i == possibleActions.Count) { i = 0; } if (i == initialIndex) { break; //If all the possible actions have been tested, the while loop ends } } yield return(null); } currentTetrisState.DoAction(nextPiece, bestAction); //The bestAction is played in the real state TBController.DoActionByBot(bestAction); //And also, it is said to the TetrisBoardController to play that action in the real board }