示例#1
0
        private void solveButton_Click(object sender, EventArgs e)
        {
            var rowString = "";

            foreach (var box in rowTextBoxs)
            {
                rowString += box.Value.Text + ";";
            }
            var colString = "";

            foreach (var box in rowTextBoxs)
            {
                colString += box.Value.Text + ";";
            }

            var puzzle = PuzzleFactory.Instance().MakePuzzle(numberOfRows, numberOfColumns, rowString, colString);

            PuzzleSolver solver = new PuzzleSolver(puzzle);

            solver.Solve();

            if (solver.Solve())
            {
                UpdateDisplay(puzzle);
            }
            else
            {
                MessageBox.Show(solver.ErrorMessage);
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            var day = PuzzleFactory.GetPuzzle(21, "b");

            day.ReadInput();
            day.Solve();
            day.DeliverResults();
        }
        private void ShuffleCommandAction(object parameter)
        {
            _puzzleState     = PuzzleFactory.CreateShuffled();
            _puzzleSteps     = 0;
            _puzzleCompleted = false;

            RaisePropertyChanged(nameof(PuzzleState));
            RaisePropertyChanged(nameof(PuzzleStepsInfo));
            RaisePropertyChanged(nameof(IsPuzzleCompleted));
        }
示例#4
0
        /// <summary>
        /// This method maps a PuzzleEntity object to a Puzzle object.
        /// </summary>
        /// <param name="puzzleEntity">PuzzleEntity to be mapped.</param>
        /// <returns>Puzzle object</returns>
        public Puzzle MapPuzzleEntityToPuzzle(PuzzleEntity puzzleEntity)
        {
            var difficulty = (Difficulty)puzzleEntity.Difficulty;
            var puzzle     = PuzzleFactory.GetPuzzle(difficulty);

            puzzle.Id = puzzleEntity.Id;
            int[,] array;
            MapToArray(puzzleEntity.WorkingPuzzleArray, out array);
            puzzle.PuzzleArray = array;
            return(puzzle);
        }
示例#5
0
        public void MapPuzzleToPuzzleEntity()
        {
            var puzzle = PuzzleFactory.GetPuzzle(Core.Enums.Difficulty.Medium);

            Assert.IsInstanceOfType(puzzle, typeof(MediumPuzzle));
            puzzle.CreatePuzzle();
            Assert.IsNotNull(puzzle.PuzzleArray);
            var dataMapper   = new PuzzleMapper();
            var puzzleEntity = dataMapper.MapPuzzleToPuzzleEntity(puzzle);

            Assert.AreEqual(puzzle.Id, puzzleEntity.Id);
        }
示例#6
0
        public GameViewModel(IEventAggregator eventAggregator,
                             GameRepository gameRepository)
        {
            _gameRepository  = gameRepository;
            _eventAggregator = eventAggregator;

            New        = new Command(async() => await NewCommandAsync());
            Solve      = new Command(CanSolveCheck, async() => await SolveCommandAsync());
            Check      = new Command(CanSolveCheck, async() => await CheckPuzzleAsync());
            Save       = new Command(CanSave, async() => await SavePuzzleAsync());
            Load       = new Command(LoadCommand);
            Undo       = new Command(CanUndo, UndoCommand);
            puzzle     = PuzzleFactory.GetPuzzle(Difficulty);
            Difficulty = Difficulty.Empty;
        }
示例#7
0
 public void TestSetUp()
 {
     Puzzle = PuzzleFactory.Instance().MakePuzzle(5, 5, new List <Line>
     {
         PuzzleFactory.Instance().MakeLine <Row>(new[] { 1, 1 }, 0),
         PuzzleFactory.Instance().MakeLine <Row>(new[] { 5 }, 1),
         PuzzleFactory.Instance().MakeLine <Row>(new[] { 1, 1 }, 2),
         PuzzleFactory.Instance().MakeLine <Row>(new[] { 5 }, 3),
         PuzzleFactory.Instance().MakeLine <Row>(new[] { 1, 1 }, 4),
         PuzzleFactory.Instance().MakeLine <Column>(new[] { 1, 1 }, 0),
         PuzzleFactory.Instance().MakeLine <Column>(new[] { 5 }, 1),
         PuzzleFactory.Instance().MakeLine <Column>(new[] { 1, 1 }, 2),
         PuzzleFactory.Instance().MakeLine <Column>(new[] { 5 }, 3),
         PuzzleFactory.Instance().MakeLine <Column>(new[] { 1, 1 }, 4)
     });
 }
示例#8
0
        /// <summary>
        /// Load GameBoard object into viewmodel
        /// </summary>
        /// <param name="puzzleId">Determine which puzzle object to load (nullable will load fresh game)</param>
        /// <returns></returns>
        public async Task LoadPuzzle(int?puzzleId = null)
        {
            if (puzzleId.HasValue)
            {
                puzzle    = _gameRepository.GetPuzzleById(puzzleId.Value);
                GameBoard = new GameBoardWrapper(new GameBoard(puzzle.PuzzleArray));
            }
            else
            {
                puzzle = PuzzleFactory.GetPuzzle(Difficulty);
                await Task.Run(() => puzzle.CreatePuzzle());

                GameBoard = new GameBoardWrapper(new GameBoard(puzzle.PuzzleArray)
                {
                    State = ObjectState.Added
                });
            }
        }
示例#9
0
        /// <summary>
        /// WinForms GUI for Sudoku game
        /// </summary>
        public UserInterface()
        {
            InitializeComponent();

            game  = PuzzleFactory.GetSudoku();          // Instantiate puzzle
            trans = new Transform(game.SideLength,      // Scaled and translated utility methods to match current dimensions
                                  new Size(pnlPuzzle.Width, pnlPuzzle.Height));
            gameHistory = new Stack <Game>();           // Prepare for undo history
            launch      = DateTime.Now;

            // Configure shared calculated values used for scaling and translating
            sqrtGameSize     = (int)Math.Round(Math.Sqrt(game.SideLength), 0);
            logicalCellSize  = sqrtGameSize + 1;
            logicalUnitCount = 1 + game.SideLength * logicalCellSize;

            //SetStyle(ControlStyles.ResizeRedraw, true); // Redraw form when resized
            stringFormat.Alignment     = StringAlignment.Center;
            stringFormat.LineAlignment = StringAlignment.Center;
        }
示例#10
0
        public void ShouldSavePuzzle()
        {
            var gameRepo       = new GameRepository(new PuzzleMapper());
            var puzzleEntities = gameRepo.GetPuzzleList();

            Assert.IsNotNull(puzzleEntities);
            var originalPuzzleCount = puzzleEntities.Count;

            var puzzle = PuzzleFactory.GetPuzzle(Core.Enums.Difficulty.Medium);

            Assert.IsInstanceOfType(puzzle, typeof(MediumPuzzle));
            puzzle.CreatePuzzle();
            Assert.IsNotNull(puzzle.PuzzleArray);

            gameRepo.SaveGame(puzzle);
            puzzleEntities = gameRepo.GetPuzzleList();
            Assert.IsNotNull(puzzleEntities);
            Assert.AreNotEqual(originalPuzzleCount, puzzleEntities.Count);
        }
示例#11
0
        public void ShouldStorePuzzleEntityMappedFromPuzzle()
        {
            using (var context = new GameContext())
            {
                var puzzle = PuzzleFactory.GetPuzzle(Core.Enums.Difficulty.Medium);
                Assert.IsInstanceOfType(puzzle, typeof(MediumPuzzle));

                puzzle.CreatePuzzle();
                Assert.IsNotNull(puzzle.PuzzleArray);

                var dataMapper   = new PuzzleMapper();
                var puzzleEntity = dataMapper.MapPuzzleToPuzzleEntity(puzzle);
                puzzleEntity.Name = "test save";
                Assert.AreEqual(puzzle.Id, puzzleEntity.Id);

                context.PuzzleEntities.Add(puzzleEntity);
                context.SaveChanges();
            }
        }
示例#12
0
        public void TestMethod2()
        {
            var list     = PuzzleFactory.StringToList("1 , 1 , 1 ; 1 ; 2 , 3");
            var expected = new List <int[]>();

            int[] a = { 1, 1, 1 };
            int[] b = { 1 };
            int[] c = { 2, 3 };
            expected.Add(a);
            expected.Add(b);
            expected.Add(c);

            for (int i = 0; i < list.Count; i++)
            {
                for (int j = 0; j < list[i].Length; j++)
                {
                    var x = expected[i][j];
                    var y = list[i][j];
                    Assert.AreEqual(x, y);
                }
            }
        }
示例#13
0
        public void ReturnsHardPuzzle()
        {
            var puzzle = PuzzleFactory.GetPuzzle(Core.Enums.Difficulty.Hard);

            Assert.IsInstanceOfType(puzzle, typeof(HardPuzzle));
        }
示例#14
0
        public void ReturnEmptyPuzzleByDefault()
        {
            var puzzle = PuzzleFactory.GetPuzzle(Core.Enums.Difficulty.Empty);

            Assert.IsInstanceOfType(puzzle, typeof(EmptyPuzzle));
        }
示例#15
0
        public void ReturnsMediumPuzzle()
        {
            var puzzle = PuzzleFactory.GetPuzzle(Core.Enums.Difficulty.Medium);

            Assert.IsInstanceOfType(puzzle, typeof(MediumPuzzle));
        }
示例#16
0
 public PuzzleRunner(PuzzleFactory puzzleFactory, PuzzleLocator puzzleLocator)
 {
     PuzzleFactory = puzzleFactory;
     PuzzleLocator = puzzleLocator;
 }
示例#17
0
 void Start()
 {
     pFactoryComponent = GetComponent <PuzzleFactory>();
 }
示例#18
0
        public void PuzzleFactory_GetSudoku_Valid()
        {
            var puzzle = PuzzleFactory.GetSudoku();

            Assert.IsInstanceOfType(puzzle, typeof(Game));
        }
示例#19
0
    /// <summary>
    /// Solves the puzzle associated with the specified HTTP request as an asynchronous operation.
    /// </summary>
    /// <param name="year">The year the puzzle to solve is from.</param>
    /// <param name="day">The day the puzzle to solve is from.</param>
    /// <param name="request">The HTTP request.</param>
    /// <param name="factory">The <see cref="PuzzleFactory"/> to use.</param>
    /// <param name="logger">The <see cref="ILogger"/> to use.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
    /// <returns>
    /// A <see cref="Task"/> representing the asynchronous operation to solve the puzzle.
    /// </returns>
    internal static async Task <IResult> SolvePuzzleAsync(
        int year,
        int day,
        HttpRequest request,
        PuzzleFactory factory,
        ILogger <Puzzle> logger,
        CancellationToken cancellationToken)
    {
        if (!request.HasFormContentType)
        {
            return(Results.Problem("The specified media type is not supported.", statusCode: StatusCodes.Status415UnsupportedMediaType));
        }

        Puzzle puzzle;

        try
        {
            puzzle = factory.Create(year, day);
        }
        catch (PuzzleException ex)
        {
            return(Results.Problem(ex.Message, statusCode: StatusCodes.Status404NotFound));
        }

        var metadata = puzzle.Metadata();

        if (metadata.IsHidden)
        {
            return(Results.Problem("This puzzle cannot be solved.", statusCode: StatusCodes.Status403Forbidden));
        }

        string[] arguments = Array.Empty <string>();

        if (metadata.RequiresData || metadata.MinimumArguments > 0)
        {
            var form = await request.ReadFormAsync(cancellationToken);

            if (metadata.RequiresData)
            {
                if (form.Files["resource"] is not {
                } resource)
                {
                    return(Results.Problem("No puzzle resource provided.", statusCode: StatusCodes.Status400BadRequest));
                }

                puzzle.Resource = resource.OpenReadStream();
            }

            if (form.TryGetValue("arguments", out var values))
            {
                arguments = values.Select((p) => p).ToArray();
            }
        }

        var timeout = TimeSpan.FromMinutes(1);

        using var timeoutCts = new CancellationTokenSource(timeout);
        using var linkedCts  = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken);
        var stopwatch = Stopwatch.StartNew();

        PuzzleResult solution;

        try
        {
            solution = await puzzle.SolveAsync(arguments, linkedCts.Token).WaitAsync(timeout, linkedCts.Token);
        }
        catch (OperationCanceledException)
        {
            return(Results.Problem($"The puzzle was not solved within {timeout}.", statusCode: StatusCodes.Status408RequestTimeout));
        }
        catch (PuzzleException ex)
        {
            return(Results.Problem(ex.Message, statusCode: StatusCodes.Status400BadRequest));
        }
#pragma warning disable CA1031
        catch (Exception ex)
#pragma warning restore CA1031
        {
            Log.FailedToSolvePuzzle(logger, ex, year, day);
            return(Results.Problem("Failed to solve puzzle.", statusCode: StatusCodes.Status500InternalServerError));
        }

        stopwatch.Stop();

        var result = new PuzzleSolution
        {
            Year           = year,
            Day            = day,
            Solutions      = solution.Solutions,
            Visualizations = solution.Visualizations,
            TimeToSolve    = stopwatch.Elapsed.TotalMilliseconds,
        };

        return(Results.Json(result));
    }
        public void ShouldNot_CreatePuzzleDayClassName(int dayNumber, string daySuffix, string expected)
        {
            var name = PuzzleFactory.CreatePuzzleDayClassName(dayNumber, daySuffix);

            Assert.NotEqual(name, expected);
        }
 public void ShouldNot_ValidateArguments_daySuffix(int dayNumber, string daySuffix)
 {
     Assert.Throws <ArgumentException>("daySuffix", () => PuzzleFactory.ValidateArguments(dayNumber, daySuffix));
 }
 public void Should_ValidateArguments(int dayNumber, string daySuffix)
 {
     PuzzleFactory.ValidateArguments(dayNumber, daySuffix);
 }