Exemplo n.º 1
0
        public void SetBlockTest()
        {
            int[,] setBlockTestPuzzle = { { 1, 2, 0, 4 },
                                          { 3, 4, 0, 2 },
                                          { 2, 3, 0, 1 },
                                          { 4, 1, 0, 3 } };
            Sudoku sudoku = new Sudoku(setBlockTestPuzzle);

            sudoku.SetBlock(0, 2, 3);
            Assert.AreEqual(sudoku.AvailableValuesInRow(0).Count, 0);
            Assert.AreEqual(sudoku.AvailableValuesInColumn(2).Count, 3);
            Assert.AreEqual(sudoku.AvailableValuesInGrid(1).Count, 1);

            sudoku.SetBlock(1, 2, 1);
            Assert.AreEqual(sudoku.AvailableValuesInRow(1).Count, 0);
            Assert.AreEqual(sudoku.AvailableValuesInColumn(2).Count, 2);
            Assert.AreEqual(sudoku.AvailableValuesInGrid(1).Count, 0);

            sudoku.SetBlock(2, 2, 4);
            Assert.AreEqual(sudoku.AvailableValuesInRow(2).Count, 0);
            Assert.AreEqual(sudoku.AvailableValuesInColumn(2).Count, 0);
            Assert.AreEqual(sudoku.AvailableValuesInGrid(3).Count, 0);

            Assert.IsTrue(sudoku.Solved);
        }
Exemplo n.º 2
0
 public void EgalPlusValeurCTest_DoitReussir()
 {
     int[] TabRef = { 1, 0, 0, 0, 0, 1, 0, 0, 0 };
     int[,] GrilleTest =
     {
         { 1, 2, 3, 4, 5, 6, 7, 8, 0 },
         { 4, 5, 6, 0, 8, 0, 5, 4, 1 },
         { 7, 8, 0, 4, 0, 0, 6, 3, 2 },
         { 4, 9, 0, 6, 2, 1, 0, 0, 3 },
         { 5, 2, 7, 0, 0, 0, 1, 6, 4 },
         { 6, 0, 0, 5, 7, 4, 0, 9, 5 },
         { 7, 4, 5, 0, 0, 9, 7, 0, 6 },
         { 8, 3, 2, 0, 5, 0, 8, 4, 7 },
         { 0, 6, 1, 6, 5, 4, 3, 2, 1 }
     };     // A noter que la grille n'est pas une réelle grille de sudoku mais peut être utilisée pour un test unitaire.
     Sudoku.Sudoku  GrilleDeSudoku = new Sudoku.Sudoku(GrilleTest);
     Sudoku.Cellule Case           = new Sudoku.Cellule(0, 0, 0);
     for (int i = 1; i < Case.PropValPossibles.Length; i++)
     {
         Case.PropValPossibles[i] = 0;
     }
     Case.PropValPossibles[0] = 1;
     Case.PropValPossibles[5] = 1;
     Case.PropValPossibles[6] = 1;                                // Toutes les valeurs du champs de de la case sont nulles sauf 3, dont deux qui correspond à celles non nulles dans le tableau de reférence.
     Assert.IsTrue(GrilleDeSudoku.EgalPlusValeurC(Case, TabRef)); // Donc le test réussi, il n'y a qu'une seule valeur C en plus de A et B.
 }
Exemplo n.º 3
0
        public void ConstructorTests()
        {
            Sudoku sudoku = new Sudoku(testPuzzle);

            Assert.AreEqual(sudoku.GridSize, 9);
            Assert.AreEqual(sudoku.NumBlocksUnknown, 45);
            Assert.IsFalse(sudoku.Solved);
        }
Exemplo n.º 4
0
 public SudokuForm()
 {
     InitializeComponent();
     sdk = new Sudoku();
     this.dataGridViewSudoku.Rows.Add(9);
     this.dataGridViewAnswer.Rows.Add(9);
     this.dataGridViewAnswer.Visible = false;
     //this.textBoxResult.Visible = false;
 }
Exemplo n.º 5
0
        public void AvailableValuesInRowTest()
        {
            Sudoku sudoku = new Sudoku(testPuzzle);
            var expectedValues = new List<int>() { 1, 2, 5, 6 };

            var vals = sudoku.AvailableValuesInRow(0);
            Assert.AreEqual(vals.Count, 4);
            foreach (var val in vals)
            {
                Assert.IsTrue(expectedValues.Contains(val));
            }
        }
Exemplo n.º 6
0
        public void AvailableValuesInColumnTest()
        {
            Sudoku sudoku = new Sudoku(testPuzzle);
            var expectedValues = new List<int>() { 2, 3, 5, 6, 7, 8, 9 };

            var vals = sudoku.AvailableValuesInColumn(4);
            Assert.AreEqual(vals.Count, 7);
            foreach (var val in vals)
            {
                Assert.IsTrue(expectedValues.Contains(val));
            }
        }
Exemplo n.º 7
0
        public void SolveAFile(string filePath)
        {
            string line;

            System.IO.StreamReader file =
                new System.IO.StreamReader(filePath);

            int currentLineIndex = 0;

            while ((line = file.ReadLine()) != null)
            {
                string[] sudokulineElements = line.Split(',');

                string inputProblem     = sudokulineElements[0];
                string expectedSolution = sudokulineElements[1];


                Sudoku.Sudoku sudoku = new Sudoku.Sudoku(inputProblem);



                //RenderNewEntries(sudoku, Color.Black);

                //MessageBox.Show($"Problem {counter} loaded from DB. Click to Solve ");

                bool   isSovled = sudoku.Solve();
                string solution = sudoku.ToString();

                if (isSovled)
                {
                    if (!solution.Equals(expectedSolution))
                    {
                        throw new Exception($"Sudoku solution does not match input solution excped: {expectedSolution}.\n Actual {solution}");
                    }
                    Console.WriteLine("Solved a Problem. Rating=" + sudoku.DifficultyRating);
                }
                else
                {
                    throw new Exception($"Sudoku could not be solved. Incompelete solution is {solution} expected solution was {expectedSolution}");
                }



                currentLineIndex++;
            }

            file.Close();
        }
Exemplo n.º 8
0
 public void UneSeuleValeurLigneTest_DoitReussir()
 {
     int[,] GrilleTest =
     {
         { 1, 2, 3, 4, 5, 6, 7, 8, 0 },
         { 0, 1, 9, 0, 8, 0, 5, 4, 1 },
         { 0, 0, 8, 4, 0, 0, 6, 3, 2 },
         { 5, 9, 0, 6, 2, 1, 0, 0, 3 },
         { 0, 2, 7, 0, 0, 0, 1, 6, 4 },
         { 0, 0, 0, 5, 7, 4, 0, 9, 5 },
         { 0, 8, 5, 0, 0, 9, 7, 0, 6 },
         { 9, 3, 0, 0, 5, 0, 8, 4, 7 },
         { 0, 0, 2, 0, 6, 0, 0, 0, 8 }
     };     // A noter que la grille n'est pas une réelle grille de sudoku mais peut être utilisée pour un test unitaire.
     Sudoku.Sudoku GrilleDeSudoku = new Sudoku.Sudoku(GrilleTest);
     GrilleDeSudoku.ReInitialiseTableauPossiblesAChaqueCellule();
     Assert.AreEqual(GrilleDeSudoku.UneSeuleValeurLigne(0, 8), 9); // Pour la ligne 0 et colonne 8, seule la valeur 9 est possible, on a bien 9 en paramètre, le test est réussi.
 }
Exemplo n.º 9
0
 public void UneSeuleValeurColonneTest_DoitEchouer()
 {
     int[,] GrilleTest =
     {
         { 1, 2, 3, 4, 5, 6, 7, 8, 0 },
         { 2, 1, 9, 0, 8, 0, 5, 4, 1 },
         { 3, 0, 8, 4, 0, 0, 6, 3, 2 },
         { 4, 9, 0, 6, 2, 1, 0, 0, 3 },
         { 5, 2, 7, 0, 0, 0, 1, 6, 4 },
         { 6, 0, 0, 5, 7, 4, 0, 9, 5 },
         { 7, 4, 5, 0, 0, 9, 7, 0, 6 },
         { 8, 3, 2, 0, 5, 0, 8, 4, 7 },
         { 0, 6, 1, 6, 5, 4, 3, 2, 1 }
     };     // A noter que la grille n'est pas une réelle grille de sudoku mais peut être utilisée pour un test unitaire.
     Sudoku.Sudoku GrilleDeSudoku = new Sudoku.Sudoku(GrilleTest);
     GrilleDeSudoku.ReInitialiseTableauPossiblesAChaqueCellule();
     Assert.AreEqual(GrilleDeSudoku.UneSeuleValeurColonne(8, 0), 3); // Pour la ligne 8 et colonne 0, seule la valeur 9 est possible, le test échoue à cause de la valeur 3 en paramètre.
 }
Exemplo n.º 10
0
        public void zGeneralTests()
        {
            var values = @"004300209005009001070060043006002087190007400050083000600000105003508690042910300";

            Regex regularExpression = new Regex("[^0-9]");


            string result = regularExpression.Replace(values, "");

            Sudoku.Sudoku cloneWithSortedCells = new Sudoku.Sudoku(result);

            cloneWithSortedCells.EliminatePossibilitiesFromUnsetCells();
            cloneWithSortedCells.EliminatePossibilitiesFromUnsetCells();

            SudokuCell[][] cells = cloneWithSortedCells.GetSudokuCellsCopy();

            SudokuCell[] linearArray = new SudokuCell[81];

            for (int rowIndex = 0; rowIndex <= 8; rowIndex++)
            {
                for (int colIndex = 0; colIndex <= 8; colIndex++)
                {
                    linearArray[rowIndex * 9 + colIndex] = cells[rowIndex][colIndex];
                }
            }

            Array.Sort(linearArray);


            for (int index = 0; index < linearArray.Length; index++)
            {
                if (linearArray[index].Value == 0)
                {
                    Console.Write($"({linearArray[index].RemainingPossibilities.Count}) ");
                }
            }
        }
Exemplo n.º 11
0
 public void EgalPlusValeurCTest_DoitEchouer()
 {
     int[] TabRef = { 1, 0, 0, 0, 0, 1, 0, 0, 0 };
     int[,] GrilleTest =
     {
         { 1, 2, 3, 4, 5, 6, 7, 8, 0 },
         { 4, 5, 6, 0, 8, 0, 5, 4, 1 },
         { 7, 8, 0, 4, 0, 0, 6, 3, 2 },
         { 4, 9, 0, 6, 2, 1, 0, 0, 3 },
         { 5, 2, 7, 0, 0, 0, 1, 6, 4 },
         { 6, 0, 0, 5, 7, 4, 0, 9, 5 },
         { 7, 4, 5, 0, 0, 9, 7, 0, 6 },
         { 8, 3, 2, 0, 5, 0, 8, 4, 7 },
         { 0, 6, 1, 6, 5, 4, 3, 2, 1 }
     };     // A noter que la grille n'est pas une réelle grille de sudoku mais peut être utilisée pour un test unitaire.
     Sudoku.Sudoku  GrilleDeSudoku = new Sudoku.Sudoku(GrilleTest);
     Sudoku.Cellule Case           = new Sudoku.Cellule(0, 0, 0);
     for (int i = 0; i < Case.PropValPossibles.Length; i++)
     {
         Case.PropValPossibles[i] = 1;
     }
     // Toutes les valeurs du champs de de la case sont vallent 1.
     Assert.IsTrue(GrilleDeSudoku.EgalPlusValeurC(Case, TabRef)); // Donc le champs contient A et B mais aussi pleins d'autres valeurs, le test échoue.
 }
Exemplo n.º 12
0
        public void GenerateGame()
        {
            if (PlaySound != null)
            {
                PlaySound(SudokuSound.Stop);
            }

            UseTemplate();

            int trials_counter = 0;

            int trials_max = 100;

            SolveMethods M = SolveMethods.All;

            // Generating a list of filled squares

            List <Point> L = new List <Point>();

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (s[j, i] > 0)
                    {
                        L.Add(new Point(i, j));
                    }
                }
            }

            int n;

            for (n = 0; n < 55;)
            {
                int index = R.Next(L.Count);

                int x = L[index].X;

                int y = L[index].Y;

                int temp = s[x, y];

                if (temp != 0)
                {
                    s[x, y] = 0;

                    Sudoku S2 = CreateCopy();

                    int solutionStepsCount = S2.ComputePossibleSteps(M).Count();

                    bool range0Ok = ((n > 35) && (solutionStepsCount > 25));

                    bool range1Ok = ((n > 15) && (solutionStepsCount > 25));

                    bool range2Ok = n < 16;

                    bool solutionStepsCountOk = range0Ok || range1Ok || range2Ok;

                    if (solutionStepsCountOk)
                    {
                        bool isSolvable = S2.SolvePuzzle(M);

                        if (isSolvable)
                        {
                            L.RemoveAt(index);

                            n++;

                            trials_counter = 0;
                        }
                        else
                        {
                            s[x, y] = temp;
                        }
                    }
                    else
                    {
                        s[x, y] = temp;
                    }
                    trials_counter++;
                }

                if (trials_counter > trials_max)
                {
                    break;
                }
            }

            ScrambleGame();

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (s[i, j] == 0)
                    {
                        f[i, j] = 0;
                    }
                    else
                    {
                        f[i, j] = 1;
                    }
                }
            }

            //  SetGameString("XX7XXX5XXXXXX4XX3XXXX832X9X8XXXXX4XXX294X586XXX6XXXXX7X5X364XXXX7XX5XXXXXX3XXX2XX");

            EnumeratePossibilities();

            starttime = DateTime.Now;

            DisplayMessage = false;

            if (PlaySound != null)
            {
                PlaySound(SudokuSound.NewPuzzle);
            }

            if (RequestRepaint != null)
            {
                RequestRepaint();
            }
        }
Exemplo n.º 13
0
        private bool SolveByTryingPossibilities()
        {
            if (!IsAValidState())
            {
                return(false);
            }

            int unsolvedCells = CountUnsolvedCells();

            if (unsolvedCells == 0)
            {
                return(Solved);
            }


            SudokuCell[] linearArray = new SudokuCell[81];

            for (int rowIndex = 0; rowIndex <= 8; rowIndex++)
            {
                for (int colIndex = 0; colIndex <= 8; colIndex++)
                {
                    linearArray[rowIndex * 9 + colIndex] = sudokuCells[rowIndex][colIndex];
                }
            }
            //Sorted array by remaining possibilities.
            Array.Sort(linearArray);



            foreach (var cell in linearArray)
            {
                int rowIndex = cell.RowIndex;
                int colIndex = cell.ColIndex;

                if (cell.Value == 0)
                {
                    var remainingDigitsOnThisCell = cell.RemainingPossibilities;

                    if (remainingDigitsOnThisCell.Count == 0)
                    {
                        Logger.WriteLine("Invalid situation. remainingDigitsOnThisCell.Count == 0 ", _cloningDepth);
                        return(false);
                    }

                    //if (cloningDepth == 0)
                    {
                        Logger.WriteLine($"Evaluating Cell@{cell} ", _cloningDepth);
                        Logger.WriteLine(ToStringFormatted(), _cloningDepth);
                    }

                    foreach (var possibility in remainingDigitsOnThisCell)
                    {
                        //Set this possibility and try to solve.
                        Sudoku clone = new Sudoku(this.ToString());
                        clone._cloningDepth = this._cloningDepth + 1;

                        clone.sudokuCells[rowIndex][colIndex].Value = possibility;

                        if (clone.Solve())
                        {
                            //if (cloningDepth == 0)
                            {
                                Logger.WriteLine($"Valid Solution found for Cell@{cell}  new Value {possibility}", _cloningDepth);
                                Logger.WriteLine($"\n{clone.ToStringFormatted()}", _cloningDepth);
                            }

                            cell.SolvingDifficulty = SolvingDifficulty.MaxDifficulty;
                            cell.Value             = possibility;

                            CopyUnSolvedCellsFromSolution(clone);

                            return(Solved);
                        }
                    }

                    if (_cloningDepth == 0)
                    {
                        throw new Exception("No possibility worked. Root problem is not right");
                    }

                    Logger.WriteLine($"No possibility worked for  Cell@{cell}. Impossible situation. Should be backtraced.", _cloningDepth);

                    return(Notsolved);
                }
            }



            return(Notsolved);
        }
Exemplo n.º 14
0
 static void Main(string[] args)
 {
     Sudoku.Run(args);
 }
Exemplo n.º 15
0
 /// The main entry point for the application.
 static void Main(string[] args)
 {
     using (Sudoku game = new Sudoku()) {
         game.Run();
     }
 }
Exemplo n.º 16
0
 private void button1_Click(object sender, EventArgs e)
 {
     Sudoku.Solve();
 }
Exemplo n.º 17
0
 private void SolverToolStripMenuItem_Click(object sender, EventArgs e)
 {
     DialogResult EstaSeguro = MessageBox.Show("Esta seguro que desea resolver el sudoku actual? No podra terminarlo una vez haya confirmado."
         , "Resolver Sudoku?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
     if (EstaSeguro == DialogResult.Yes)
     {
         Sudoku ToBeSolved;
         List<int> Fields = new List<int>();
         for (int i = 0; i < 9; i++)
         {
             for (int j = 0; j < 9; j++)
             {
                 if (Texts[i][j].Text == "")
                     Fields.Add(0);
                 else
                     Fields.Add(int.Parse(Texts[i][j].Text));
             }
         }
         ToBeSolved = new Sudoku(Fields);
         SudokuSolver Solver = new SudokuSolver();
         Sudoku Result = Solver.Solve(ToBeSolved, false, 4);
         Resolviendo = true;
         Display(Result);
         Resolviendo = false;
         SolverToolStripMenuItem.Enabled = false;
     }
     else
     {
         MessageBox.Show("Adelante no te desesperes, todavia se puede!", "Tu puedes", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Exemplo n.º 18
0
 public Sudoku Resolver(Sudoku ToBeSolved)
 {
     SudokuSolver Solver = new SudokuSolver();
     Sudoku Result = Solver.Solve(ToBeSolved, false, 4);
     return Result;
 }
Exemplo n.º 19
0
 public Sudoku(Sudoku instance)
 {
     array = (byte[, ])instance.array.Clone();
 }
Exemplo n.º 20
0
        public SudokuCell[][] GetSudokuCellsCopy()
        {
            Sudoku clone = new Sudoku(ToString());

            return(clone.sudokuCells);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Takes action according to the keyboard button pressed.
        ///  - If it is a number from numpad or from the main keyboard,
        ///         it writes it down or overwrites the current number in that field.
        ///  - If it is up/down/left/right/tab/enter,
        ///         it selects the respective cell.
        ///  - If it is escape/backspace or delete,
        ///         it deletes the value in the cell.
        ///  - Else, it doesn't do anything.
        ///  - It checks if the grid has been solved,
        ///         and prompts a window according to the result.
        ///  - If the grid is full but it isn't a valid solution to the game,
        ///         it doesn't do anything.
        ///  - If the grid is solved but the time does not make it in the top 5,
        ///         it prompts a MessageBox
        ///  - If the grid is solved AND the time makes it in the top 5,
        ///         it prompts a new form, that asks for the player's name
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (standard == null && squiggly == null)
            {
                System.Media.SystemSounds.Asterisk.Play();
                return;
            }
            if (dataGridView.SelectedCells.Count > 0)
            {
                var selected = dataGridView.SelectedCells[0];
                int sel_i    = selected.RowIndex;
                int sel_j    = selected.ColumnIndex;
                if (CellMap[sel_i, sel_j] == LOCKED)
                {
                    if (!(e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right))
                    {
                        System.Media.SystemSounds.Asterisk.Play();
                    }

                    return;
                }
                if (!(e.KeyValue >= 49 && e.KeyValue <= 57 || e.KeyValue >= 97 && e.KeyValue <= 105))
                {
                    if (e.KeyValue == 27 || e.KeyValue == 8 || e.KeyValue == 46)   // Same as e.KeyCode == Keys.Enter  etc.
                    {
                        selected.Value = "";
                        if (standard != null)
                        {
                            standard.userGrid[selected.RowIndex, selected.ColumnIndex] = 0;
                        }
                        else
                        {
                            squiggly.userGrid[selected.RowIndex, selected.ColumnIndex] = 0;
                        }
                    }
                    else if (!(e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right))
                    {
                        System.Media.SystemSounds.Asterisk.Play();
                    }
                }
                else
                {
                    int value = -1;
                    if (e.KeyValue >= 49 && e.KeyValue <= 57)
                    {
                        selected.Value = e.KeyValue - 48;
                        value          = e.KeyValue - 48;
                    }
                    else
                    {
                        selected.Value = e.KeyValue - 96;
                        value          = e.KeyValue - 96;
                    }

                    if (standard != null)
                    {
                        standard.userGrid[sel_i, sel_j] = value;
                    }
                    else if (squiggly != null)
                    {
                        squiggly.userGrid[sel_i, sel_j] = value;
                    }

                    highlightSelectedNumber();
                }
            }

            if ((standard != null && Sudoku.isSolved(standard.userGrid, Standard.scheme)) ||
                (squiggly != null && Sudoku.isSolved(squiggly.userGrid, squiggly.scheme)))
            {
                long time = ticks;
                timer.Stop();
                DarkenGrid();
                //MessageBox.Show("Congratulations!!!");
                System.Media.SoundPlayer finishSoundPlayer          = new System.Media.SoundPlayer(@"C:\Windows\Media\tada.wav");
                System.Media.SoundPlayer finish_no_high_SoundPlayer = new System.Media.SoundPlayer(@"C:\Windows\Media\chimes.wav");
                gameType   type  = standard == null ? gameType.Squiggly : gameType.Standard;
                Difficulty level = standard == null ? squiggly.diff : standard.diff;
                int        d     = level == Difficulty.Easy ? 0 : (level == Difficulty.Medium ? 1 : 2);
                SaveScoreHasAppeared = true;
                if (HS.HS[type][d].highScores.Count == 5 && ticks > HS.HS[type][d].highScores[4].time)
                {
                    finish_no_high_SoundPlayer.Play();
                    MessageBox.Show("\t\tCongratulations!!! \n I'm sorry but you didn't make it in the top 5.");
                }
                else
                {
                    finishSoundPlayer.Play();
                    Form2 form2 = new Form2(this, ticks, type, level);
                    form2.Show();
                    form2.name.Focus();
                }
                standard = null;
                squiggly = null;
                sudoku   = null;
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// This is used to create a new game object, according to the given parameters,
        /// to fill the dataGridView with the starting values,
        /// and to update the text shown on the form.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="level"></param>
        public void setGrid(gameType type, Difficulty level)
        {
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    dataGridView.Rows[i].Cells[j].Value = "";
                }
            }
            if (standard != null || type == gameType.Standard)
            {
                if (standard == null)
                {
                    squiggly = null;
                    standard = new Standard(level);
                    sudoku   = standard;
                }
                for (int i = 0; i < 9; i++)
                {
                    for (int j = 0; j < 9; j++)
                    {
                        if (standard.mask[i, j] != 0)
                        {
                            dataGridView.Rows[i].Cells[j].Value = standard.mask[i, j];
                        }
                        ColorMap[i, j] = Color.White;
                    }
                }
                this.Text += " - Standard " + (standard.diff == Difficulty.Easy ? "(easy) " : (standard.diff == Difficulty.Medium ? "(medium)" : "(hard)"));
            }
            else
            {
                if (squiggly == null)
                {
                    standard = null;
                    schemeBuilder();

                    Random random = new Random();
                    squiggly = null;
                    bool Completed = false;
                    while (squiggly == null && !Completed)
                    {
                        squiggly = Limex(() => new Squiggly(level, Schemes[random.Next(0, Schemes.Count)]), 4000, out Completed);
                        sudoku   = squiggly;
                    }
                }
                for (int i = 0; i < 9; i++)
                {
                    for (int j = 0; j < 9; j++)
                    {
                        if (squiggly.mask[i, j] != 0)
                        {
                            dataGridView.Rows[i].Cells[j].Value = squiggly.mask[i, j];
                        }
                        dataGridView.Rows[i].Cells[j].Style.BackColor = colors[squiggly.scheme[i, j]];
                        ColorMap[i, j] = colors[squiggly.scheme[i, j]];
                    }
                }
                this.Text += " - Squiggly " + (squiggly.diff == Difficulty.Easy ? "(easy) " : (squiggly.diff == Difficulty.Medium ? "(medium)" : "(hard)"));
            }
            LockCellMap();
        }
Exemplo n.º 23
0
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (modoDeJuego == null)
            {
                System.Media.SystemSounds.Asterisk.Play();
                return;
            }
            if (dataGridView1.SelectedCells.Count > 0)
            {
                var selected = dataGridView1.SelectedCells[0];
                int sel_i    = selected.RowIndex;
                int sel_j    = selected.ColumnIndex;
                if (CellMap[sel_i, sel_j] == LOCKED)
                {
                    if (!(e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right))
                    {
                        System.Media.SystemSounds.Asterisk.Play();
                    }

                    return;
                }
                if (!(e.KeyValue >= 49 && e.KeyValue <= 57 || e.KeyValue >= 97 && e.KeyValue <= 105))
                {
                    if (e.KeyValue == 27 || e.KeyValue == 8 || e.KeyValue == 46)                       // Same as e.KeyCode == Keys.Enter  etc.
                    {
                        selected.Value = "";
                        if (modoDeJuego != null)
                        {
                            modoDeJuego.grillaUsuario[selected.RowIndex, selected.ColumnIndex] = 0;
                        }
                    }
                    else if (!(e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right))
                    {
                        System.Media.SystemSounds.Asterisk.Play();
                    }
                }
                else
                {
                    int value = -1;
                    if (e.KeyValue >= 49 && e.KeyValue <= 57)
                    {
                        selected.Value = e.KeyValue - 48;
                        value          = e.KeyValue - 48;
                    }
                    else
                    {
                        selected.Value = e.KeyValue - 96;
                        value          = e.KeyValue - 96;
                    }

                    if (modoDeJuego != null)
                    {
                        modoDeJuego.grillaUsuario[sel_i, sel_j] = value;
                    }


                    highlightSelectedNumber();
                }
            }

            if ((modoDeJuego != null && Sudoku.estaResuelto(modoDeJuego.grillaUsuario, ModoDeJuego.esquema)))
            {
                timer1.Stop();
                ColorearAVerde();
                MessageBox.Show("FELICITACIONES ! NIVEL : " + dificultadElegida + " SUPERADO");


                modoDeJuego = null;

                sudoku = null;
            }
        }
Exemplo n.º 24
0
 private int[,] GetSudokuGrid(Sudoku sudoku)
 {
     return(GetSudokuGrid(sudoku, true));
 }
Exemplo n.º 25
0
 public SudokuForm(int fieldsPerRow, Difficulty difficulty, bool diagonalRows, bool randomBoxFormation)
 {
     InitializeComponent();
     this.CurrentSudoku = new Sudoku(9, difficulty, diagonalRows, false);
     PrepareControls();
 }
Exemplo n.º 26
0
        public bool checkSolvable(SolveMethods M)
        {
            Sudoku copy = CreateCopy();

            return(copy.SolvePuzzle(M));
        }
Exemplo n.º 27
0
 private void BruteForce(List<Sudoku.Field> ToDo, int pos, Sudoku Temp)
 {
     // the brute force implementation for creating complete sudokus
     if (Finished)
         return;
     for (int i = 1; i <= 9; i++)
     {
         Sudoku Copied = Temp.Copy();
         Copied.Fields[ToDo[pos].i][ToDo[pos].j].Filled = true;
         Copied.Fields[ToDo[pos].i][ToDo[pos].j].Value = Rnd.Next(1, 10);
         bool Valid = true;
         foreach (Sudoku.Field f in Copied.GetGroup(ToDo[pos].i, ToDo[pos].j))
         {
             if (f.Filled && f.Value == Copied.Fields[ToDo[pos].i][ToDo[pos].j].Value)
             {
                 Valid = false;
                 break;
             }
         }
         if (Valid)
         {
             if (pos < ToDo.Count - 1)
                 BruteForce(ToDo, pos + 1, Copied);
             else
             {
                 Finished = true;
                 Result = Copied;
             }
         }
     }
 }
Exemplo n.º 28
0
 private void Display(Sudoku suk)
 {
     if (suk != null)
     {
         SolverToolStripMenuItem.Enabled = true;
         SolverToolStripMenuItem.Visible = true;
     }
     for (int i = 0; i < 9; i++)
     {
         for (int j = 0; j < 9; j++)
         {
             if (suk != null)
             {
                 if (suk.Fields[i][j].Value == 0)
                 {
                     Texts[i][j].Text = "";
                     Texts[i][j].ReadOnly = false;
                     Texts[i][j].ForeColor = Color.Black;
                     Texts[i][j].BackColor = Color.White;
                 }
                 else if(Resolviendo)
                 {
                     Texts[i][j].Text = suk.Fields[i][j].Value.ToString();
                     Texts[i][j].ReadOnly = true;
                 }
                 else
                 {
                     Texts[i][j].Text = suk.Fields[i][j].Value.ToString();
                     Texts[i][j].ReadOnly = true;
                     Texts[i][j].BackColor = Color.Gray;
                     Texts[i][j].ForeColor = Color.White;
                 }
             }
             else
             {
                 if (Creando)
                 {
                     Texts[i][j].ReadOnly = false;
                     Texts[i][j].Text = "";
                     Texts[i][j].ForeColor = Color.White;
                     Texts[i][j].BackColor = Color.Aqua;
                 }
                 else
                 {
                     MessageBox.Show("Se ha producido un error al crear el sudoku, el juego se cerrara", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     this.Close();
                 }
             }
         }
     }
 }
Exemplo n.º 29
0
        public Sudoku CreateRandomSudoku(int Difficulty, int targetdels)
        {
            bool Start = true;

            bool Done = false;
            int Deleted = 0;
            int Tolerance = 10;

            // Various counters, we count the iterations we do in case the created instance somehow gets stuck, then we reset
            int FieldDelCounter = 0;
            int ResetCounter1 = 0;
            int ResetCounter2 = 0;
            Sudoku NewSudoku = null;
            Sudoku Fallback = null;
            int FallbackCounter = 0;

            while (!Done)
            {
                if (ResetCounter1 > 40)
                {
                    ResetCounter1 = 0;
                    Start = true;
                }
                if (ResetCounter2 > 40)
                {
                    ResetCounter2 = 0;
                    Start = true;
                }

                if (Start)
                {
                    // first, create a complete sudoku using brute force
                    NewSudoku = new Sudoku(new List<int>());
                    List<Sudoku.Field> ToDo = new List<Sudoku.Field>();
                    for (int i = 0; i < 9; i++)
                    {
                        for (int j = 0; j < 9; j++)
                        {
                            ToDo.Add(NewSudoku.Fields[i][j]);
                        }
                    }
                    Rnd = new Random();
                    Finished = false;
                    BruteForce(ToDo, 0, NewSudoku);
                    FallbackCounter = 0;
                    NewSudoku = Result.Copy();
                    Start = false;
                    Fallback = null;
                }

                Sudoku Cloned = NewSudoku.Copy();
                int difficulty = Difficulty;
                // take out one field and check if solutions still is unique and not harder than desired
                if (DeleteField(Cloned, ref difficulty))
                {
                    NewSudoku = Cloned;
                    Deleted++;

                    if (NewSudoku.Difficulty == Difficulty && Deleted >= targetdels)
                    {   // in this case we are done
                        NewSudoku.Difficulty = difficulty;
                        return NewSudoku;
                    }
                    else if (difficulty == Difficulty && Deleted < targetdels)
                    { // matching difficulty found but more fields have to be deleted
                        Fallback = NewSudoku.Copy();
                    }
                    else if (Deleted >= targetdels + Tolerance) // enough fields deleted but not desired difficulty
                    {
                        if (FallbackCounter < 100 && Fallback != null) // first try fallback
                        {
                            NewSudoku = Fallback.Copy();
                        }
                        else
                        {
                            NewSudoku = Result.Copy();
                            ResetCounter1++;
                            FallbackCounter = 0;
                        }
                        Deleted = 0;

                    }
                }
                else
                {
                    FieldDelCounter++;
                    if (FieldDelCounter > 100) // probably no more field can be deleted to get the desired difficulty
                    {
                        FieldDelCounter = 0;
                        NewSudoku = Result.Copy();
                        Deleted = 0;
                        ResetCounter2++;
                    }
                    continue;
                }
            }

            return Result;
        }
Exemplo n.º 30
0
 private void terminarToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (noHayErrores())
     {
         Sudoku OwnSudoku = new Sudoku(Texts);
         if (sePuedeResolver(OwnSudoku))
         {
             Display(OwnSudoku);
             terminarToolStripMenuItem.Visible = false;
             terminarToolStripMenuItem.Enabled = false;
             SolverToolStripMenuItem.Enabled = true;
             SolverToolStripMenuItem.Visible = true;
             generateOneToolStripMenuItem.Enabled = true;
             Creando = false;
         }
         else
         {
             MessageBox.Show("Lo hiciste tan dificil que no se puede resolver.", "Ops...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
     }
     else
         MessageBox.Show("Tienes errores con los numeros, revisa los cuadros rojos", "Errores", MessageBoxButtons.OK, MessageBoxIcon.Warning);
 }
Exemplo n.º 31
0
 // Constructor
 //
 public SudokuSolver(int[,] puzzle)
 {
     this.puzzle = new Sudoku(puzzle);
 }
Exemplo n.º 32
0
 public Boolean sePuedeResolver(Sudoku ToBeSolved)
 {
     SudokuSolver Solver = new SudokuSolver();
     Sudoku Result = Solver.Solve(ToBeSolved, false, 4);
     if (Result != null)
         return true;
     else
         return false;
 }
Exemplo n.º 33
0
 private void BruteForce(List<Sudoku.Field> ToDo, int pos, Sudoku Temp, bool count)
 {
     if (Finished)
         return;
     for (int i = 0; i < ToDo[pos].Candidates.Count; i++)
     {
         Sudoku Copied = Temp.Copy();
         Copied.Fields[ToDo[pos].i][ToDo[pos].j].Filled = true;
         Copied.Fields[ToDo[pos].i][ToDo[pos].j].NewFound = false;
         // place a random value and ...
         Copied.Fields[ToDo[pos].i][ToDo[pos].j].Value = ToDo[pos].Candidates[i];
         bool Valid = true;
         // ... check if solution is still valid
         foreach (Sudoku.Field f in Copied.GetGroup(ToDo[pos].i, ToDo[pos].j))
         {
             if (f.Filled && f.Value == Copied.Fields[ToDo[pos].i][ToDo[pos].j].Value)
             {
                 Valid = false;
                 break;
             }
         }
         if (Valid)
         {   // if yes, go to the next position
             if (pos % 5 == 0)
                 Grade0();
             if (pos < ToDo.Count - 1)
                 BruteForce(ToDo, pos + 1, Copied, count);
             else
             {   // or otherwise, we are done
                 if (!count)
                 {
                     Finished = true;
                     Input = Copied;
                     Remaining = 0;
                 }
                 else
                 {   // if we want to count the solutions, we do not stop after having found the first one
                     SolCounter++;
                     Remaining = 0;
                     if (SolCounter > 1)
                     {
                         Finished = true;
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 34
0
        public void NewGame()
        {
            int level;

            // Level
            if (rb_easy.IsChecked == true)
            {
                level = 55;
            }
            else if (rb_medium.IsChecked == true)
            {
                level = 30;
            }
            else if (rb_hard.IsChecked == true)
            {
                level = 0;
            }
            else
            {
                level = 30;
            }

            input = Sudoku.Create(level);
            int counter = 0;
            int solved  = 0;

            Sudoku.Solve(0, 0, 0, input[0], ref counter, ref solved, 0);

            List <TextBox> TextBox = new List <TextBox>();

            TextBox.Add(tb_1); TextBox.Add(tb_2); TextBox.Add(tb_3); TextBox.Add(tb_4); TextBox.Add(tb_5); TextBox.Add(tb_6); TextBox.Add(tb_7); TextBox.Add(tb_8); TextBox.Add(tb_9);
            TextBox.Add(tb_10); TextBox.Add(tb_11); TextBox.Add(tb_12); TextBox.Add(tb_13); TextBox.Add(tb_14); TextBox.Add(tb_15); TextBox.Add(tb_16); TextBox.Add(tb_17); TextBox.Add(tb_18);
            TextBox.Add(tb_19); TextBox.Add(tb_20); TextBox.Add(tb_21); TextBox.Add(tb_22); TextBox.Add(tb_23); TextBox.Add(tb_24); TextBox.Add(tb_25); TextBox.Add(tb_26); TextBox.Add(tb_27);
            TextBox.Add(tb_28); TextBox.Add(tb_29); TextBox.Add(tb_30); TextBox.Add(tb_31); TextBox.Add(tb_32); TextBox.Add(tb_33); TextBox.Add(tb_34); TextBox.Add(tb_35); TextBox.Add(tb_36);
            TextBox.Add(tb_37); TextBox.Add(tb_38); TextBox.Add(tb_39); TextBox.Add(tb_40); TextBox.Add(tb_41); TextBox.Add(tb_42); TextBox.Add(tb_43); TextBox.Add(tb_44); TextBox.Add(tb_45);
            TextBox.Add(tb_46); TextBox.Add(tb_47); TextBox.Add(tb_48); TextBox.Add(tb_49); TextBox.Add(tb_50); TextBox.Add(tb_51); TextBox.Add(tb_52); TextBox.Add(tb_53); TextBox.Add(tb_54);
            TextBox.Add(tb_55); TextBox.Add(tb_56); TextBox.Add(tb_57); TextBox.Add(tb_58); TextBox.Add(tb_59); TextBox.Add(tb_60); TextBox.Add(tb_61); TextBox.Add(tb_62); TextBox.Add(tb_63);
            TextBox.Add(tb_64); TextBox.Add(tb_65); TextBox.Add(tb_66); TextBox.Add(tb_67); TextBox.Add(tb_68); TextBox.Add(tb_69); TextBox.Add(tb_70); TextBox.Add(tb_71); TextBox.Add(tb_72);
            TextBox.Add(tb_73); TextBox.Add(tb_74); TextBox.Add(tb_75); TextBox.Add(tb_76); TextBox.Add(tb_77); TextBox.Add(tb_78); TextBox.Add(tb_79); TextBox.Add(tb_80); TextBox.Add(tb_81);

            int k = 0;

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (input[0][i, j] == 0)
                    {
                        TextBox[k].Text       = Convert.ToString("");
                        TextBox[k].Background = Brushes.Transparent;
                        k++;
                    }
                    else
                    {
                        TextBox[k].Text       = Convert.ToString(input[0][i, j]);
                        TextBox[k].Background = Brushes.Transparent;
                        k++;
                    }
                }
            }
        }
Exemplo n.º 35
0
        public static int[][,] Create(int fieldsLeft)
        {
            int zeile, spalte, n, solved, counter, selectedIndependentBlocks;

            int[,] OutputField       = new int[9, 9];
            int[,] SolvedGame        = new int[9, 9];
            int[,] tmp               = new int[9, 9];
            int[,] independentBlocks = new int[6, 3] {
                { 0, 30, 60 }, { 0, 33, 57 }, { 3, 27, 60 }, { 3, 33, 54 }, { 6, 30, 54 }, { 6, 27, 57 }
            };
            int[] ShuffeledArray;

            selectedIndependentBlocks = rnd.Next(5);
            counter = 0;
            solved  = 0;

            for (int currentBlock = 0; currentBlock < 3; currentBlock++)
            {
                ShuffeledArray = Sudoku.Shuffle();
                zeile          = independentBlocks[selectedIndependentBlocks, currentBlock] / 9;
                spalte         = independentBlocks[selectedIndependentBlocks, currentBlock] % 9;
                n = 0;
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        OutputField[spalte - (spalte % 3) + i, zeile - (zeile % 3) + j] = ShuffeledArray[n++];
                        SolvedGame[spalte - (spalte % 3) + i, zeile - (zeile % 3) + j]  = OutputField[spalte - (spalte % 3) + i, zeile - (zeile % 3) + j];
                    }
                }
            }

            Sudoku.Solve(0, 0, 0, OutputField, ref counter, ref solved, 1);
            OutputField = solution[0];

            n = 81 - fieldsLeft;

            Array.Copy(OutputField, tmp, OutputField.Length);

            do
            {
                zeile  = rnd.Next(9);
                spalte = rnd.Next(9);
                solution.Clear();
                tmp[zeile, spalte] = 0;
                counter            = 0;
                solved             = 0;
                Sudoku.Solve(0, 0, 0, tmp, ref counter, ref solved, 0);
                if (solved == 1)
                {
                    Array.Copy(tmp, OutputField, OutputField.Length);
                    n--;
                }
                else
                {
                    Array.Copy(OutputField, tmp, OutputField.Length);
                }
            } while (n > 0);


            SolvedGame = solution[0];
            Array.Copy(SolvedGame, tmp, SolvedGame.Length);

            zeile  = rnd.Next(9);
            spalte = rnd.Next(9);
            solution.Clear();
            tmp[zeile, spalte] = 0;
            counter            = 0;
            solved             = 0;
            Sudoku.Solve(0, 0, 0, tmp, ref counter, ref solved, 0);

            Array.Copy(SolvedGame, tmp, SolvedGame.Length);

            int[][,] SendBack = new int[2][, ];
            SendBack[0]       = OutputField;
            SendBack[1]       = SolvedGame;

            return(SendBack);
        }
Exemplo n.º 36
0
        public void Fill1()
        {
            sd        = new Sudoku();
            btn       = new Button[9, 9];
            btn[0, 0] = btn1_1;
            btn[0, 1] = btn2_1;
            btn[0, 2] = btn3_1;
            btn[0, 3] = btn1_2;
            btn[0, 4] = btn2_2;
            btn[0, 5] = btn3_2;
            btn[0, 6] = btn1_3;
            btn[0, 7] = btn2_3;
            btn[0, 8] = btn3_3;

            btn[1, 0] = btn4_1;
            btn[1, 1] = btn5_1;
            btn[1, 2] = btn6_1;
            btn[1, 3] = btn4_2;
            btn[1, 4] = btn5_2;
            btn[1, 5] = btn6_2;
            btn[1, 6] = btn4_3;
            btn[1, 7] = btn5_3;
            btn[1, 8] = btn6_3;

            btn[2, 0] = btn7_1;
            btn[2, 1] = btn8_1;
            btn[2, 2] = btn9_1;
            btn[2, 3] = btn7_2;
            btn[2, 4] = btn8_2;
            btn[2, 5] = btn9_2;
            btn[2, 6] = btn7_3;
            btn[2, 7] = btn8_3;
            btn[2, 8] = btn9_3;

            btn[3, 0] = btn1_4;
            btn[3, 1] = btn2_4;
            btn[3, 2] = btn3_4;
            btn[3, 3] = btn1_5;
            btn[3, 4] = btn2_5;
            btn[3, 5] = btn3_5;
            btn[3, 6] = btn1_6;
            btn[3, 7] = btn2_6;
            btn[3, 8] = btn3_6;

            btn[4, 0] = btn4_4;
            btn[4, 1] = btn5_4;
            btn[4, 2] = btn6_4;
            btn[4, 3] = btn4_5;
            btn[4, 4] = btn5_5;
            btn[4, 5] = btn6_5;
            btn[4, 6] = btn4_6;
            btn[4, 7] = btn5_6;
            btn[4, 8] = btn6_6;

            btn[5, 0] = btn7_4;
            btn[5, 1] = btn8_4;
            btn[5, 2] = btn9_4;
            btn[5, 3] = btn7_5;
            btn[5, 4] = btn8_5;
            btn[5, 5] = btn9_5;
            btn[5, 6] = btn7_6;
            btn[5, 7] = btn8_6;
            btn[5, 8] = btn9_6;

            btn[6, 0] = btn1_7;
            btn[6, 1] = btn2_7;
            btn[6, 2] = btn3_7;
            btn[6, 3] = btn1_8;
            btn[6, 4] = btn2_8;
            btn[6, 5] = btn3_8;
            btn[6, 6] = btn1_9;
            btn[6, 7] = btn2_9;
            btn[6, 8] = btn3_9;

            btn[7, 0] = btn4_7;
            btn[7, 1] = btn5_7;
            btn[7, 2] = btn6_7;
            btn[7, 3] = btn4_8;
            btn[7, 4] = btn5_8;
            btn[7, 5] = btn6_8;
            btn[7, 6] = btn4_9;
            btn[7, 7] = btn5_9;
            btn[7, 8] = btn6_9;

            btn[8, 0] = btn7_7;
            btn[8, 1] = btn8_7;
            btn[8, 2] = btn9_7;
            btn[8, 3] = btn7_8;
            btn[8, 4] = btn8_8;
            btn[8, 5] = btn9_8;
            btn[8, 6] = btn7_9;
            btn[8, 7] = btn8_9;
            btn[8, 8] = btn9_9;
        }
Exemplo n.º 37
0
 public SudokuColumn(Sudoku sudoku, int n, int index) : base(sudoku, n, index)
 {
 }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            #region Teil 1
            byte[,] Beispiel =
            {
                { 0, 3, 0, 0, 0, 0, 0, 0, 0 }, //0
                { 0, 0, 0, 1, 9, 5, 0, 0, 0 },
                { 0, 0, 8, 0, 0, 0, 0, 6, 0 }, // 2
                { 8, 0, 0, 0, 6, 0, 0, 0, 0 }, //3
                { 4, 0, 0, 8, 0, 0, 0, 0, 1 },
                { 0, 0, 0, 0, 2, 0, 0, 0, 0 }, // 5
                { 0, 6, 0, 0, 0, 0, 2, 8, 0 }, //6
                { 0, 0, 0, 4, 1, 9, 0, 0, 5 },
                { 0, 0, 0, 0, 0, 0, 0, 7, 0 } // 8
            };

            Sudoku s = new Sudoku(Beispiel);
            Sudoku t = new Sudoku();

            s.Print();
            t.Print();

            #endregion
            #region Teil 2

            Console.WriteLine("Setze 4 in das 3. Feld der ersten Zeile:");
            s.SetzeFeld(3, 1, 4);
            s.Print();

            #endregion
            #region Teil 3

            Console.WriteLine("Zeilen:");
            for (int i = 1; i <= 9; i++)
            {
                Console.WriteLine("{0} {1}", i, s.ZeilenFehler(i) ? "Fehler" : "OK");
            }

            #endregion
            #region Teil 4

            Console.WriteLine("Spalten");
            for (int i = 1; i <= 9; i++)
            {
                Console.WriteLine("{0} {1}", i, s.SpaltenFehler(i) ? "Fehler" : "OK");
            }
            Console.WriteLine("Blöcke:");
            for (int i = 1; i <= 3; i++)
            {
                for (int j = 1; j <= 3; j++)
                {
                    Console.WriteLine("{0}|{1} {2}", i, j, s.BlockFehler(i, j) ? "Fehler" : "OK");
                }
            }

            #endregion
            #region Teil 5

            if (s.Fehler)
            {
                Console.WriteLine("Fehlerhaft!");
            }
            else
            {
                Console.WriteLine("Fehlerfrei");
            }

            #endregion
            #region Teil 6

            t = new Sudoku(s);

            Console.WriteLine("t == s         : {0}", (t == s) ? "JA" : "NEIN");
            Console.WriteLine("t.IstGleich(s) : {0}", (t.IstGleich(s)) ? "JA" : "NEIN");

            t.SetzeFeld(1, 1, 5);
            Console.WriteLine("t neu:");
            t.Print();
            Console.WriteLine("t.IstGleich(s) : {0}", (t.IstGleich(s)) ? "JA" : "NEIN");

            #endregion
            #region Teil 7

            Console.WriteLine("Datei lesen:");
            Sudoku u = Sudoku.LeseDatei(@"..\..\..\beispiel.sudoku");

            u.Print();
            if (u.Fehler)
            {
                Console.WriteLine("Fehlerhaft!");
            }
            else
            {
                Console.WriteLine("Fehlerfrei");
            }

            #endregion
            #region Teil 8

            Console.WriteLine("Datei speichern:");
            s.SpeichernUnter(@"..\..\..\mein.sudoku");

            #endregion
        }
Exemplo n.º 39
0
        public MainForm()
        {
            InitializeComponent();
            squareColors = new Color[9, 9];
            saved        = true;
            undo         = new UndoRedo(new Update(setMark), new UpdateState(undoRedoButtons));
            sudoku       = new Sudoku(undo);

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    squareColors[i, j] = Color.FromArgb(214, 230, 237);
                }
                for (int j = 3; j < 6; j++)
                {
                    squareColors[i, j] = Color.FromArgb(208, 227, 234);
                }
                for (int j = 6; j < 9; j++)
                {
                    squareColors[i, j] = Color.FromArgb(201, 223, 232);
                }
            }
            for (int i = 3; i < 6; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    squareColors[i, j] = Color.FromArgb(193, 219, 229);
                }
                for (int j = 3; j < 6; j++)
                {
                    squareColors[i, j] = Color.FromArgb(186, 215, 226);
                }
                for (int j = 6; j < 9; j++)
                {
                    squareColors[i, j] = Color.FromArgb(179, 211, 224);
                }
            }
            for (int i = 6; i < 9; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    squareColors[i, j] = Color.FromArgb(171, 207, 221);
                }
                for (int j = 3; j < 6; j++)
                {
                    squareColors[i, j] = Color.FromArgb(161, 203, 218);
                }
                for (int j = 6; j < 9; j++)
                {
                    squareColors[i, j] = Color.FromArgb(152, 198, 215);
                }
                undoRedoButtons();
            }

            gridSudoku.RowsDefaultCellStyle.Font      = new Font("Courier New", 12, FontStyle.Bold);
            gridSudoku.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            gridSudoku.MultiSelect = false;
            for (int i = 1; i < 10; i++)
            {
                gridSudoku.Rows.Add();
                if (gridSudoku.Rows[i - 1].IsNewRow)
                {
                    continue;
                }
                gridSudoku.Rows[i - 1].HeaderCell.Value = i.ToString();
                gridSudoku.Rows[i - 1].Height           = 40;
                for (int j = 0; j < 9; j++)
                {
                    gridSudoku.Rows[i - 1].Cells[j].Style.BackColor = squareColors[i - 1, j];
                }
            }

            // Connect the virtual-mode events to event handlers.
            gridSudoku.CellValueNeeded += new
                                          DataGridViewCellValueEventHandler(gridSudoku_CellValueNeeded);
            gridSudoku.CellValuePushed += new
                                          DataGridViewCellValueEventHandler(gridSudkou_CellValuePushed);
            gridSudoku.RowValidated += new
                                       DataGridViewCellEventHandler(gridSudoku_RowValidated);
            gridSudoku.RowDirtyStateNeeded += new
                                              QuestionEventHandler(gridSudoku_RowDirtyStateNeeded);
            gridSudoku.CancelRowEdit += new
                                        QuestionEventHandler(gridSudoku_CancelRowEdit);
        }
Exemplo n.º 40
0
 public SudokuRow(Sudoku sudoku, int index) : this(sudoku, 3, index)
 {
 }
Exemplo n.º 41
0
 public SudokuRow(Sudoku sudoku, int n, int index) : base(sudoku, n, index)
 {
 }
Exemplo n.º 42
0
        private bool DeleteField(Sudoku temp, ref int difficulty)
        {
            int i = Rnd.Next(0, 9); ;
            int j = Rnd.Next(0, 9); ;

            // select random not yet deleted field
            while (!temp.Fields[i][j].Filled)
            {
                i = Rnd.Next(0, 9);
                j = Rnd.Next(0, 9);
            }

            temp.Fields[i][j].Value = 0;
            temp.Fields[i][j].Filled = false;
            SudokuSolver Test = new SudokuSolver();
            int Difficulty = difficulty;
            // check the desired characteristics
            Sudoku Temp = Test.Solve(temp.Copy(), true, Difficulty);
            if (Temp == null)
                return false;
            temp.Difficulty = Temp.Difficulty;
            if (Temp.NrSolutions > 1 || Temp.Difficulty > Difficulty)
                return false;
            else
                return true;
        }
Exemplo n.º 43
0
 public SudokuCollection(Sudoku sudoku, int index) : this(sudoku, 3, index)
 {
 }
Exemplo n.º 44
0
        public static string GenerateSudokuAndGetSeed(int fieldsPerRowAmount, Difficulty difficulty, bool diagonalRows, bool randomBoxFormation)
        {
            var sudoku = new Sudoku(fieldsPerRowAmount, difficulty, diagonalRows, randomBoxFormation);

            return(ConvertSudokuIntoSeed(sudoku));
        }
Exemplo n.º 45
0
        private static byte[] Solve(Sudoku sudoku)
        {
            bool updated;
            bool solved;

            do
            {
                updated = false;
                solved  = true;

                for (int i = 0; i < sudoku.Answer.Length; i++)
                {
                    if (sudoku.Answer[i] != 0)
                    {
                        continue;
                    }
                    solved = false;

                    int c = sudoku.GetCandidateBit(i);
                    if (c == 0)
                    {
                        return(null);
                    }

                    int lowest = LowestOneBit(c);
                    if (c == lowest)
                    {
                        sudoku.Update(i, ToNum(lowest));
                        updated = true;
                    }
                }
            } while (updated);

            if (solved)
            {
                return(sudoku.Answer);
            }

            // 候補が少ない箇所を探す
            int count = int.MaxValue;
            int index = 0;

            for (int i = 0; i < sudoku.Answer.Length; i++)
            {
                if (sudoku.Answer[i] != 0)
                {
                    continue;
                }

                int c = BitCount(sudoku.GetCandidateBit(i));
                if (c < count)
                {
                    count = c;
                    index = i;
                }
            }

            // 複数ある候補のうちの一つを仮定して、再帰的に解析
            int candidate = sudoku.GetCandidateBit(index);

            for (int i = 0; i < 9; i++)
            {
                int bit = (candidate & (1 << i));
                if (bit == 0)
                {
                    continue;
                }

                Sudoku newSudoku = new Sudoku(sudoku);
                newSudoku.Update(index, (byte)(i + 1));

                byte[] answer = Solve(newSudoku);
                if (answer != null)
                {
                    return(answer);
                }
            }

            return(null);
        }
Exemplo n.º 46
0
 // Constructor
 // filename - file from which to read the puzzle
 public SudokuSolver(string puzzleFile)
 {
     puzzle = new Sudoku(puzzleFile);
 }
Exemplo n.º 47
0
 public SudokuColumn(Sudoku sudoku, int index) : this(sudoku, 3, index)
 {
 }
Exemplo n.º 48
0
        int SolCounter; // Solution counter

        #endregion Fields

        #region Methods

        public Sudoku Solve(Sudoku suk, bool count, int maxDifficulty)
        {
            Remaining = 81;
            Input = suk;
            InitCandidates();
            SolCounter = 0;

            int Difficulty = 1;
            int HighestDifficulty = 1;

            Input.Rem1 = -1;
            Input.Rem2 = -1;
            Input.Rem3 = -1;

            while (Remaining > 0)
            {
                int oldRem = Remaining;

                if (Grade0())
                    continue;

                if (Grade1())
                    continue;

                if (Difficulty >= 2)
                {
                    if (Input.Rem1 == -1)
                        Input.Rem1 = Remaining;

                    if (GradeX(2))
                    {
                        continue;
                    }
                    if (CandidateLine())
                    {
                        continue;
                    }
                }

                if (Difficulty >= 3)
                {
                    if (Input.Rem2 == -1)
                        Input.Rem2 = Remaining;

                    if (GradeX(3))
                        continue;
                    if (XWing())
                    {
                        continue;
                    }
                }

                if (Difficulty >= 4)
                {   // this completes the sudoku in one step
                    if (Input.Rem3 == -1)
                        Input.Rem3 = Remaining;

                    NonLogic(count);
                }

                if (Remaining == oldRem)
                {
                    Difficulty++;
                    if (Difficulty > HighestDifficulty)
                        HighestDifficulty = Difficulty;

                    if (Difficulty > maxDifficulty)
                    {
                        Input.Difficulty = HighestDifficulty;
                        Input.NrSolutions = 0;
                        return null;
                    }
                    if (Difficulty > 4)
                        break;
                }
                else
                    Difficulty = 1;
            }

            // brute force counts the number of solutions
            Input.NrSolutions = SolCounter;
            if (Input.NrSolutions == 0)
                Input.NrSolutions = 1; // no brute force used

            Input.Difficulty = HighestDifficulty;
            return Input;
        }
Exemplo n.º 49
0
        public Sudoku Copy()
        {
            Sudoku Result = new Sudoku(new List<int>());
            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    Result.Fields[i][j] = Fields[i][j].Copy();
                }
            }
            Result.Difficulty = Difficulty;
            Result.Rem1 = Rem1;
            Result.Rem2 = Rem2;
            Result.Rem3 = Rem3;
            Result.NrSolutions = NrSolutions;

            return Result;
        }