Llop_Sudoku - Espacio de nombres Llop_Sudoku
Llop Site Home > Visual Studio .NET > Sudoku > Llop_Sudoku
![]()
Clase Form1
Namespace Llop_Sudoku
Public Class Form1 : Inherits System.Windows.Forms.Form
Private Shared LadoMargenEnPixels As Int32 = 30
Private Shared dimensiones()() As Int32 = {New Int32() {4, 4, 2, 2}, _
New Int32() {6, 6, 3, 2}, _
New Int32() {6, 6, 2, 3}, _
New Int32() {9, 9, 3, 3}, _
New Int32() {12, 12, 4, 3}, _
New Int32() {12, 12, 3, 4}, _
New Int32() {16, 16, 4, 4}}
Private sudoku As Llop_Sudoku_Sudoku
Private textboxes As New ArrayList
Dim _creadorPdf As New CreadorPDF
#Region " Código generado por el Diseñador de Windows Forms "
Public Sub New()
MyBase.New()
'El Diseñador de Windows Forms requiere esta llamada.
InitializeComponent()
inicializaComponentesDos()
End Sub
'Form reemplaza a Dispose para limpiar la lista de componentes.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Requerido por el Diseñador de Windows Forms
Private components As System.ComponentModel.IContainer
'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
'Puede modificarse utilizando el Diseñador de Windows Forms.
'No lo modifique con el editor de código.
Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents Button2 As System.Windows.Forms.Button
Friend WithEvents Button3 As System.Windows.Forms.Button
Friend WithEvents StatusBar1 As System.Windows.Forms.StatusBar
Friend WithEvents TrackBar1 As System.Windows.Forms.TrackBar
Friend WithEvents ComboBox2 As System.Windows.Forms.ComboBox
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents Label5 As System.Windows.Forms.Label
Friend WithEvents Label6 As System.Windows.Forms.Label
Friend WithEvents Label7 As System.Windows.Forms.Label
Friend WithEvents Label8 As System.Windows.Forms.Label
Friend WithEvents Label9 As System.Windows.Forms.Label
Friend WithEvents GroupBox3 As System.Windows.Forms.GroupBox
Friend WithEvents CheckBox1 As System.Windows.Forms.CheckBox
Friend WithEvents GroupBox4 As System.Windows.Forms.GroupBox
Friend WithEvents Button4 As System.Windows.Forms.Button
Friend WithEvents GroupBox5 As System.Windows.Forms.GroupBox
Friend WithEvents Button5 As System.Windows.Forms.Button
Friend WithEvents Button6 As System.Windows.Forms.Button
Friend WithEvents GroupBox6 As System.Windows.Forms.GroupBox
Friend WithEvents Button7 As System.Windows.Forms.Button
Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox
Private Sub InitializeComponent()
Me.GroupBox1 = New System.Windows.Forms.GroupBox
Me.Label9 = New System.Windows.Forms.Label
Me.TrackBar1 = New System.Windows.Forms.TrackBar
Me.Button1 = New System.Windows.Forms.Button
Me.Label2 = New System.Windows.Forms.Label
Me.Button2 = New System.Windows.Forms.Button
Me.Button3 = New System.Windows.Forms.Button
Me.StatusBar1 = New System.Windows.Forms.StatusBar
Me.ComboBox2 = New System.Windows.Forms.ComboBox
Me.Label3 = New System.Windows.Forms.Label
Me.GroupBox2 = New System.Windows.Forms.GroupBox
Me.Label8 = New System.Windows.Forms.Label
Me.Label7 = New System.Windows.Forms.Label
Me.Label6 = New System.Windows.Forms.Label
Me.Label5 = New System.Windows.Forms.Label
Me.Label4 = New System.Windows.Forms.Label
Me.GroupBox3 = New System.Windows.Forms.GroupBox
Me.CheckBox1 = New System.Windows.Forms.CheckBox
Me.GroupBox4 = New System.Windows.Forms.GroupBox
Me.Button6 = New System.Windows.Forms.Button
Me.Button5 = New System.Windows.Forms.Button
Me.Button4 = New System.Windows.Forms.Button
Me.GroupBox5 = New System.Windows.Forms.GroupBox
Me.ComboBox1 = New System.Windows.Forms.ComboBox
Me.GroupBox6 = New System.Windows.Forms.GroupBox
Me.Button7 = New System.Windows.Forms.Button
Me.GroupBox1.SuspendLayout()
CType(Me.TrackBar1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.GroupBox2.SuspendLayout()
Me.GroupBox3.SuspendLayout()
Me.GroupBox4.SuspendLayout()
Me.GroupBox5.SuspendLayout()
Me.GroupBox6.SuspendLayout()
Me.SuspendLayout()
'
'GroupBox1
'
Me.GroupBox1.Controls.Add(Me.Label9)
Me.GroupBox1.Controls.Add(Me.TrackBar1)
Me.GroupBox1.Controls.Add(Me.Button1)
Me.GroupBox1.Controls.Add(Me.Label2)
Me.GroupBox1.Location = New System.Drawing.Point(640, 64)
Me.GroupBox1.Name = "GroupBox1"
Me.GroupBox1.Size = New System.Drawing.Size(232, 112)
Me.GroupBox1.TabIndex = 0
Me.GroupBox1.TabStop = False
Me.GroupBox1.Text = "Generación sudoku"
'
'Label9
'
Me.Label9.Location = New System.Drawing.Point(168, 56)
Me.Label9.Name = "Label9"
Me.Label9.Size = New System.Drawing.Size(56, 16)
Me.Label9.TabIndex = 5
Me.Label9.TextAlign = System.Drawing.ContentAlignment.MiddleRight
'
'TrackBar1
'
Me.TrackBar1.AutoSize = False
Me.TrackBar1.Location = New System.Drawing.Point(8, 72)
Me.TrackBar1.Name = "TrackBar1"
Me.TrackBar1.Size = New System.Drawing.Size(216, 32)
Me.TrackBar1.TabIndex = 4
Me.TrackBar1.TickStyle = System.Windows.Forms.TickStyle.TopLeft
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(8, 24)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(216, 24)
Me.Button1.TabIndex = 3
Me.Button1.Text = "Nuevo sudoku"
'
'Label2
'
Me.Label2.Location = New System.Drawing.Point(8, 56)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(56, 16)
Me.Label2.TabIndex = 1
Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'Button2
'
Me.Button2.Location = New System.Drawing.Point(8, 24)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(216, 24)
Me.Button2.TabIndex = 4
Me.Button2.Text = "Nuevo sudoku vacío"
'
'Button3
'
Me.Button3.Location = New System.Drawing.Point(8, 24)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(216, 24)
Me.Button3.TabIndex = 5
Me.Button3.Text = "Resolver sudoku"
'
'StatusBar1
'
Me.StatusBar1.Location = New System.Drawing.Point(0, 632)
Me.StatusBar1.Name = "StatusBar1"
Me.StatusBar1.Size = New System.Drawing.Size(880, 22)
Me.StatusBar1.TabIndex = 1
'
'ComboBox2
'
Me.ComboBox2.Location = New System.Drawing.Point(56, 56)
Me.ComboBox2.Name = "ComboBox2"
Me.ComboBox2.Size = New System.Drawing.Size(48, 21)
Me.ComboBox2.TabIndex = 2
'
'Label3
'
Me.Label3.Location = New System.Drawing.Point(8, 64)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(48, 16)
Me.Label3.TabIndex = 3
Me.Label3.Text = "Solución"
'
'GroupBox2
'
Me.GroupBox2.Controls.Add(Me.Label8)
Me.GroupBox2.Controls.Add(Me.Label7)
Me.GroupBox2.Controls.Add(Me.Label6)
Me.GroupBox2.Controls.Add(Me.Label5)
Me.GroupBox2.Controls.Add(Me.Label4)
Me.GroupBox2.Controls.Add(Me.Button3)
Me.GroupBox2.Controls.Add(Me.Label3)
Me.GroupBox2.Controls.Add(Me.ComboBox2)
Me.GroupBox2.Location = New System.Drawing.Point(640, 464)
Me.GroupBox2.Name = "GroupBox2"
Me.GroupBox2.Size = New System.Drawing.Size(232, 160)
Me.GroupBox2.TabIndex = 2
Me.GroupBox2.TabStop = False
Me.GroupBox2.Text = "Solución"
'
'Label8
'
Me.Label8.Location = New System.Drawing.Point(88, 136)
Me.Label8.Name = "Label8"
Me.Label8.Size = New System.Drawing.Size(136, 16)
Me.Label8.TabIndex = 10
'
'Label7
'
Me.Label7.Location = New System.Drawing.Point(8, 136)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(72, 16)
Me.Label7.TabIndex = 9
Me.Label7.Text = "Tiempo (ms):"
'
'Label6
'
Me.Label6.Location = New System.Drawing.Point(88, 112)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(136, 16)
Me.Label6.TabIndex = 8
'
'Label5
'
Me.Label5.Location = New System.Drawing.Point(8, 112)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(72, 16)
Me.Label5.TabIndex = 7
Me.Label5.Text = "Calificación:"
'
'Label4
'
Me.Label4.Location = New System.Drawing.Point(8, 88)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(216, 16)
Me.Label4.TabIndex = 6
'
'GroupBox3
'
Me.GroupBox3.Controls.Add(Me.CheckBox1)
Me.GroupBox3.Controls.Add(Me.Button2)
Me.GroupBox3.Location = New System.Drawing.Point(640, 184)
Me.GroupBox3.Name = "GroupBox3"
Me.GroupBox3.Size = New System.Drawing.Size(232, 80)
Me.GroupBox3.TabIndex = 3
Me.GroupBox3.TabStop = False
Me.GroupBox3.Text = "Creación sudoku"
'
'CheckBox1
'
Me.CheckBox1.Location = New System.Drawing.Point(8, 56)
Me.CheckBox1.Name = "CheckBox1"
Me.CheckBox1.Size = New System.Drawing.Size(216, 16)
Me.CheckBox1.TabIndex = 5
Me.CheckBox1.Text = "Poniendo pistas"
'
'GroupBox4
'
Me.GroupBox4.Controls.Add(Me.Button6)
Me.GroupBox4.Controls.Add(Me.Button5)
Me.GroupBox4.Controls.Add(Me.Button4)
Me.GroupBox4.Location = New System.Drawing.Point(640, 336)
Me.GroupBox4.Name = "GroupBox4"
Me.GroupBox4.Size = New System.Drawing.Size(232, 120)
Me.GroupBox4.TabIndex = 4
Me.GroupBox4.TabStop = False
Me.GroupBox4.Text = "Evaluación"
'
'Button6
'
Me.Button6.Location = New System.Drawing.Point(8, 56)
Me.Button6.Name = "Button6"
Me.Button6.Size = New System.Drawing.Size(216, 24)
Me.Button6.TabIndex = 2
Me.Button6.Text = "Añadir pista"
'
'Button5
'
Me.Button5.Location = New System.Drawing.Point(8, 88)
Me.Button5.Name = "Button5"
Me.Button5.Size = New System.Drawing.Size(216, 24)
Me.Button5.TabIndex = 1
Me.Button5.Text = "Volver a empezar"
'
'Button4
'
Me.Button4.Location = New System.Drawing.Point(8, 24)
Me.Button4.Name = "Button4"
Me.Button4.Size = New System.Drawing.Size(216, 24)
Me.Button4.TabIndex = 0
Me.Button4.Text = "¿Qué tal voy?"
'
'GroupBox5
'
Me.GroupBox5.Controls.Add(Me.ComboBox1)
Me.GroupBox5.Location = New System.Drawing.Point(640, 8)
Me.GroupBox5.Name = "GroupBox5"
Me.GroupBox5.Size = New System.Drawing.Size(232, 48)
Me.GroupBox5.TabIndex = 5
Me.GroupBox5.TabStop = False
Me.GroupBox5.Text = "Tamaño de la cuadrícula"
'
'ComboBox1
'
Me.ComboBox1.Location = New System.Drawing.Point(8, 16)
Me.ComboBox1.Name = "ComboBox1"
Me.ComboBox1.Size = New System.Drawing.Size(216, 21)
Me.ComboBox1.TabIndex = 2
'
'GroupBox6
'
Me.GroupBox6.Controls.Add(Me.Button7)
Me.GroupBox6.Location = New System.Drawing.Point(640, 272)
Me.GroupBox6.Name = "GroupBox6"
Me.GroupBox6.Size = New System.Drawing.Size(232, 56)
Me.GroupBox6.TabIndex = 6
Me.GroupBox6.TabStop = False
Me.GroupBox6.Text = "Exportar"
'
'Button7
'
Me.Button7.Location = New System.Drawing.Point(8, 24)
Me.Button7.Name = "Button7"
Me.Button7.Size = New System.Drawing.Size(216, 24)
Me.Button7.TabIndex = 0
Me.Button7.Text = "Crear .PDF"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(880, 654)
Me.Controls.Add(Me.GroupBox6)
Me.Controls.Add(Me.GroupBox5)
Me.Controls.Add(Me.GroupBox4)
Me.Controls.Add(Me.GroupBox3)
Me.Controls.Add(Me.GroupBox2)
Me.Controls.Add(Me.StatusBar1)
Me.Controls.Add(Me.GroupBox1)
Me.Name = "Form1"
Me.Text = "Llop_Sudoku v1.0"
Me.GroupBox1.ResumeLayout(False)
CType(Me.TrackBar1, System.ComponentModel.ISupportInitialize).EndInit()
Me.GroupBox2.ResumeLayout(False)
Me.GroupBox3.ResumeLayout(False)
Me.GroupBox4.ResumeLayout(False)
Me.GroupBox5.ResumeLayout(False)
Me.GroupBox6.ResumeLayout(False)
Me.ResumeLayout(False)
End Sub
#End Region
'Private Function CBin(ByVal Number As Integer) As String
' Dim Temp As Object
' Temp = 1 'Can't fouble nothing
' Do Until Temp > Number 'sets starting point for Len
' Temp = Temp * 2
' Loop
' Do Until Temp < 1
' If Number >= Temp Then
' CBin = CBin + "1"
' Number = Number - Temp
' Else
' CBin = CBin + "0"
' End If
' Temp = Temp / 2
' Loop 'Loop until string is complete
' CBin = CStr(Val(CBin))
'End Function
Private Sub inicializaComponentesDos()
Dim tamanosComboBox As String() = {"Sudoku de 4x4 y regiones de 2x2", _
"Sudoku de 6x6 y regiones de 2x3", _
"Sudoku de 6x6 y regiones de 3x2", _
"Sudoku de 9x9 y regiones de 3x3", _
"Sudoku de 12x12 y regiones de 3x4", _
"Sudoku de 12x12 y regiones de 4x3", _
"Sudoku de 16x16 y regiones de 4x4"} ', "Cuadrícula de 25x25; regiones de 5x5"}
Me.ComboBox1.DataSource = tamanosComboBox
Me.ComboBox1.SelectedIndex = 3
Me.sudoku = New Llop_Sudoku_Sudoku(dimensiones(ComboBox1.SelectedIndex)(0), _
dimensiones(ComboBox1.SelectedIndex)(1), _
dimensiones(ComboBox1.SelectedIndex)(2), _
dimensiones(ComboBox1.SelectedIndex)(3))
'Me.ajustaTamanoFormulario()
Me.anadeCasillas()
End Sub
Private Sub anadeCasillas()
Dim i As Int32
Dim j As Int32
Dim textbox As Llop_Sudoku_TextBox
Dim casilla As Llop_Sudoku_Casilla
Dim fila As Int32
Dim col As Int32
Dim ladoTextbox As Int32 = 576 / Me.sudoku.numeroFilas
Dim maximaCapacidad As Int32
If Me.sudoku.numeroFilas < 10 Then
maximaCapacidad = 1
Else
maximaCapacidad = 2
End If
Me.SuspendLayout()
For Each antiguoTextbox As Llop_Sudoku_TextBox In textboxes
Me.Controls.Remove(antiguoTextbox)
Next
textboxes.Clear()
For i = 0 To Me.sudoku.numeroFilas - 1
For j = 0 To Me.sudoku.numeroColumnas - 1
casilla = Me.sudoku.Casilla(i, j)
textbox = New Llop_Sudoku_TextBox(ladoTextbox, maximaCapacidad, casilla)
If casilla.EsPista Then
textbox.EsEditable = False
textbox.ForeColor = Llop_Sudoku_Util.ColorPista
End If
textbox.Location = New System.Drawing.Point(LadoMargenEnPixels + j * ladoTextbox, LadoMargenEnPixels + i * ladoTextbox)
textboxes.Add(textbox)
Me.Controls.Add(textbox)
Next j
Next i
Me.coloreaCasillas()
Me.ResumeLayout()
Me.refrescaCasillas()
End Sub
'Private Sub ajustaTamanoFormulario()
' Dim y As Int32
' Dim x As Int32 = 0
' x += LadoMargenEnPixels * 2 + Me.sudoku.NumeroCasillasLado * Llop_Sudoku_TextBox.LadoEnPixels
' Me.SuspendLayout()
' Me.GroupBox1.Location = New Point(x, GroupBox1.Location.Y)
' Me.GroupBox2.Location = New Point(x, GroupBox2.Location.Y)
' 'Me.GroupBox1.Size = New Size(GroupBox1.Size.Width, x - 14)
' 'Me.Button1.Location = New Point(Button1.Location.X, GroupBox1.Size.Height - 96)
' 'Me.Button2.Location = New Point(Button2.Location.X, GroupBox1.Size.Height - 64)
' 'Me.Button3.Location = New Point(Button3.Location.X, GroupBox1.Size.Height - 32)
' If x + 22 < GroupBox1.Size.Height + GroupBox2.Size.Height + 38 Then
' y = GroupBox1.Size.Height + GroupBox2.Size.Height + 38
' Else
' y = x + 22
' End If
' Me.ClientSize = New Size(x + GroupBox1.Size.Width + 12, y)
' Me.ResumeLayout()
'End Sub
Private Sub refrescaCasillas()
For Each textbox As Llop_Sudoku_TextBox In textboxes
textbox.refresca()
Next
End Sub
Private Sub trataSolucion(ByVal solucion As Solucion)
Dim cadena As String = solucion.getNumeroSoluciones & " solucion(es) encontrada(s) en " & solucion.getTiempoSolucion & " ms.; número de cambios: " & solucion.getCambios
Me.StatusBar1.Text = cadena
Me.Label4.Text = solucion.getNumeroSoluciones
Me.Label6.Text = solucion.getCambios & " - " & Llop_Sudoku_Util.getDescripcionCalificación(solucion.getCambios)
Me.Label8.Text = solucion.getTiempoSolucion
If solucion.getNumeroSoluciones = 0 Then
Me.ComboBox2.DataSource = Nothing
MsgBox("Ninguna solución - ¡mal problema!", MsgBoxStyle.Exclamation, "Llop_Sudoku - Advertencia")
Return
End If
Dim solucionesComboBox As New ArrayList
Dim i As Int32
For i = 0 To solucion.getNumeroSoluciones - 1
solucionesComboBox.Add(i + 1)
Next i
Me.ComboBox2.DataSource = solucionesComboBox
Me.ComboBox2.SelectedIndex = 0
Me.setValorCasillas(solucion.getSolucion(ComboBox2.SelectedIndex))
If Not solucion.getNumeroSoluciones = 1 Then
MsgBox("Más de una solución - ¡mal problema!", MsgBoxStyle.Exclamation, "Llop_Sudoku - Advertencia")
End If
End Sub
Private Sub setValorCasillas(ByVal valores()() As Int32)
For i As Int32 = 0 To Me.sudoku.numeroFilas - 1
For j As Int32 = 0 To Me.sudoku.numeroColumnas - 1
Me.sudoku.Casilla(i, j).Valor = valores(i)(j)
Next j
Next i
End Sub
Private Sub limpiaPanelSoluciones()
Me.Label4.Text = ""
Me.Label6.Text = ""
Me.Label8.Text = ""
Me.ComboBox2.DataSource = Nothing
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If Me.ComboBox1.SelectedIndex > 5 Then
If Not MsgBox("Crear un sudoku de este tamaño puede tardar varios minutos." & Chr(13) & "¿Desea crearlo de todos modos?", MsgBoxStyle.YesNo, "Llop_Sudoku - Advertencia") = MsgBoxResult.Yes Then
Return
End If
End If
Dim sudokuTemp As New Llop_Sudoku_Sudoku(dimensiones(ComboBox1.SelectedIndex)(0), _
dimensiones(ComboBox1.SelectedIndex)(1), _
dimensiones(ComboBox1.SelectedIndex)(2), _
dimensiones(ComboBox1.SelectedIndex)(3))
Dim numPistas As Int32 = Me.TrackBar1.Value
If sudokuTemp.generaPuzzle(numPistas) Then
Me.sudoku = sudokuTemp
Dim prob As Problema = Me.sudoku.Problema
Me.StatusBar1.Text = Me.ComboBox1.SelectedItem & " creado en " & prob.getTiempoGeneracion & " ms.; número de cambios: " & prob.getCambios
Me.limpiaPanelSoluciones()
'Me.ajustaTamanoFormulario()
Me.anadeCasillas()
Else
Dim mensaje As String = "Ha fallado la creación de un puzzle válido."
Me.StatusBar1.Text = mensaje
MsgBox(mensaje, MsgBoxStyle.Exclamation, "Llop_Sudoku - Advertencia")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Try
Me.coloreaCasillas()
If Not Me.sudoku.EsGenerado Then
Me.establecePistas()
End If
If Me.sudoku.EstaSolucionado Then
MsgBox("¡Sudoku bien resuelto!", MsgBoxStyle.Information, "Llop_Sudoku - ¡Felicidades!")
Return
End If
If Not Me.sudoku.EstaVacio Then
Me.sudoku.setProblema(Me.sudoku.getProblema)
Me.trataSolucion(Me.sudoku.getSolucion)
Me.refrescaCasillas()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub establecePistas()
' Si no hay casillas escritas en color oliva, pintamos las que están escritas de color oliva.
Dim ctrl As Boolean = True
For Each textbox As Llop_Sudoku_TextBox In textboxes
If Not textbox.Text.Equals("") And textbox.ForeColor.Equals(Llop_Sudoku_Util.ColorPista) Then
ctrl = False
Exit For
End If
Next
If ctrl Then
For Each textbox As Llop_Sudoku_TextBox In textboxes
If Not textbox.Text.Equals("") Then
textbox.ForeColor = Llop_Sudoku_Util.ColorPista
End If
Next
End If
Me.fijarPistas()
' Establecemos como pista las casillas no editables. Las demás pasan a no ser pistas.
Dim pivote As Int32 = 0
For i As Int32 = 0 To Me.sudoku.numeroFilas - 1
For j As Int32 = 0 To Me.sudoku.numeroColumnas - 1
If Not Me.sudoku.Casilla(i, j).EstaEscrita Then
Me.sudoku.Casilla(i, j).EsPista = False
Else
If CType(Me.textboxes.Item(pivote), Llop_Sudoku_TextBox).EsEditable Then
Me.sudoku.Casilla(i, j).EsPista = False
Else
Me.sudoku.Casilla(i, j).EsPista = True
End If
End If
pivote += 1
Next j
Next i
Me.CheckBox1.Checked = False
End Sub
Private Sub coloreaTextboxesVacios(ByVal color As Color)
For Each textbox As Llop_Sudoku_TextBox In textboxes
If textbox.Text.Equals("") Then
textbox.ForeColor = color
End If
Next
End Sub
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox2.SelectedIndexChanged
If Me.ComboBox2.DataSource Is Nothing Then
Return
End If
Try
If Not Me.sudoku.getSolucion.getNumeroSoluciones = 0 Then
Me.setValorCasillas(Me.sudoku.getSolucion.getSolucion(ComboBox2.SelectedIndex))
Me.refrescaCasillas()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Me.sudoku = New Llop_Sudoku_Sudoku(dimensiones(ComboBox1.SelectedIndex)(0), _
dimensiones(ComboBox1.SelectedIndex)(1), _
dimensiones(ComboBox1.SelectedIndex)(2), _
dimensiones(ComboBox1.SelectedIndex)(3))
'Me.ajustaTamanoFormulario()
Me.limpiaPanelSoluciones()
Me.anadeCasillas()
If Me.CheckBox1.Checked Then
Me.coloreaTextboxesVacios(Llop_Sudoku_Util.ColorPista)
Else
Me.coloreaTextboxesVacios(Llop_Sudoku_Util.ColorNormal)
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub fijarPistas()
For Each textbox As Llop_Sudoku_TextBox In textboxes
If Not textbox.Text.Equals("") And textbox.ForeColor.Equals(Llop_Sudoku_Util.ColorPista) Then
textbox.EsEditable = False
Else
textbox.EsEditable = True
End If
Next
End Sub
Private Function hayPistas() As Boolean
For Each textbox As Llop_Sudoku_TextBox In textboxes
If Not textbox.Text.Equals("") And textbox.ForeColor.Equals(Llop_Sudoku_Util.ColorPista) Then
Return True
End If
Next
Return False
End Function
Private Sub habilitarTextboxes()
For Each textbox As Llop_Sudoku_TextBox In textboxes
textbox.EsEditable = True
Next
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Try
If Me.sudoku.EsGenerado Then
Return
End If
If Me.CheckBox1.Checked Then
Me.coloreaTextboxesVacios(Llop_Sudoku_Util.ColorPista)
Me.habilitarTextboxes()
Else
Me.coloreaTextboxesVacios(Llop_Sudoku_Util.ColorNormal)
Me.fijarPistas()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Try
If Not Me.sudoku.EsGenerado And Me.hayPistas Then
Me.establecePistas()
End If
Me.sudoku.vacia()
Me.coloreaCasillas()
Me.refrescaCasillas()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Try
Me.coloreaCasillas()
If Me.sudoku.EstaSolucionado Then
MsgBox("¡Sudoku bien resuelto!", MsgBoxStyle.Information, "Llop_Sudoku - ¡Felicidades!")
Return
End If
Me.trataEvaluacion(Me.sudoku.evalua)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub trataEvaluacion(ByVal evaluacion As Llop_Sudoku_Evaluacion)
If evaluacion Is Nothing Then
MsgBox("El problema no es de solución única y no se puede evaluar.", MsgBoxStyle.Exclamation, "Llop_Sudoku - Evaluación")
Return
End If
Dim numRegion As Int32
Dim numCasilla As Int32
Dim fila As Int32
Dim columna As Int32
Dim coordX As Int32
Dim coordY As Int32
For i As Int32 = 0 To evaluacion.NumeroRegionesConError - 1
numRegion = evaluacion.RegionConError(i)
fila = Decimal.Floor(numRegion / Me.sudoku.numeroFilasRegion)
columna = numRegion Mod Me.sudoku.numeroFilasRegion
For m As Int32 = 0 To Me.sudoku.numeroFilasRegion - 1
For n As Int32 = 0 To Me.sudoku.numeroColumnasRegion - 1
coordX = columna * Me.sudoku.numeroColumnasRegion + n
coordY = fila * Me.sudoku.numeroFilasRegion + m
numCasilla = coordX + Me.sudoku.numeroColumnas * coordY
CType(Me.textboxes.Item(numCasilla), Llop_Sudoku_TextBox).BackColor = Llop_Sudoku_Util.ColorError
Next n
Next m
Next i
Dim mensaje As String
If evaluacion.NumeroRegionesConError = 0 Then
If Me.numeroTextboxesVacios = 0 Then
mensaje = "¡Sudoku solucionado! ¡Felicidades!"
Else
mensaje = evaluacion.Mensaje & Chr(13) & " Te quedan " & Me.numeroTextboxesVacios & " números."
End If
End If
MsgBox(evaluacion.Mensaje, MsgBoxStyle.Information, "Llop_Sudoku - Evaluación")
End Sub
Private Function numeroTextboxesVacios() As Int32
Dim cuenta As Int32 = 0
For Each txtbox As Llop_Sudoku_TextBox In textboxes
If txtbox.Text.Equals("") Then
cuenta += 1
End If
Next
Return cuenta
End Function
Private Sub coloreaCasillas()
Dim fila As Int32
Dim col As Int32
Dim pivote As Int32 = 0
For i As Int32 = 0 To Me.sudoku.numeroFilas - 1
For j As Int32 = 0 To Me.sudoku.numeroColumnas - 1
fila = Decimal.Floor(i / Me.sudoku.numeroFilasRegion)
col = Decimal.Floor(j / Me.sudoku.numeroColumnasRegion)
CType(textboxes.Item(pivote), Llop_Sudoku_TextBox).BackColor = Llop_Sudoku_Util.getColor(fila, col)
pivote += 1
Next j
Next i
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Try
Me.coloreaCasillas()
If Me.sudoku.EstaLleno Then
MsgBox("No hay donde poner la pista.", MsgBoxStyle.Exclamation, "Llop_Sudoku - Advertencia")
Return
End If
Dim generadorAleatorios As New Random
Dim indice As Int32 = generadorAleatorios.Next(0, textboxes.Count)
While Not CType(textboxes.Item(indice), Llop_Sudoku_TextBox).Text.Equals("")
indice = generadorAleatorios.Next(0, textboxes.Count)
End While
Dim pista As Int32 = Me.sudoku.getPista(indice)
CType(textboxes.Item(indice), Llop_Sudoku_TextBox).EsEditable = False
CType(textboxes.Item(indice), Llop_Sudoku_TextBox).ForeColor = Llop_Sudoku_Util.ColorPista
Dim casilla As Llop_Sudoku_Casilla = CType(textboxes.Item(indice), Llop_Sudoku_TextBox).Casilla
casilla.Valor = pista
casilla.EsPista = True
Me.refrescaCasillas()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
Try
Dim filename As String = _creadorPdf.creaPdfSudoku(Me.sudoku)
'Dim pdf As New AxPdfLib.AxPdf
'pdf.LoadFile(filename)
'Dim pdf As New PdfLib.Pdf
'pdf.LoadFile(filename)
System.Diagnostics.Process.Start(filename)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Llop_Sudoku - Excepción capturada")
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim tamano As Int32
Select Case Me.ComboBox1.SelectedIndex
Case 0
tamano = sudoku.CUATRO_X_CUATRO
Case 1, 2
tamano = sudoku.SEIS_X_SEIS
Case 3
tamano = sudoku.NUEVE_X_NUEVE
Case 4, 5
tamano = sudoku.DOCE_X_DOCE
Case 6
tamano = sudoku.DIECISEIS_X_DIECISEIS
Case Else
Throw New Exception("Tamaño del sudoku no permitido.")
End Select
Me.Label2.Text = sudoku.getRangoPistasPorDimension(tamano)(0) & " pistas"
Me.Label9.Text = sudoku.getRangoPistasPorDimension(tamano)(1) & " pistas"
Me.TrackBar1.Minimum = sudoku.getRangoPistasPorDimension(tamano)(0)
Me.TrackBar1.Maximum = sudoku.getRangoPistasPorDimension(tamano)(1)
End Sub
End Class
End Namespace
Clase Llop_Sudoku_Casilla
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Casilla
Private _EstaEscrita As Boolean
Private _EsPista As Boolean
Private _maximoValor As Int32
Private _Valor As Int32
Private _PosiblesValores As New ArrayList
Public Property EsPista() As Boolean
Get
Return _EsPista
End Get
Set(ByVal Value As Boolean)
_EsPista = Value
End Set
End Property
Public Property Valor() As Int32
Get
Return _Valor
End Get
Set(ByVal Value As Int32)
If Value < 0 Or Value > Me._maximoValor Then
Throw New Exception("El valor no está permitido.")
End If
_Valor = Value
If _Valor = 0 Then
_EstaEscrita = False
Else
_EstaEscrita = True
End If
End Set
End Property
Public ReadOnly Property EstaEscrita() As Boolean
Get
Return _EstaEscrita
End Get
End Property
Public Sub New(ByVal maximoValor As Int32)
Me._maximoValor = maximoValor
Me._EsPista = False
Me.borrarValor()
End Sub
Public Sub borrarValor()
Me.Valor = 0
End Sub
Public Sub anadePosibleValor(ByVal posibleValor As Int32)
Me._PosiblesValores.Add(posibleValor)
End Sub
Public Function getNumeroPosiblesValores() As Int32
Return Me._PosiblesValores.Count()
End Function
Public Function getPosibleValor(ByVal indice As Int32) As Int32
Return Me._PosiblesValores.Item(indice)
End Function
Public Overloads Overrides Function Equals(ByVal objeto As Object) As Boolean
'Miramos que objeto no sea nulo, y que sea del tipo 'LlopID3TagInfo'.
If objeto Is Nothing Or Not Me.GetType() Is objeto.GetType() Then
Return False
End If
Dim otraCasilla As Llop_Sudoku_Casilla = CType(objeto, Llop_Sudoku_Casilla)
If Not Me.Valor = otraCasilla.Valor Or Not _
Me.getNumeroPosiblesValores = otraCasilla.getNumeroPosiblesValores() Then
Return False
End If
Dim switch As Boolean
Dim i As Int32
Dim j As Int32
Dim posibleValor As Int32
For i = 0 To Me.getNumeroPosiblesValores
posibleValor = Me.getPosibleValor(i)
switch = True
For j = 0 To Me.getNumeroPosiblesValores
If posibleValor = otraCasilla.getPosibleValor(j) Then
switch = False
Exit For
End If
Next j
If switch Then
Return False
End If
Next i
Return True
End Function
End Class
End Namespace
Clase Llop_Sudoku_ColumnaRegiones
Namespace Llop_Sudoku
Public Class Llop_Sudoku_ColumnaRegiones : Inherits Llop_Sudoku_FilaRegiones
End Class
End Namespace
Clase Llop_Sudoku_ColumnaCasillas
Namespace Llop_Sudoku
Public Class Llop_Sudoku_ColumnaCasillas : Inherits Llop_Sudoku_FilaCasillas
End Class
End Namespace
Clase Llop_Sudoku_Evaluacion
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Evaluacion
Private _mensaje As String
Private _numeroRegionesConError As Int32
Private _regionesConError As ArrayList
Public ReadOnly Property Mensaje() As String
Get
Return Me._mensaje
End Get
End Property
Public ReadOnly Property RegionConError(ByVal indice As Int32) As Int32
Get
Return Me._regionesConError.Item(indice)
End Get
End Property
Public ReadOnly Property NumeroRegionesConError() As Int32
Get
Return Me._numeroRegionesConError
End Get
End Property
Public Sub New(ByVal nuevasRegionesConError As ArrayList)
Me._regionesConError = nuevasRegionesConError
Me._numeroRegionesConError = nuevasRegionesConError.Count
If Me._numeroRegionesConError = 0 Then
Me._mensaje = "¡Por ahora bien!"
Else
Me._mensaje = "Algo falla en las regiones coloreadas."
End If
End Sub
End Class
End Namespace
Clase Llop_Sudoku_FilaCasillas
Namespace Llop_Sudoku
Public Class Llop_Sudoku_FilaCasillas
Private _casillas As New ArrayList
Public Function getCasilla(ByVal indice As Int32) As Llop_Sudoku_Casilla
Return CType(_casillas.Item(indice), Llop_Sudoku_Casilla)
End Function
Public Sub anadeCasilla(ByVal nuevaCasilla As Llop_Sudoku_Casilla)
_casillas.Add(nuevaCasilla)
End Sub
End Class
End Namespace
![]()
Clase Llop_Sudoku_FilaRegiones
Namespace Llop_Sudoku
Public Class Llop_Sudoku_FilaRegiones
Private regiones As ArrayList
End Class
End Namespace
![]()
Clase Llop_Sudoku_Region
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Region
Private _numeroFilas As Int32
Private _numeroColumnas As Int32
Private _filas As New ArrayList
Private _columnas As New ArrayList
Public ReadOnly Property NumeroFilas() As Int32
Get
Return _numeroFilas
End Get
End Property
Public ReadOnly Property NumeroColumnas() As Int32
Get
Return _numeroColumnas
End Get
End Property
Public Sub New(ByVal arrayCasillas As Array)
_numeroFilas = arrayCasillas.GetLength(0)
_numeroColumnas = arrayCasillas.GetLength(1)
' Rellenar el array de filas
Dim i As Int32
Dim j As Int32
Dim fila As Llop_Sudoku_FilaCasillas
For i = 0 To _numeroFilas - 1
fila = New Llop_Sudoku_FilaCasillas
For j = 0 To _numeroColumnas - 1
fila.anadeCasilla(arrayCasillas.GetValue(i, j))
Next j
_filas.Add(fila)
Next i
' Rellenar el array de columnas.
Dim columna As Llop_Sudoku_ColumnaCasillas
For j = 0 To _numeroColumnas - 1
columna = New Llop_Sudoku_ColumnaCasillas
For i = 0 To _numeroFilas - 1
columna.anadeCasilla(arrayCasillas.GetValue(i, j))
Next i
_columnas.Add(columna)
Next j
End Sub
Public Function getCasilla(ByVal fila As Int32, ByVal columna As Int32) As Llop_Sudoku_Casilla
Dim var As Llop_Sudoku_FilaCasillas = CType(_filas.Item(fila), Llop_Sudoku_FilaCasillas)
Return var.getCasilla(columna)
End Function
Public Function getFilaCasillas(ByVal indice As Int32) As Llop_Sudoku_FilaCasillas
Return CType(_filas.Item(indice), Llop_Sudoku_FilaCasillas)
End Function
Public Function getColumnaCasillas(ByVal indice As Int32) As Llop_Sudoku_ColumnaCasillas
Return CType(_columnas.Item(indice), Llop_Sudoku_ColumnaCasillas)
End Function
End Class
End Namespace
![]()
Clase Llop_Sudoku_Solucion
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Solucion
Private _soluciones As New ArrayList
Private _numeroSolucionesDisponibles As Int32
Private _numeroSolucionesReal As String
Private _calificacion As String
Private _tiempo As Int32
Public ReadOnly Property Solucion(ByVal indice As Int32) As String
Get
Return _soluciones.Item(indice)
End Get
End Property
Public ReadOnly Property NumeroSolucionesDisponibles() As Int32
Get
Return _numeroSolucionesDisponibles
End Get
End Property
Public ReadOnly Property NumeroSolucionesReal() As String
Get
Return _numeroSolucionesReal
End Get
End Property
Public ReadOnly Property Calificacion() As String
Get
Return _calificacion
End Get
End Property
Public ReadOnly Property Tiempo() As Int32
Get
Return _tiempo
End Get
End Property
Public Sub New(ByVal solucion As String)
Dim pivote1 As Int32
If solucion.StartsWith("0 ") Then
Me._numeroSolucionesDisponibles = 0
Me._numeroSolucionesReal = solucion.Substring(0, 12)
Me._calificacion = solucion.Substring(14, 19)
pivote1 = solucion.IndexOf(" ms")
Me._tiempo = Int32.Parse(solucion.Substring(40, pivote1 - 40))
Return
End If
Dim pivote2 As Int32 = solucion.IndexOf(", rating ")
Dim arrSols As String() = solucion.Substring(0, pivote2).Split("#")
Dim nulo As Char
For pivote1 = 0 To arrSols.Length - 2
Me._soluciones.Add(arrSols(pivote1))
Next pivote1
Me._numeroSolucionesDisponibles = _soluciones.Count
Me._numeroSolucionesReal = arrSols(pivote1)
pivote1 = pivote2 + 9
pivote2 = solucion.IndexOf(", time ")
Me._calificacion = solucion.Substring(pivote1, pivote2 - pivote1)
pivote1 = pivote2 + 7
pivote2 = solucion.IndexOf(" ms")
Me._tiempo = Int32.Parse(solucion.Substring(pivote1, pivote2 - pivote1))
End Sub
End Class
End Namespace
![]()
Clase Llop_Sudoku_Solucionador
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Solucionador
Private sudoku As Llop_Sudoku_Sudoku
Public Shared metodoIntermedioUno()
End Class
End Namespace
![]()
Clase Llop_Sudoku_Sudoku
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Sudoku : Inherits Sudoku
Private _esGenerado As Boolean = False
Private _problema As Problema
Private _filas As New ArrayList
Private _columnas As New ArrayList
Private _regiones As Array
Public ReadOnly Property EsGenerado() As Boolean
Get
Return Me._esGenerado
End Get
End Property
Public ReadOnly Property Problema() As Problema
Get
Return _problema
End Get
End Property
Public ReadOnly Property EstaVacio() As Boolean
Get
For i As Int32 = 0 To Me.numeroFilas - 1
For j As Int32 = 0 To Me.numeroColumnas - 1
If Me.Casilla(i, j).EstaEscrita Then
Return False
End If
Next j
Next i
Return True
End Get
End Property
Public ReadOnly Property EstaSolucionado() As Boolean
Get
If Not Me.EstaLleno Then
Return False
End If
Return validaSolucion(Me.toInt32Array)
End Get
End Property
Private Function validaSolucion(ByVal sol As Int32()()) As Boolean
Dim i As Int32
Dim j As Int32
Dim m As Int32
Dim n As Int32
Dim coordX As Int32
Dim coordY As Int32
For i = 0 To Me.numeroFilas - 1
Dim restriccionFila(Me.numeroFilas) As Int32
For j = 0 To Me.numeroColumnas - 1
restriccionFila(sol(i)(j)) += 1
Next j
For j = 0 To Me.numeroColumnas - 1
If Not restriccionFila(j) = 1 Then
Return False
End If
Next j
Next i
For j = 0 To Me.numeroColumnas - 1
Dim restriccionColumna(Me.numeroColumnas) As Int32
For i = 0 To Me.numeroFilas - 1
restriccionColumna(sol(i)(j)) += 1
Next i
For i = 0 To Me.numeroFilas - 1
If Not restriccionColumna(i) = 1 Then
Return False
End If
Next i
Next j
For i = 0 To Me.numeroColumnasRegion - 1
For j = 0 To Me.numeroFilasRegion - 1
Dim restriccionRegion(Me.numeroCasillasRegion) As Int32
For m = 0 To Me.numeroFilasRegion - 1
For n = 0 To Me.numeroColumnasRegion - 1
coordX = i * Me.numeroFilasRegion + m
coordY = j * Me.numeroColumnasRegion + n
restriccionRegion(sol(coordX)(coordY)) += 1
Next n
Next m
For m = 0 To Me.numeroCasillasRegion - 1
If Not restriccionRegion(m) = 1 Then
Return False
End If
Next m
Next j
Next i
Return True
End Function
Public ReadOnly Property EstaLleno() As Boolean
Get
For i As Int32 = 0 To Me.numeroFilas - 1
For j As Int32 = 0 To Me.numeroColumnas - 1
If Not Me.Casilla(i, j).EstaEscrita Then
Return False
End If
Next j
Next i
Return True
End Get
End Property
Public ReadOnly Property Casilla(ByVal fila As Int32, ByVal columna As Int32) As Llop_Sudoku_Casilla
Get
Dim var As Llop_Sudoku_FilaCasillas = CType(_filas.Item(fila), Llop_Sudoku_FilaCasillas)
Return var.getCasilla(columna)
End Get
End Property
Public ReadOnly Property CasillaRegion(ByVal filaRegion As Int32, ByVal columnaRegion As Int32, ByVal filaCasilla As Int32, ByVal columnaCasilla As Int32) As Llop_Sudoku_Casilla
Get
Dim reg As Llop_Sudoku_Region = CType(_regiones.GetValue(filaRegion, columnaRegion), Llop_Sudoku_Region)
Dim var As Llop_Sudoku_FilaCasillas = reg.getFilaCasillas(filaCasilla)
Return var.getCasilla(columnaCasilla)
End Get
End Property
Public Sub New(ByVal numFil As Int32, ByVal numCol As Int32, ByVal numFilReg As Int32, ByVal numColReg As Int32)
MyBase.New(numFil, numCol, numFilReg, numColReg)
Dim casillas As Array = Array.CreateInstance(GetType(Llop_Sudoku_Casilla), numFil, numCol)
Dim i As Int32
Dim j As Int32
For i = 0 To numFil - 1
For j = 0 To numCol - 1
casillas.SetValue(New Llop_Sudoku_Casilla(Me.numeroCasillasRegion), i, j)
Next j
Next i
' Rellenar la matriz de regiones.
_regiones = Array.CreateInstance(GetType(Llop_Sudoku_Region), numColReg, numFilReg)
Dim casillasRegion As Array
Dim region As Llop_Sudoku_Region
Dim casilla As Llop_Sudoku_Casilla
Dim m As Int32
Dim n As Int32
Dim coordX As Int32
Dim coordY As Int32
For i = 0 To numColReg - 1
For j = 0 To numFilReg - 1
casillasRegion = Array.CreateInstance(GetType(Llop_Sudoku_Casilla), numFilReg, numColReg)
For m = 0 To numFilReg - 1
For n = 0 To numColReg - 1
coordX = i * numFilReg + m
coordY = j * numColReg + n
casillasRegion.SetValue(casillas.GetValue(coordX, coordY), m, n)
Next n
Next m
region = New Llop_Sudoku_Region(casillasRegion)
_regiones.SetValue(region, i, j)
Next j
Next i
' Rellenar las filas y las columnas
Dim fila As Llop_Sudoku_FilaCasillas
For i = 0 To numFil - 1
fila = New Llop_Sudoku_FilaCasillas
For j = 0 To numCol - 1
fila.anadeCasilla(casillas.GetValue(i, j))
Next j
_filas.Add(fila)
Next i
' Rellenar el array de columnas.
Dim columna As Llop_Sudoku_ColumnaCasillas
For j = 0 To numCol - 1
columna = New Llop_Sudoku_ColumnaCasillas
For i = 0 To numFil - 1
columna.anadeCasilla(casillas.GetValue(i, j))
Next i
_columnas.Add(columna)
Next j
End Sub
Private Overloads Sub rellenaValores(ByVal solucion As Int32()())
Me.rellenaValores(solucion, False)
End Sub
Private Overloads Sub rellenaValores(ByVal solucion As Int32()(), ByVal sonPistas As Boolean)
Dim casilla As Llop_Sudoku_Casilla
Dim i As Int32
Dim j As Int32
For i = 0 To Me.numeroFilas - 1
For j = 0 To Me.numeroColumnas - 1
casilla = Me.Casilla(i, j)
casilla.Valor = solucion(i)(j)
If sonPistas And Not casilla.Valor = 0 Then
casilla.EsPista = True
End If
Next j
Next i
End Sub
Public Function getPista(ByVal indice As Int32) As Int32
If Not Me._esGenerado Then
Throw New Exception("Imposible añadir pistas si usted establece el problema.")
End If
Me.setProblema(Me.getProblema)
Dim sol As Solucion = Me.getSolucion
Dim fil As Int32 = Decimal.Floor(indice / Me.numeroColumnas)
Dim col As Int32 = indice Mod Me.numeroColumnas
Dim retorno As Int32 = sol.getSolucion(0)(fil)(col)
Me._problema.getProblema(fil)(col) = retorno
Return retorno
End Function
Public Function generaPuzzle(ByVal numeroPistas As Int32) As Boolean
Me.setNumeroPistas(numeroPistas)
Me._problema = Me.generaProblema
Me._esGenerado = True
Me.rellenaValores(Me._problema.getProblema, True)
Return True
End Function
Public Function evalua() As Llop_Sudoku_Evaluacion
Me.setProblema(Me.getProblema)
If Not Me.getSolucion.getNumeroSoluciones = 1 Then
Throw New Exception("Imposible evaluar - el sudoku no tiene una sola solución.")
End If
Dim regionesConError As New ArrayList
Dim fil As Int32
Dim col As Int32
Dim prob()() As Int32 = Me.toInt32Array
Dim sol()() As Int32 = Me.getSolucion.getSolucion(0)
Dim pivoteReg As Int32
For i As Int32 = 0 To Me.numeroFilas - 1
For j As Int32 = 0 To Me.numeroColumnas - 1
If Not prob(i)(j) = 0 Then
If Not prob(i)(j) = sol(i)(j) Then
fil = Decimal.Floor(i / Me.numeroFilasRegion)
col = Decimal.Floor(j / Me.numeroColumnasRegion)
pivoteReg = fil * Me.numeroFilasRegion + col
If Not regionesConError.Contains(pivoteReg) Then
regionesConError.Add(pivoteReg)
End If
End If
End If
Next j
Next i
Return New Llop_Sudoku_Evaluacion(regionesConError)
End Function
Public Sub vacia()
If Me._esGenerado Then
Me.rellenaValores(Me.getProblema, True)
Return
End If
For i As Int32 = 0 To Me.numeroFilas - 1
For j As Int32 = 0 To Me.numeroColumnas - 1
If Not Me.Casilla(i, j).EsPista Then
Me.Casilla(i, j).borrarValor()
End If
Next j
Next i
End Sub
Public Function getProblema() As Int32()()
If Me._esGenerado Then
Return Me._problema.getProblema
End If
Dim retorno(Me.numeroFilas - 1)() As Int32
Dim ctrl As Boolean = True
For i As Int32 = 0 To Me.numeroFilas - 1
Dim fil(Me.numeroColumnas - 1) As Int32
retorno(i) = fil
For j As Int32 = 0 To Me.numeroFilas - 1
If Me.Casilla(i, j).EsPista Then
retorno(i)(j) = Me.Casilla(i, j).Valor
If ctrl Then
ctrl = False
End If
Else
retorno(i)(j) = 0
End If
Next j
Next i
If ctrl Then
Return Me.toInt32Array
End If
Return retorno
End Function
Public Function toInt32Array() As Int32()()
Dim retorno(Me.numeroFilas - 1)() As Int32
For i As Int32 = 0 To Me.numeroFilas - 1
Dim fil(Me.numeroColumnas - 1) As Int32
retorno(i) = fil
For j As Int32 = 0 To Me.numeroColumnas - 1
retorno(i)(j) = Me.Casilla(i, j).Valor
Next j
Next i
Return retorno
End Function
Public Overrides Function toString() As String
Dim retorno As String = ""
For i As Int32 = 0 To Me.numeroFilas - 1
For j As Int32 = 0 To Me.numeroColumnas - 1
retorno &= Llop_Sudoku_Util.getCaracterSudoku(Me.Casilla(i, j).Valor)
Next j
Next i
Return retorno
End Function
End Class
End Namespace
![]()
Clase Llop_Sudoku_TextBox
Namespace Llop_Sudoku
Public Class Llop_Sudoku_TextBox : Inherits TextBox
Private _EsEditable As Boolean
Private _casilla As Llop_Sudoku_Casilla
Public ReadOnly Property Casilla() As Llop_Sudoku_Casilla
Get
Return Me._casilla
End Get
End Property
Public Property EsEditable() As Boolean
Get
Return Me._EsEditable
End Get
Set(ByVal Value As Boolean)
Me._EsEditable = Value
End Set
End Property
Public Sub New(ByVal lado As Int32, ByVal maximaCapacidad As Int32, ByVal nuevaCasilla As Llop_Sudoku_Casilla)
MyBase.New()
Dim tamFont As Single = lado * (14.25! / 28.0!)
Me.AutoSize = False
Me.BorderStyle = BorderStyle.FixedSingle
Me.Font = New System.Drawing.Font("Microsoft Sans Serif", tamFont, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.MaxLength = maximaCapacidad
Me.Size = New Size(lado, lado)
Me.TextAlign = HorizontalAlignment.Center
Me._EsEditable = True
Me._casilla = nuevaCasilla
End Sub
Public Sub refresca()
If _casilla.EstaEscrita Then
Me.Text = _casilla.Valor
Else
Me.Text = ""
End If
End Sub
' Restricts the entry of characters to digits (including hex),
' the negative sign, the e decimal point, and editing keystrokes (backspace).
Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
MyBase.OnKeyPress(e)
If Not Me._EsEditable Then
e.Handled = True
Return
End If
If [Char].IsDigit(e.KeyChar) Then
' Digits are OK
Try
_casilla.Valor = Int32.Parse(Me.Text & e.KeyChar)
Catch ex As Exception
e.Handled = True
End Try
ElseIf e.KeyChar = vbBack Then
' Backspace key is OK
If Me.Text.Length = 1 Then
_casilla.borrarValor()
Else
_casilla.Valor = Int32.Parse(Me.Text.Substring(0, Me.Text.Length - 1))
End If
Else
' Swallow this invalid key and beep
e.Handled = True
End If
End Sub
Public ReadOnly Property IntValue() As Integer
Get
Return Int32.Parse(Me.Text)
End Get
End Property
Public ReadOnly Property DecimalValue() As Decimal
Get
Return [Decimal].Parse(Me.Text)
End Get
End Property
End Class
End Namespace
![]()
Clase Llop_Sudoku_Util
Namespace Llop_Sudoku
Public Class Llop_Sudoku_Util
Private Shared CaracteresSudoku As Char() = {".", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "#", "*", "~"}
Public Shared ColorNormal As Color = Color.Black
Public Shared ColorPista As Color = Color.Olive
Public Shared ColorError As Color = Color.Tomato
Public Shared Function getDescripcionCalificación(ByVal calificacion As Int32) As String
If calificacion < 2000 Then
Return "¡Chupado!"
ElseIf calificacion < 4000 Then
Return "Niño pequeño"
ElseIf calificacion < 6000 Then
Return "Fácil"
ElseIf calificacion < 8000 Then
Return "Intermedio"
ElseIf calificacion < 10000 Then
Return "Avanzado"
ElseIf calificacion < 12000 Then
Return "Muy chungo"
ElseIf calificacion < 20000 Then
Return "Vas a llorar"
Else
Return "Nivel peninsular"
End If
End Function
Public Shared Function getCaracterSudoku(ByVal valor As Int32) As Char
If CaracteresSudoku.Length <= valor Then
Throw New Exception("No existe un caracter para este valor.")
End If
Return CaracteresSudoku(valor)
End Function
Public Shared Function getValorSudoku(ByVal caracter As Char) As Int32
Dim i As Int32
For i = 0 To CaracteresSudoku.Length - 1
If caracter.Equals(CaracteresSudoku(i)) Then
Return i
End If
Next i
Throw New Exception("No existe un valor para este caracter.")
End Function
Public Shared Function getColor(ByVal fila As Int32, ByVal columna As Int32) As Color
If fila Mod 2 = 0 Then
columna += 1
End If
If columna Mod 2 = 0 Then
Return Color.LightSalmon
End If
Return Color.Beige
End Function
End Class
End Namespace
![]()
Clase CreadorPDF
Imports System.Reflection
Imports System.IO
Imports iTextSharp.text
Namespace Llop_Sudoku
Public Class CreadorPDF
Dim assyName As String = Path.GetFileName([Assembly].GetExecutingAssembly().GetName().CodeBase.ToString())
Dim assyVersion As String = [Assembly].GetExecutingAssembly().GetName().Version.ToString()
Private rnd As New Random
Private fileindex As Int32 = 0
Public Sub New()
End Sub
Public Function creaPdfSudoku(ByVal sudoku As Llop_Sudoku_Sudoku) As String
Dim pid As Int32 = System.Diagnostics.Process.GetCurrentProcess().Id
Dim Filename As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), String.Format("{0}-{1}-{2}.pdf", assyName, pid, fileindex + 1))
'Dim filename As String = "C:\sudoku" & fileindex & ".pdf"
fileindex += 1
Try
' step 1: create a document
Dim document As New Document
' step 2: we set the ContentType and create an instance of the Writer
'string Filename= String.Format("{0}-{1}-{2}.pdf", assyName, pid, rnd.Next(1000));
iTextSharp.text.pdf.PdfWriter.GetInstance(document, New FileStream(Filename, FileMode.Create))
' step 3: add metadata (before document.Open())
document.AddTitle("Llop_Sudoku")
document.AddSubject("Sudoku")
document.AddKeywords("Sudoku")
document.AddCreator("Ensamblado .NET: " + assyName)
document.AddAuthor("Albert Lobo")
document.AddProducer()
' step 4: open the doc
document.Open()
' step 5: Add content to the document
Dim font28 As Font = FontFactory.GetFont(FontFactory.TIMES_BOLDITALIC, 28)
Dim font18 = FontFactory.GetFont(FontFactory.HELVETICA, 18)
'Font font14= FontFactory.GetFont(FontFactory.HELVETICA, 14)
Dim font12 = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 12)
Dim font8 = FontFactory.GetFont(FontFactory.HELVETICA, 8)
Dim fontAnchor = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.UNDERLINE, New Color(0, 0, 255))
'Chunk bullet= new Chunk("\u2022", font18)
document.Add(New Paragraph(vbCr & vbCr & vbCr))
document.Add(New Paragraph(New Chunk("Llop_Sudoku", font28)))
Dim info As String = String.Format("{0}, a las {1}" + vbCr, DateTime.Now.ToString("dddd, dd MMMM, yyyy"), DateTime.Now.ToString("hh:mm:ss tt zzzz"))
document.Add(New Paragraph(New Chunk(info, font12)))
If Not sudoku.getProblema Is Nothing Then
Dim problema()() As Int32 = sudoku.getProblema
Dim widthPercentage As Int32
Select Case sudoku.getNumeroFilas
Case 4
widthPercentage = 25
Case 6
widthPercentage = 40
Case 9
widthPercentage = 60
Case 12
widthPercentage = 80
Case 16
widthPercentage = 90
End Select
Dim bigtable As New iTextSharp.text.pdf.PdfPTable(sudoku.numeroFilasRegion)
bigtable.WidthPercentage = widthPercentage
bigtable.DefaultCell.BorderWidth = 1.2F
bigtable.DefaultCell.Padding = 0.8F
Dim coordX As Int32
Dim coordY As Int32
Dim s As String
For i As Int32 = 0 To sudoku.numeroColumnasRegion - 1
For j As Int32 = 0 To sudoku.numeroFilasRegion - 1
Dim nested As New iTextSharp.text.pdf.PdfPTable(sudoku.numeroColumnasRegion)
nested.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER
nested.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE
nested.DefaultCell.MinimumHeight = 30
For n As Int32 = 0 To sudoku.numeroFilasRegion - 1
For m As Int32 = 0 To sudoku.numeroColumnasRegion - 1
coordX = i * sudoku.numeroFilasRegion + n
coordY = j * sudoku.numeroColumnasRegion + m
If problema(coordX)(coordY) = 0 Then
s = " "
Else
s = problema(coordX)(coordY)
End If
'nested.AddCell(s)
nested.AddCell(New Phrase(New Chunk(s, font18)))
Next m
Next n
bigtable.AddCell(nested)
Next j
Next i
'dim header as String.Format("seed: {0} rating level: {1}\rdifficulty: {2}\r", puzzle.seed, puzzle.ratingLevel+1, puzzle.actualRating)
'Paragraph p1= new Paragraph(new Chunk(header, font12));
'p1.SetLeading(14,14);
'document.Add(p1);
document.Add(New Paragraph(vbCr & vbCr & vbCr))
document.Add(bigtable)
document.Add(New Paragraph(vbCr))
Else
info = "No ha sido posible generar el sudoku."
Dim p1 As New Paragraph(New Chunk(info, font12))
p1.SetLeading(14, 14)
document.Add(p1)
End If
'// step 6: Close document
document.Close()
Catch ex As DocumentException
Console.Error.WriteLine(ex.StackTrace)
Console.Error.WriteLine(ex.Message)
Filename = "--"
End Try
Return Filename
End Function
End Class
End Namespace
¿Comentarios, sugerencias?: llopsite.at.yahoo.es | © 2005-07 Albert Lobo
Última actualización: 24-Feb-2007