Пример #1
0
 public bool AppliesAt(int x, int y, SudokuGrid grid)
 {
     if (house == Houses.Cell)
     {
         return(x == i0 && y == i1);
     }
     if (house == Houses.Column)
     {
         return(x == i0);
     }
     if (house == Houses.Row)
     {
         return(y == i0);
     }
     if (house == Houses.Box)
     {
         return(grid.BoxAt(x, y) == i0);
     }
     if (house == Houses.MajorDiagonal)
     {
         return(x == y);
     }
     if (house == Houses.MinorDiagonal)
     {
         return(x == grid.Cells - y - 1);
     }
     if (house == Houses.Cage)
     {
         return(grid.CageAt(x, y) == i0);
     }
     return(false);
 }
Пример #2
0
        public SolveResult DoLogicalSolve(SudokuGrid grid, HintSelections hs)
        {
            if (hs == null)
            {
                return(DoBacktrackingSolve(grid));
            }

            while (true)
            {
                if (Solved)
                {
                    return(SolveResult.SingleSolution);
                }
                Hint hint = SingleHint(hs);
                if (hint == null)
                {
                    return(SolveResult.TooDifficult);
                }
                SolveResult result = hint.Apply(grid);
                if (result != SolveResult.Ongoing)
                {
                    return(result);
                }
            }
        }
Пример #3
0
        private void InitCells(SudokuGrid grid)
        {
            CurrentCell         = new SudokuCell(FirstCellRowPosition, FirstCellColPosition);
            CurrentCellRowIndex = 0;
            CurrentCellColIndex = 0;

            const int SudokuDim = SudokuGrid.SudokuDimension;

            cells = new SudokuCell[SudokuDim, SudokuDim];
            int       currWindowRowPos = GameWindow.FirstCellRowPosition;
            int       currWindowColPos = GameWindow.FirstCellColPosition;
            const int RowIncrement     = GameWindow.CellPositionRowIncrements;
            const int ColIncrement     = GameWindow.CellPositionColIncrements;

            for (int row = 0; row < SudokuDim; row++)
            {
                for (int col = 0; col < SudokuDim; col++)
                {
                    cells[row, col]   = new SudokuCell(grid[row, col], grid.IsEditable(row, col), currWindowRowPos, currWindowColPos);
                    currWindowColPos += ColIncrement;
                }
                currWindowColPos  = GameWindow.FirstCellColPosition;
                currWindowRowPos += RowIncrement;
            }

            menuCells = new MenuCell[MenuItemLabels.Length];
            for (int item = 0; item < menuCells.Length; item++)
            {
                menuCells[item] = new MenuCell(MenuItemsCellRowPosition, MenuItemsCellColPositions[item], MenuItemLabels[item]);
            }
            RedrawCells();
        }
Пример #4
0
        public void FillTemplate(XmlDocument doc, SudokuGrid grid)
        {
            XmlNode sudoku = doc.CreateNode(XmlNodeType.Element, "Sudoku", "");
            XmlNode hints  = doc.CreateNode(XmlNodeType.Element, "Hints", "");
            XmlNode rows   = doc.CreateNode(XmlNodeType.Element, "Rows", "");

            doc.AppendChild(sudoku);
            sudoku.AppendChild(hints);
            hints.AppendChild(rows);

            for (int row = 0; row < 9; row++)
            {
                XmlNode node = doc.CreateNode(XmlNodeType.Element, "Row", "");

                rows.AppendChild(node);

                for (int col = 0; col < 9; col++)
                {
                    if (grid[row, col] == 0)
                    {
                        node.InnerText += "-,";
                    }
                    else
                    {
                        node.InnerText += grid[row, col] + ",";
                    }
                }

                if (node.InnerText.Length > 0)
                {
                    node.InnerText = node.InnerText.Remove(node.InnerText.Length - 1, 1);
                }
            }
        }
Пример #5
0
        void UpdateTooltip(int x, int y, SudokuGrid grid)
        {
            StringBuilder hints = new StringBuilder();

            foreach (Hint hint in Grid.PaintedHints)
            {
                if (AppliesAt(hint, x, y, grid))
                {
                    hints.AppendLine(hint.ToString());
                }
            }
            if (hints.Length == 0)
            {
                if (toolTipText != null)
                {
                    toolTipText     = null;
                    toolTip1.Active = false;
                }
            }
            else
            {
                if (toolTipText == null ||
                    !toolTipText.Equals(hints.ToString()))
                {
                    toolTipText     = hints.ToString();
                    toolTip1.Active = true;
                    toolTip1.SetToolTip(this, toolTipText);
                }
            }
        }
Пример #6
0
        public SudokuZone(SudokuGrid grid, int row, int col)
        {
            InitializeComponent();

            this._grid = grid;
            this._cells = new SudokuCell[grid.Puzzle.Rank, grid.Puzzle.Rank];
            this._row = row;
            this._column = col;

            StackPanel zoneStackPanel = new StackPanel() { Orientation = Orientation.Vertical };

            for (int i = 0; i < grid.Puzzle.Rank; i++)
            {
                StackPanel rowStackPanel = new StackPanel() { Orientation = Orientation.Horizontal };

                for (int j = 0; j < grid.Puzzle.Rank; j++)
                {
                    SudokuCell cell = new SudokuCell(this, i, j);
                    this._cells[i, j] = cell;
                    rowStackPanel.Children.Add(cell);
                }

                zoneStackPanel.Children.Add(rowStackPanel);
            }

            this.SudokuCellContainer.Child = zoneStackPanel;
        }
Пример #7
0
        public SudokuZone()
        {
            InitializeComponent();

            this._grid = null;
            this._cells = new SudokuCell[3, 3];
            this._row = 0;
            this._column = 0;

            StackPanel zoneStackPanel = new StackPanel() { Orientation = Orientation.Vertical };

            for (int i = 0; i < 3; i++)
            {
                StackPanel rowStackPanel = new StackPanel() { Orientation = Orientation.Horizontal };

                for (int j = 0; j < 3; j++)
                {
                    SudokuCell cell = new SudokuCell();
                    this._cells[i, j] = cell;
                    rowStackPanel.Children.Add(cell);
                }

                zoneStackPanel.Children.Add(rowStackPanel);
            }

            this.SudokuCellContainer.Child = zoneStackPanel;
        }
Пример #8
0
        public static SudokuGrid Random()
        {
            SudokuGrid newGrid = new SudokuGrid();
            Dictionary <int, List <int> > columnValues = new Dictionary <int, List <int> >();
            Dictionary <int, List <int> > boxValues    = new Dictionary <int, List <int> >();

            for (int i = 0; i < 9; i++)
            {
                columnValues[i] = new List <int>();
                boxValues[i]    = new List <int>();
            }

            for (int i = 0; i < 9; i++)
            {
                var rowValues = AssignRow(columnValues, boxValues, i);
                for (int j = 0; j < 9; j++)
                {
                    newGrid._grid[i, j] = rowValues[j];
                    columnValues[j].Add(rowValues[j]);
                    boxValues[GetBoxNumber(i, j)].Add(rowValues[j]);
                }
            }

            return(newGrid);
        }
Пример #9
0
        public void FillDocument(XmlDocument doc, SudokuGrid grid, int CM)
        {
            XmlNode rows1   = doc.CreateNode(XmlNodeType.Element, "Rows", "");
            XmlNode rows2   = doc.CreateNode(XmlNodeType.Element, "Rows", "");
            XmlNode sudoku  = doc.CreateNode(XmlNodeType.Element, "Sudoku", "");
            XmlNode hints   = doc.CreateNode(XmlNodeType.Element, "Hints", "");
            XmlNode guesses = doc.CreateNode(XmlNodeType.Element, "Guesses", "");

            doc.AppendChild(sudoku);
            sudoku.AppendChild(hints);
            sudoku.AppendChild(guesses);
            guesses.AppendChild(rows1);
            hints.AppendChild(rows2);

            for (int row = 0; row < 10; row++)
            {
                XmlNode node  = doc.CreateNode(XmlNodeType.Element, "Row", "");
                XmlNode node2 = doc.CreateNode(XmlNodeType.Element, "Row", "");
                rows1.AppendChild(node2);
                rows2.AppendChild(node);
                if (row == 9)
                {
                    node2.InnerText += CM.ToString();
                }
                else
                {
                    for (int col = 0; col < 9; col++)
                    {
                        if (grid[row, col] == 0)
                        {
                            node.InnerText  += "-,";
                            node2.InnerText += "-,";
                        }
                        else
                        {
                            if (grid.IsKnownElement(row, col))
                            {
                                node.InnerText  += grid[row, col] + ",";
                                node2.InnerText += "-,";
                            }
                            else
                            {
                                node.InnerText  += "-,";
                                node2.InnerText += grid[row, col] + ",";
                            }
                        }
                    }

                    if (node.InnerText.Length > 0)
                    {
                        node.InnerText = node.InnerText.Remove(node.InnerText.Length - 1, 1);
                    }

                    if (node2.InnerText.Length > 0)
                    {
                        node2.InnerText = node2.InnerText.Remove(node2.InnerText.Length - 1, 1);
                    }
                }
            }
        }
Пример #10
0
        //Generates and returns a new Sudoku grid
        public static SudokuGrid Generate(SudokuGrid.Difficulty difficulty)
        {
            SudokuGrid generatedGrid = new SudokuGrid(ReadySudokus[randGenerator.Next(0, ReadySudokus.Length - 1)], difficulty, false);

            //Do some transformations.
            for (int transposeCount = 0; transposeCount < TransposeLimit; transposeCount++)
            {
                for (int groupSwapCount = 0; groupSwapCount < GroupSwapsLimit; groupSwapCount++)
                {
                    for (int rowSwapCount = 0; rowSwapCount < RowSwapsLimit; rowSwapCount++)
                    {
                        generatedGrid.Transform(SudokuGrid.TransformType.SwapRows);
                    }
                    generatedGrid.Transform(SudokuGrid.TransformType.SwapGroups);
                }
                generatedGrid.Transform(SudokuGrid.TransformType.Transpose);
            }

            #region Remove some numbers.

            int cellsToRemove = 0, emptyRowsLimit = 0;
            switch (difficulty)
            {
                case SudokuGrid.Difficulty.Easy:
                    cellsToRemove = EasyDifficultyInitEmptyCells;
                    emptyRowsLimit = EasyDifficultyMaxEmptyRows;
                    break;
                case SudokuGrid.Difficulty.Medium:
                    cellsToRemove = MediumDifficultyInitEmptyCells;
                    emptyRowsLimit = MediumDifficultyMaxEmptyRows;
                    break;
                case SudokuGrid.Difficulty.Hard:
                    cellsToRemove = HardDifficultyInitEmptyCells;
                    emptyRowsLimit = HardDifficultyMaxEmptyRows;
                    break;
            }
            generatedGrid.EmptyCells = cellsToRemove;

            //Start removing random numbers
            int cellsRemoved = 0;
            int rowsRemoved = 0;
            int row, col;
            const int IndexLimit = SudokuGrid.SudokuDimension - 1;
            while (cellsRemoved <= cellsToRemove)
            {
                row = randGenerator.Next(0, IndexLimit);
                col = randGenerator.Next(0, IndexLimit);

                if (!(generatedGrid.IsSingleInRow(row, col) && rowsRemoved > emptyRowsLimit))
                {
                    generatedGrid.ClearCell(row, col);
                    cellsRemoved++;
                }
            }

            #endregion

            return generatedGrid;
        }
Пример #11
0
        public static SudokuGrid Generate(SudokuGrid.Difficulty difficulty)
        {
            SudokuGrid generatedGrid = new SudokuGrid(ReadySudokus[randGenerator.Next(0, ReadySudokus.Length - 1)], difficulty, false);

            for (int transposeCount = 0; transposeCount < TransposeLimit; transposeCount++)
            {
                for (int groupSwapCount = 0; groupSwapCount < GroupSwapsLimit; groupSwapCount++)
                {
                    for (int rowSwapCount = 0; rowSwapCount < RowSwapsLimit; rowSwapCount++)
                    {
                        generatedGrid.Transform(SudokuGrid.TransformType.SwapRows);
                    }
                    generatedGrid.Transform(SudokuGrid.TransformType.SwapGroups);
                }
                generatedGrid.Transform(SudokuGrid.TransformType.Transpose);
            }

            #region Remove some numbers.

            int cellsToRemove = 0, emptyRowsLimit = 0;
            switch (difficulty)
            {
            case SudokuGrid.Difficulty.Easy:
                cellsToRemove  = EasyDifficultyInitEmptyCells;
                emptyRowsLimit = EasyDifficultyMaxEmptyRows;
                break;

            case SudokuGrid.Difficulty.Medium:
                cellsToRemove  = MediumDifficultyInitEmptyCells;
                emptyRowsLimit = MediumDifficultyMaxEmptyRows;
                break;

            case SudokuGrid.Difficulty.Hard:
                cellsToRemove  = HardDifficultyInitEmptyCells;
                emptyRowsLimit = HardDifficultyMaxEmptyRows;
                break;
            }
            generatedGrid.EmptyCells = cellsToRemove;

            int       cellsRemoved = 0;
            int       rowsRemoved = 0;
            int       row, col;
            const int IndexLimit = SudokuGrid.SudokuDimension - 1;
            while (cellsRemoved <= cellsToRemove)
            {
                row = randGenerator.Next(0, IndexLimit);
                col = randGenerator.Next(0, IndexLimit);

                if (!(generatedGrid.IsSingleInRow(row, col) && rowsRemoved > emptyRowsLimit))
                {
                    generatedGrid.ClearCell(row, col);
                    cellsRemoved++;
                }
            }

            #endregion

            return(generatedGrid);
        }
Пример #12
0
 protected void CreateRequirements(SudokuGrid grid, int nc)
 {
     ca = new SudokuRequirement[nc];
     for (int i = 0; i < ca.Length; ++i)
     {
         ca[i] = new SudokuRequirement();
     }
 }
Пример #13
0
 public GameWindow()
 {
     grid = SudokuGenerator.Generate(SudokuGrid.Difficulty.Easy);
     InitWindow();
     InitCells(grid);
     currentMenuItem = MenuItem.None;
     currentMenuItemIndex = 0;
     gameIsRunning = true;
 }
Пример #14
0
 public GameWindow()
 {
     grid = SudokuGenerator.Generate(SudokuGrid.Difficulty.Easy);
     InitWindow();
     InitCells(grid);
     currentMenuItem      = MenuItem.None;
     currentMenuItemIndex = 0;
     gameIsRunning        = true;
 }
Пример #15
0
 public PaintContext(Graphics graphics, Size size, SudokuGrid grid, int selx, int sely)
     : base(size, grid.CellA, grid.CellB)
 {
     this.grid     = grid;
     this.graphics = graphics;
     this.selx     = selx;
     this.sely     = sely;
     SmallFont     = new Font(FontFamily.GenericSansSerif, 10.0f);
     LargeFont     = new Font(FontFamily.GenericSansSerif, 30.0f);
 }
Пример #16
0
 protected void CreateOptionals(SudokuGrid grid, int nc)
 {
     co = new CageOptional[nc, Cells];
     for (int i0 = 0; i0 < nc; ++i0)
     {
         for (int i1 = 0; i1 < Cells; ++i1)
         {
             co[i0, i1] = new CageOptional(grid.cageInfo);
         }
     }
 }
Пример #17
0
        public SudokuForm(SudokuGrid grid)
        {
            System.Diagnostics.Debug.Assert(Instance == null);
            Instance = this;

            InitializeComponent();
            sudokuControl.Grid = grid;
            CreateChildMenus();
            UpdateMode();
            LoadOptions();
        }
Пример #18
0
        private void easyButton_Click(object sender, EventArgs e)
        {
            // Seleccionamos el sudoku a mostrar
            Random     rnd        = new Random();
            int        puzzlePick = rnd.Next(1, numOfSolvedGrids() + 1);
            SudokuGrid sudokuGrid = new SudokuGrid(getPuzzle(puzzlePick));
            PlayWindow pw         = new PlayWindow(gameControl, sudokuGrid, 0);

            pw.FormClosed += (s, args) => Close();
            Hide();
            pw.Show();
        }
Пример #19
0
        //////////////////////////

        public SudokuGame(SudokuGrid sg, SudokuGames sgs)
        {
            SudokuGrid = sg;
            Parent     = sgs;

            Id                  = Guid.NewGuid();
            Players             = new List <Player>();
            Actions             = new List <Action>();
            SendClientsDelegate = SendClients;

            Parent.Add(this);
        }
Пример #20
0
        private void NewGame(SudokuGrid.Difficulty difficulty)
        {
            grid = SudokuGenerator.Generate(difficulty);

            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    cells[row, col].RefreshValues(grid[row, col], grid.IsEditable(row, col));
                }
            }
            RefreshCellValues();
        }
Пример #21
0
        public void NewGame()
        {
            SudokuGrid = GameController.NewGame();

            //Bind the cells
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    squares[i, j].DataContext = SudokuGrid[i, j];
                }
            }
        }
Пример #22
0
 public PlayWindow(GameControl gc, SudokuGrid sg, int difficulty) // difficulty: 0 - easy, 1 - medium, 2 - hard
 {
     InitializeComponent();
     gameControl = gc;
     gameControl.createButtonGrid(this, 40);
     gameControl.setSizeOfWindow(this, 40);
     gameControl.createToolbox(this, 50);
     gameControl.setSelectedToolkitButtonName("toolkit1");
     gameControl.setHighlightNumber(this, 1);
     gameControl.showStartingNumbers(difficulty, sg);
     gridDifficulty = difficulty;
     sudokuGrid     = sg;
     initialToolkitCheck();
 }
Пример #23
0
        private void doWork(object state)
        {
            SudokuGrid sg = new SudokuGrid(path, file);

            updateProgressLabel("Trabajando...");
            sg.setUpPlacementOrders();
            updateProgressBar();
            for (int i = 0; i < 9; i++)
            {
                sg.doInitialPlacementFill(i);
            }

            updateProgressBar();
            sg.populate(this);
        }
Пример #24
0
 public SudokuSolver(SudokuGrid grid)
 {
     Cells = grid.Cells;
     CreateMatrix(grid);
     for (int x = 0; x < Cells; ++x)
     {
         for (int y = 0; y < Cells; ++y)
         {
             if (grid.FlagAt(x, y) != SudokuGrid.CellFlags.Free)
             {
                 TrySelectCandidate(GetCandidate(x, y, grid.ValueAt(x, y)));
             }
         }
     }
 }
Пример #25
0
 public static void ReplaceListener(UpdateListener listener, SudokuGrid value, ref SudokuGrid grid)
 {
     if (grid == value)
     {
         return;
     }
     if (grid != null)
     {
         grid.RemoveListener(listener);
     }
     grid = value;
     if (grid != null)
     {
         grid.AddListener(listener);
     }
 }
Пример #26
0
        static void Main(string[] args)
        {
            SudokuGrid grid;

            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();

            s.Start();

            grid = SudokuGrid.Random();

            s.Stop();

            Console.WriteLine(grid.ToString());

            Console.WriteLine(s.ElapsedMilliseconds);

            Console.ReadLine();
        }
Пример #27
0
        public TheGrid()
        {
            InitializeComponent();


            SudokuGrid = GameController.CurrentGame;

            // Cadrillage
            for (int i = 0; i < 19; i += 2)
            {
                Rectangle rectCol = new Rectangle();
                rectCol.SetValue(Grid.ColumnProperty, i);
                rectCol.SetValue(Grid.RowSpanProperty, 19);
                rectCol.Fill = new SolidColorBrush(Colors.Black);

                sudokuGrid.Children.Insert(0, rectCol);

                Rectangle rectRow = new Rectangle();
                rectRow.SetValue(Grid.RowProperty, i);
                rectRow.SetValue(Grid.ColumnSpanProperty, 19);
                rectRow.Fill = new SolidColorBrush(Colors.Black);
                sudokuGrid.Children.Insert(0, rectRow);
            }

            // Cases
            squares = new Square[9, 9];
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    int gridCol = i * 2 + 1;
                    int gridRow = j * 2 + 1;

                    Square square = new Square();
                    square.SetValue(Grid.ColumnProperty, gridCol);
                    square.SetValue(Grid.RowProperty, gridRow);
                    sudokuGrid.Children.Add(square);
                    square.DataContext = SudokuGrid[i, j];
                    squares[i, j]      = square;
                    square.Click      += new RoutedEventHandler(square_Click);
                }
            }
        }
Пример #28
0
        static bool AppliesAt(Hint hint, int x, int y, SudokuGrid grid)
        {
            if (!(hint is ForcedMoveHint))
            {
                SudokuCandidate k = (SudokuCandidate)hint.Candidate;
                if (k != null)
                {
                    return(k.x == x && k.y == y);
                }
            }

            SudokuRequirement c = (SudokuRequirement)hint.Requirement;

            if (c != null)
            {
                return(c.AppliesAt(x, y, grid));
            }

            return(false);
        }
Пример #29
0
        public SudokuGrid Read(string filename)
        {
            try {
                _xDoc.Load(filename);

                SudokuGrid grid = new SudokuGrid(_xDoc);
                return(grid);
            } catch (Exception ex) {
                System.Windows.Forms.MessageBox.Show("Couldn't Load the Grid in " + filename + "-->" + ex.ToString());
            }
            SudokuGrid Grid = new SudokuGrid();

            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    Grid[row, col] = 0;
                }
            }
            return(Grid);
        }
Пример #30
0
        public SolveResult DoBacktrackingProof(SudokuGrid grid, TextWriter log)
        {
            //verbose = false;
            solnsFound = 0;
            int osc = tsc;

            BacktrackingProof(log);
            if (solnsFound == 0)
            {
                return(SolveResult.NoSolutions);
            }
            if (solnsFound == 1)
            {
                for (int i = osc; i < sampleSoln.Length; ++i)
                {
                    grid.SelectCandidate(sampleSoln[i]);
                }
                return(SolveResult.SingleSolution);
            }
            return(SolveResult.MultipleSolutions);
        }
Пример #31
0
        public void store_solution(Stack <DataNode> answer)
        {
            int[,] formatted_grid = new int[9, 9];
            var rows = new List <int>();

            foreach (var k in answer)
            {
                rows.Add(k.ID);
            }
            rows.Sort();
            var grid = new List <int>();

            foreach (var row in rows)
            {
                grid.Add(row % 9 + 1);
            }
            int x = 0;
            int y = 0;

            for (int i = 0; i < 81; i++)
            {
                formatted_grid[y, x] = grid[i];
                x++;
                if ((i + 1) % 9 == 0)
                {
                    y++;
                    x = 0;
                }
            }
            var sudoku = new SudokuGrid(formatted_grid);

            if (sudoku.Valid)
            {
                Final_Solution = sudoku;
            }
            else
            {
                Console.WriteLine("Something went wrong -- solution found did not validate.");
            }
        }
Пример #32
0
        public bool Move(Command move)
        {
            Player p = GetPlayer(move.Name);

            if (p == null)
            {
                return(false);
            }

            int x     = Convert.ToInt32(move.X);
            int y     = Convert.ToInt32(move.Y);
            int value = Convert.ToInt32(move.Value);

            if (!SudokuGrid.FillValue(x, y, value))
            {
                return(false);
            }

            AddAction(p, String.Format("move#{0}#{1}#{2}#{3}", p.Name, x, y, value));

            if (SudokuGrid.IsFinish)
            {
                Locker.EnterWriteLock();
                try
                {
                    Parent.Remove(this);
                }
                finally
                {
                    Locker.ExitWriteLock();
                }

                Command cmd = new Command(Parent, null, new string[] { "win", p.Name, this.Id.ToString() });
                cmd.Execute();

                AddAction(p, String.Format("win#{0}#{1}", p.Name, Id));
            }

            return(true);
        }
Пример #33
0
        public void solve_sudoku(SudokuGrid sudoku, string puzzle_name, string output_dir = "")
        {
            if (!sudoku.Valid)
            {
                throw new Exception(("Invalid Sudoku input."));
            }
            var watch = System.Diagnostics.Stopwatch.StartNew();

            var dlx = new DLX(new ColumnNode(-1));

            dlx.createLinkedList(sudoku.Grid);
            var algX = new AlgorithmX(dlx.h);

            algX.search();

            watch.Stop();

            SudokuGrid solution  = algX.Final_Solution;
            var        elapsedMs = watch.ElapsedMilliseconds;

            if (solution != null)
            {
                Console.WriteLine(string.Format("Puzzle \"{0}\" Solution:", puzzle_name));
                solution.print_grid();
                Console.WriteLine(string.Format("Puzzle \"{0}\" was solved in: {1} milliseconds", puzzle_name, elapsedMs));
                if (!String.IsNullOrWhiteSpace(output_dir))
                {
                    Directory.CreateDirectory(output_dir);
                    var    filename = string.Format("{0}.sln.txt", puzzle_name);
                    string path     = Path.Combine(output_dir, filename);
                    Console.WriteLine(String.Format("Your solved puzzle has been saved to the file: {0}", Path.GetFullPath(path)));
                    solution.Save_File(path);
                }
            }
            else
            {
                Console.WriteLine("Something went wrong and your puzzle could not be solved. Press any key to exit...");
                Console.ReadLine();
            }
        }
Пример #34
0
        public Generator(SudokuGrid.GridOptions options)
        {
            grid = new SudokuGrid(options);
            grid.Setup();

            desc = options.isJigsaw ? "Jigsaw" : options.isKiller ? "Killer" : "Normal";
            if (grid.MajorDiagonal && grid.MinorDiagonal)
            {
                desc += " Cross";
            }
            else if (grid.MajorDiagonal)
            {
                desc += " Major";
            }
            else if (grid.MinorDiagonal)
            {
                desc += " Minor";
            }
            desc += " " + options.Cells;

            new Thread(new ThreadStart(AutoGenerate)).Start();
        }
Пример #35
0
 public void LoadBlankPuzzle(int rank)
 {
     SudokuGrid grid = new SudokuGrid(new SudokuPuzzle() { Rank = rank }, SudokuPuzzleLoadOptions.Blank) { HorizontalAlignment = System.Windows.HorizontalAlignment.Center };
     this._currentPuzzleId = grid.Puzzle.Id;
     this.PuzzlePreviewContainer.Child = grid;
 }
Пример #36
0
 public SudokuSolver(SudokuGrid grid)
 {
     this.grid = grid;
     solutionFound = false;
 }
Пример #37
0
        private void InitCells(SudokuGrid grid)
        {
            //Initialize and set highlighted cell.
            CurrentCell = new SudokuCell(FirstCellRowPosition, FirstCellColPosition);
            CurrentCellRowIndex = 0;
            CurrentCellColIndex = 0;

            //Initialize other number fields.
            const int SudokuDim = SudokuGrid.SudokuDimension;
            cells = new SudokuCell[SudokuDim,SudokuDim];
            int currWindowRowPos = GameWindow.FirstCellRowPosition;
            int currWindowColPos = GameWindow.FirstCellColPosition;
            const int RowIncrement = GameWindow.CellPositionRowIncrements;
            const int ColIncrement = GameWindow.CellPositionColIncrements;

            for (int row = 0; row < SudokuDim; row++)
            {
                for (int col = 0; col < SudokuDim; col++)
                {
                    cells[row, col] = new SudokuCell(grid[row, col], grid.IsEditable(row, col), currWindowRowPos, currWindowColPos);
                    currWindowColPos += ColIncrement;
                }
                currWindowColPos = GameWindow.FirstCellColPosition;
                currWindowRowPos += RowIncrement;
            }

            //Initialize menu items
            menuCells = new MenuCell[MenuItemLabels.Length];
            for (int item = 0; item < menuCells.Length; item++)
            {
                menuCells[item] = new MenuCell(MenuItemsCellRowPosition, MenuItemsCellColPositions[item], MenuItemLabels[item]);
            }
            RedrawCells();
        }
Пример #38
0
            public static bool Solve(SudokuGrid grid, out List<string> solution)
            {
                int[,] g = new int[(grid.Puzzle.Rank * grid.Puzzle.Rank), (grid.Puzzle.Rank * grid.Puzzle.Rank)];

                for (int i = 0; i < (grid.Puzzle.Rank * grid.Puzzle.Rank); i++)
                {
                    for (int j = 0; j < (grid.Puzzle.Rank * grid.Puzzle.Rank); j++)
                    {
                        g[i, j] = grid.GetCell(i, j).Value.HasValue ? grid.GetCell(i, j).Value.Value : 0;
                    }
                }

                bool result = Solve(g, grid.Puzzle.Rank, 0, 0);

                if (result)
                {
                    // Set the the solution
                    solution = new List<string>();
                    for (int i = 0; i < (grid.Puzzle.Rank * grid.Puzzle.Rank); i++)
                    {
                        string line = string.Empty;
                        for (int j = 0; j < (grid.Puzzle.Rank * grid.Puzzle.Rank); j++)
                        {
                            if (!string.IsNullOrEmpty(line))
                            {
                                line += ("," + g[i, j].ToString());
                            }
                            else
                            {
                                line += g[i, j].ToString();
                            }
                        }
                        solution.Add(line);
                    }
                }
                else
                {
                    solution = grid.Puzzle.Format;
                }

                return result;
            }
Пример #39
0
        private void NewGame(SudokuGrid.Difficulty difficulty)
        {
            grid = SudokuGenerator.Generate(difficulty);

            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    cells[row, col].RefreshValues(grid[row, col], grid.IsEditable(row, col));
                }
            }
            RefreshCellValues();
        }
Пример #40
0
 public static bool Validate(int row, int col, int? value, SudokuGrid grid)
 {
     string message;
     return SudokuDuplicateRule.Validate(row, col, value, grid, out message);
 }
Пример #41
0
        public static bool Validate(int row, int col, int? value, SudokuGrid grid, out string message)
        {
            if (value == null)
            {
                message = null;
                return true;
            }

            if (grid.IsValueAvailable(row, col, value.Value))
            {
                message = null;
                return true;
            }
            else
            {
                message = "Invalid input. Duplicate value present.";
                return false;
            }
        }