Professional Documents
Culture Documents
Torre de Hanoi
Torre de Hanoi
Estructura de Datos
Torre de Hanoi
juego.setVisible(true);
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*/
tablero t;
Thread hiloJuego;
public GUI() {
initComponents();
/**
* Metodo utilizado para inizializar el tablero
*/
int torreAyuda = 0;
torreAyuda = 1;
torreAyuda = 2;
} else {
torreAyuda = 3;
panelTablero.add(t, BorderLayout.CENTER);
this.validate();
/**
*/
JOptionPane.showMessageDialog(this, salida);
botonStart.setEnabled(true);
return;
agregarTablero();
this.hiloJuego.start();
/**
* @return
*/
if (!esNumero(campoNumeroDiscos.getText())) {
if (!esNumero(campoTorreInicial.getText())) {
if (!esNumero(campoTorreFinal.getText())) {
if (!esNumero(campoVelocidad.getText())) {
if (campoTorreInicial.getText().equals(campoTorreFinal.getText())) {
if (!salida.equals("")) {
return salida;
/**
*/
if (cadena.length == 0) {
return false;
}
if (!Character.isDigit(cadena[c])) {
return false;
return true;
*/
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
jToolBar1.add(jLabel1);
getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);
panelTablero.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0,
0)));
panelTablero.setLayout(new java.awt.BorderLayout());
jPanel5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.
RAISED));
jLabel3.setText("Configuración:");
jLabel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.R
AISED));
jLabel4.setText("Num. discos:");
jLabel5.setText("Torre inicial:");
jLabel6.setFont(new java.awt.Font("Calibri", 0, 14));
jLabel6.setText("Torre final:");
jLabel7.setText("Velocidad (ms):");
botonStart.setText("Start");
botonStart.addActionListener(new java.awt.event.ActionListener() {
botonStartActionPerformed(evt);
});
botonReset.setText("Reset");
botonReset.addActionListener(new java.awt.event.ActionListener() {
botonResetActionPerformed(evt);
});
botonPausa.setText("Detener");
botonPausa.addActionListener(new java.awt.event.ActionListener() {
botonPausaActionPerformed(evt);
});
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING,
false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(jPanel5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(jPanel5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(campoVelocidad, javax.swing.GroupLayout.PREFERRED_SIZE,
77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(campoNumeroDiscos,
javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(campoTorreInicial,
javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 77,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(campoTorreFinal, javax.swing.GroupLayout.PREFERRED_SIZE,
77, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addContainerGap())))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(campoNumeroDiscos, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(campoTorreInicial, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(campoTorreFinal, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(campoVelocidad, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31,
Short.MAX_VALUE)
.addComponent(botonStart)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(botonPausa)
.addComponent(botonReset))
.addContainerGap())
);
jPanel6.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.
RAISED));
tabla.setModel(new javax.swing.table.DefaultTableModel(
},
new String [] {
){
};
};
});
jScrollPane1.setViewportView(tabla);
jLabel8.setText("Bitacora de movimientos:");
jLabel8.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.R
AISED));
jLabel9.setText("Torre A:");
jLabel10.setText("Torre B:");
jLabel11.setText("Torre C:");
jLabel12.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.
RAISED));
campoTorreA.setEditable(false);
campoTorreA.setText("0");
campoTorreB.setEditable(false);
campoTorreB.setText("0");
campoTorreC.setEditable(false);
campoTorreC.setText("0");
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12)
.addGap(8, 8, 8)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(campoTorreC, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(jLabel10)
.addComponent(campoTorreA, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING,
false)
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelTablero, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, 678, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel2.add(jSeparator1, java.awt.BorderLayout.PAGE_START);
jLabel2.setText("Torres de Hanoi");
jPanel2.add(jLabel2, java.awt.BorderLayout.LINE_END);
getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);
pack();
}// </editor-fold>//GEN-END:initComponents
botonStart.setEnabled(false);
modelo.getDataVector().clear();
tabla.validate();
campoTorreA.setText("0");
campoTorreB.setText("0");
campoTorreC.setText("0");
start();
}//GEN-LAST:event_botonStartActionPerformed
campoNumeroDiscos.setText("");
campoTorreInicial.setText("");
campoTorreFinal.setText("");
campoVelocidad.setText("");
tabla.validate();
tabla.repaint();
campoTorreA.setText("0");
campoTorreB.setText("0");
campoTorreC.setText("0");
if(hiloJuego.isAlive()){
hiloJuego.stop();
botonStart.setEnabled(true);
}//GEN-LAST:event_botonResetActionPerformed
if (hiloJuego.isAlive()) {
hiloJuego.stop();
botonStart.setEnabled(true);
}//GEN-LAST:event_botonPausaActionPerformed
/**
*/
java.awt.EventQueue.invokeLater(new Runnable() {
new GUI().setVisible(true);
}
});
import java.awt.Graphics;
import java.util.Stack;
/**
*/
private Stack<Disco> todosLosDiscos; //Representa todos los disco que tiene la torre actual
/**
* @param posicionX Es la posicion promedio del palo en X, promedio por que si es de X0=5 y
X1=15 la posicion de x sera 10
* @param posicionY Es la posicion promedio del palo en Y, Explicacion arriba
*/
this.posicionX = posicionX;
this.posicionY = posicionY;
this.posicionXFinal = posicionXFinal;
this.posicionYFinal = posicionYFinal;
public Torre(){
/**
*/
return todosLosDiscos.peek();
/**
*/
return todosLosDiscos.pop();
/**
todosLosDiscos.push(new Disco(numeroDisco));
/**
* Metodo utilizado para obtener una copia de la pila de los discos de la torre
*/
/**
* @param g
*/
g.fill3DRect(getPosicionX(),getPosicionY(),getPosicionXFinal(),getPosicionYFinal(), true);
return posicionX;
this.posicionX = posicionX;
}
public int getPosicionY() {
return posicionY;
this.posicionY = posicionY;
return posicionXFinal;
this.posicionXFinal = posicionXFinal;
return posicionYFinal;
this.posicionYFinal = posicionYFinal;
class Disco{
//Representa el numero de disco que es,Aparte nos sirve para calcular el tamaño
int numeroDisco;
public Disco(int numeroDisco){
this.numeroDisco = numeroDisco;
/**
*/
/**
*/
return numeroDisco;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
File f;
FileWriter ficheroEscritura;
BufferedWriter escribir;
public generarFichero() {
if (!f.exists()) {
try {
f.createNewFile();
} catch (Exception e) {
return;
try {
} catch (Exception e) {
return;
/**
* Metodo encargado de generar un archivo de texto con los datos de la tabla y los totales de
movimientos
*/
int totalColumnas = 4;
int i=0;
//Escribimos el titulo
try {
escribir.newLine();
escribir.newLine();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error al escribir" );
try {
escribir.newLine();
i=0;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al escribir una linea "+e);
return;
try {
escribir.newLine();
escribir.newLine();
escribir.newLine();
escribir.write("\t\tTotal de movimientos:"+(totalTorreA+totalTorreB+totalTorreC));
escribir.newLine();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error al escribir" );
try {
escribir.close();
ficheroEscritura.close();
} catch (Exception e) {}
Desktop d = Desktop.getDesktop();
try {
d.open(f);
} catch (Exception e) {}
new generarFichero();
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
/**
*/
/**
* @param torreAyuda Este es el poste que se usara como ayuda para pasar los discos
*/
public tablero(int torreInicio, int torreFin, int torreAyuda, int velocidad, int
numeroDiscos,JButton botonStart,JTextField campoTorreA,JTextField campoTorreB,JTextField
campoTorreC,JTable tabla) {
this.torreInicio = torreInicio;
this.torreFin = torreFin;
this.torreAyuda = torreAyuda;
this.velocidad = velocidad;
this.numeroDiscos = numeroDiscos;
//Creamos una referencia a sia los campo del formulario para poderlos actualizar
this.botonStart=botonStart;
this.campoTorreA = campoTorreA;
this.campoTorreB = campoTorreB;
this.campoTorreC = campoTorreC;
this.tabla = tabla;
@Override
Image i = createImage(this.getSize().width,this.getSize().height);
torres[0].setPosicionX(this.getSize().width / 4);
torres[0].setPosicionY(10);
torres[0].setPosicionXFinal(6);
torres[0].setPosicionYFinal(this.getSize().height - 20);
torres[1].setPosicionX(this.getSize().width / 2);
torres[1].setPosicionY(10);
torres[1].setPosicionXFinal(6);
torres[1].setPosicionYFinal(this.getSize().height - 20);
torres[2].setPosicionX((this.getSize().width / 4) * 3);
torres[2].setPosicionY(10);
torres[2].setPosicionXFinal(6);
torres[2].setPosicionYFinal(this.getSize().height - 20);
gra.setColor(Color.red);
for (; !pila.isEmpty() ;) {
gra.setColor(Color.cyan);
totalDiscos--;
g.drawImage(i, 0, 0, this);
this.validate();
inizializarTablero();
try {
Thread.sleep(velocidad);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e);
return;
generarF.generarFichero(tabla,Integer.parseInt(campoTorreA.getText()),Integer.parseInt(campoTo
rreB.getText()),Integer.parseInt(campoTorreC.getText()));
botonStart.setEnabled(true);
/**
* @param inicio
* @param fin
* @param ayuda
* @param numeroDiscos
*/
public void pasar(int inicio, int fin, int ayuda, int numeroDiscos) {
//Se lleva un solo disco (el que queda) de la Torre origen a la destino
if (numeroDiscos == 1) {
pasar(inicio, fin);
return;
} else {
pasar(inicio, fin);
return;
/**
* Metodo encargado de pasar un solo disco desde su posicion inicial a la posicion en la que se
quieren los discos
* @param inicio
* @param fin
*/
contadorMovimientos++;
torres[fin].push(disco.getNumero());
if(fin ==0){
campoTorreA.setText( (Integer.parseInt(campoTorreA.getText())+1)+"" );
else if(fin==1){
campoTorreB.setText( (Integer.parseInt(campoTorreB.getText())+1)+"" );
else{
campoTorreC.setText( (Integer.parseInt(campoTorreC.getText())+1)+"" );
modelo.addRow(new Object[]{contadorMovimientos,disco.getNumero(),inicio+1,fin+1,});
//repintamos el tablero
this.repaint();
try {
Thread.sleep(velocidad);
} catch (Exception e) {
JOptionPane.showMessageDialog(this,e );
torres[torreInicio].push(c);
}
this.repaint();
Diagrama de Clases