Wednesday 26 August 2020

REST implement random & simple move algorithms

I know you have been lied to, well suck it up buttercup; I'm moving on with my life, this series isn't about writing algorithms to win tic tac toe. 

Now we are going to implement the two algorithms that we created, we are going to call them from our controller methods.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using tictactoe.game.interfaces;
using tictactoe.game.models;

namespace src.controllers.v1 {

  [ApiController]
  [Route("api/v1/[controller]")]
  public class GameController : ControllerBase {
    private readonly ILogger<GameController_logger;

    public GameController(ILogger<GameControllerlogger){
      this._logger = logger;
    }

    [HttpGet("HelloWorld")]
    public ActionResult<stringHelloWorld() => Ok($"hello world");

    [HttpGet("RandomMove")]
    public ActionResult<IMoveRandomMove([FromQuerystring[] m){
      IEnumerable<IMovemoves = m.Select(m => new Move(m));
      var game = new Game(moves.ToArray());
      var move = game.RandomResponse();
      return Ok(new {
        symbol move.Symbol,
        x move.Coordinates.X,
        y move.Coordinates.Y
      });
    }

    [HttpGet("SimpleMove")]
    public ActionResult<IMoveSimpleMove([FromQuerystring[] m){
      IEnumerable<IMovemoves = m.Select(m => new Move(m));
    var game = new Game(moves.ToArray());
      var move = game.SimpleResponse();
      return Ok(new {
        symbol move.Symbol,
        x move.Coordinates.X,
        y move.Coordinates.Y
      });
    }

    [HttpGet("ExpertMove")]
    public ActionResult<stringExpertMove([FromQuerystring[] m){
      IEnumerable<IMovemoves = m.Select(m => new Move(m));
      return "Expert Move not implemented";
    }
  }
}

now you can see that we pass back a custom object, and that is because for some reason tuples are not serializing correctly.

lets test this in postman.

looks good for random

and for simple move

but wait there's more, lets try one with and exception

now in a production setting we wouldn't propagate the full exception to the client, but just the message.