Exemplo n.º 1
0
        public StepModel Step()
        {
            TicTacHelper helper = new TicTacHelper();
              List<StepModel> allowedSteps = new List<StepModel>();
              List<StepModel> loseEscapeSteps = new List<StepModel>();

              // Trying all steps...
              for (int x = 1; x <= 3; x++)
            for (int y = 1; y <= 3; y++)
            {
              StepModel step = new StepModel { X = x, Y = y, TicTac = Game.Player2TicTac };

              // Check if step is allowed
              if (!helper.IsAllowedStep(Game, step))
            continue;

              // Check if step is win. If it is I do this step immediatelly
              List<StepModel> oneStepForward = Game.Steps.ToList();
              oneStepForward.Add(step);
              if (helper.IsWin(oneStepForward))
            return step;

              // Check if next enemy step will be win
              step.TicTac = Game.Player1TicTac;
              List<StepModel> oneEnemyStepForward = Game.Steps.ToList();
              oneEnemyStepForward.Add(step);
              if (helper.IsWin(oneEnemyStepForward))
              {
            // Don't forget to set step TicTac back to my TicTac
            step.TicTac = Game.Player2TicTac;
            loseEscapeSteps.Add(step);
            continue;
              }
              else
            step.TicTac = Game.Player2TicTac;

              allowedSteps.Add(step);
            }

              int stepIndex;

              // If there are steps which can avoid my loss I selects random from them.
              // If there aren't I I selects random from allowed steps.
              if (loseEscapeSteps.Any())
              {
            stepIndex = random.Next(loseEscapeSteps.Count);
            return loseEscapeSteps[stepIndex];
              }
              else if (allowedSteps.Any())
              {
            stepIndex = random.Next(allowedSteps.Count);
            return allowedSteps[stepIndex];
              }
              else
            return null;
        }
Exemplo n.º 2
0
 // Check if step is allowed in game
 public bool IsAllowedStep(GameModel game, StepModel step)
 {
     return !game.Steps.Where(s => s.X == step.X && s.Y == step.Y).Any();
 }