You are on page 1of 39

2022

Integrantes del Equipo:

Prieto Juárez Luis Carlos

León Rodríguez América Patricia

Aguilar Orosco Briana Itzel

Estructura de Datos
Torre de Hanoi

[NOMBRE DE LA COMPAÑÍA] | [Dirección de la compañía]


Codigo Fuente:

public class Main {

public static void main(String[] args) {

GUI juego = new GUI();

juego.setVisible(true);

import java.awt.BorderLayout;

import javax.swing.JButton;

import javax.swing.JOptionPane;

import javax.swing.table.DefaultTableModel;

/**

* @author Luis Carlos Prieto Juarez

*/

public class GUI extends javax.swing.JFrame{

tablero t;

Thread hiloJuego;

/** Creates new form GUI */

public GUI() {

initComponents();

/**
* Metodo utilizado para inizializar el tablero

*/

private void agregarTablero() {

int torreInicio = Integer.parseInt(campoTorreInicial.getText());

int torreFinal = Integer.parseInt(campoTorreFinal.getText());

int torreAyuda = 0;

int numeroDiscos = Integer.parseInt(campoNumeroDiscos.getText());

if ((torreInicio == 2 || torreInicio == 3) && (torreFinal == 2 || torreFinal == 3)) {

torreAyuda = 1;

} else if ((torreInicio == 1 || torreInicio == 3) && (torreFinal == 1 || torreFinal == 3)) {

torreAyuda = 2;

} else {

torreAyuda = 3;

int velocidad = Integer.parseInt(campoVelocidad.getText());

t = new tablero(torreInicio - 1, torreFinal - 1, torreAyuda - 1, velocidad, numeroDiscos,


botonStart,campoTorreA,campoTorreB,campoTorreC,tabla);

panelTablero.add(t, BorderLayout.CENTER);

this.validate();

/**

* Metodo encargado de aser correr el mecanismo del juego

*/

private void start() {

String salida = validarCampos();


if (!salida.equals("")) {

JOptionPane.showMessageDialog(this, salida);

botonStart.setEnabled(true);

return;

agregarTablero();

this.hiloJuego = new Thread(t);

this.hiloJuego.start();

// End of variables declaration

/**

* Validamos que todos los campos esten correctamente introducidos

* @return

*/

private String validarCampos() {

String salida = "";

if (!esNumero(campoNumeroDiscos.getText())) {

salida += "--> El numero de discos es invalido\n";

if (!esNumero(campoTorreInicial.getText())) {

salida += "--> El disco inicial es invalido\n";

} else if (Integer.parseInt(campoTorreInicial.getText()) < 1 ||


Integer.parseInt(campoTorreInicial.getText()) > 3) {

salida += "--> El disco inicial esta fuera de rango (1,2,3)\n";

if (!esNumero(campoTorreFinal.getText())) {

salida += "--> El disco final es invalido\n";


} else if (Integer.parseInt(campoTorreFinal.getText()) < 1 ||
Integer.parseInt(campoTorreFinal.getText()) > 3) {

salida += "--> El disco final esta fuera de rango (1,2,3)\n";

if (!esNumero(campoVelocidad.getText())) {

salida += "--> El disco final es invalido\n";

if (campoTorreInicial.getText().equals(campoTorreFinal.getText())) {

salida += "La torre inicial y final no pueden ser iguales\n";

if (!salida.equals("")) {

salida = "Para continuar verifique los siguientes puntos\n\n\t" + salida;

return salida;

/**

* Metodo encargado de validar si el el texto de un campo es un numero entero

* @param campo es el texto que se validara para saber si es numero entero

* @return devulve true si es numero entero, false si no es numero entero o si no es un numero


valido

*/

private boolean esNumero(String campo) {

char[] cadena = campo.toCharArray();

if (cadena.length == 0) {

return false;
}

for (int c = 0; c < cadena.length; c++) {

if (!Character.isDigit(cadena[c])) {

return false;

return true;

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents

private void initComponents() {

jToolBar1 = new javax.swing.JToolBar();

jLabel1 = new javax.swing.JLabel();

jPanel1 = new javax.swing.JPanel();

panelTablero = new javax.swing.JPanel();

jPanel4 = new javax.swing.JPanel();

jPanel5 = new javax.swing.JPanel();

jLabel3 = new javax.swing.JLabel();

campoNumeroDiscos = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

jLabel5 = new javax.swing.JLabel();

campoTorreInicial = new javax.swing.JTextField();

jLabel6 = new javax.swing.JLabel();


campoTorreFinal = new javax.swing.JTextField();

jLabel7 = new javax.swing.JLabel();

campoVelocidad = new javax.swing.JTextField();

botonStart = new javax.swing.JButton();

botonReset = new javax.swing.JButton();

botonPausa = new javax.swing.JButton();

jPanel6 = new javax.swing.JPanel();

jScrollPane1 = new javax.swing.JScrollPane();

tabla = new javax.swing.JTable();

jLabel8 = new javax.swing.JLabel();

jLabel9 = new javax.swing.JLabel();

jLabel10 = new javax.swing.JLabel();

jLabel11 = new javax.swing.JLabel();

jLabel12 = new javax.swing.JLabel();

campoTorreA = new javax.swing.JTextField();

campoTorreB = new javax.swing.JTextField();

campoTorreC = new javax.swing.JTextField();

jPanel2 = new javax.swing.JPanel();

jSeparator1 = new javax.swing.JSeparator();

jLabel2 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("LAS TORRES DE HANOI");

jToolBar1.setBackground(new java.awt.Color(0, 102, 153));

jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

jToolBar1.setFloatable(false);

jToolBar1.setRollover(true);

jToolBar1.setPreferredSize(new java.awt.Dimension(100, 100));


jLabel1.setFont(new java.awt.Font("Century Schoolbook", 1, 36));

jLabel1.setForeground(new java.awt.Color(255, 255, 255));

jLabel1.setText(" El juego de las Torres de Hanoi");

jToolBar1.add(jLabel1);

getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

jPanel1.setBackground(new java.awt.Color(204, 204, 255));

panelTablero.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0,
0)));

panelTablero.setMinimumSize(new java.awt.Dimension(2, 2));

panelTablero.setLayout(new java.awt.BorderLayout());

jPanel5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.
RAISED));

jLabel3.setFont(new java.awt.Font("Verdana", 1, 14));

jLabel3.setText("Configuración:");

jLabel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.R
AISED));

jLabel4.setFont(new java.awt.Font("Calibri", 0, 14));

jLabel4.setText("Num. discos:");

jLabel5.setFont(new java.awt.Font("Calibri", 0, 14));

jLabel5.setText("Torre inicial:");
jLabel6.setFont(new java.awt.Font("Calibri", 0, 14));

jLabel6.setText("Torre final:");

jLabel7.setFont(new java.awt.Font("Calibri", 0, 14));

jLabel7.setText("Velocidad (ms):");

botonStart.setText("Start");

botonStart.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

botonStartActionPerformed(evt);

});

botonReset.setText("Reset");

botonReset.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

botonResetActionPerformed(evt);

});

botonPausa.setText("Detener");

botonPausa.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

botonPausaActionPerformed(evt);

});

javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);

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)

.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 86,


javax.swing.GroupLayout.PREFERRED_SIZE)

.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()

.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 86,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))

.addGroup(jPanel5Layout.createSequentialGroup()

.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 86,


javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))

.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))))

.addGap(11, 11, 11))

.addGroup(jPanel5Layout.createSequentialGroup()

.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(botonStart, javax.swing.GroupLayout.DEFAULT_SIZE, 179,


Short.MAX_VALUE)

.addGroup(jPanel5Layout.createSequentialGroup()

.addComponent(botonPausa, javax.swing.GroupLayout.PREFERRED_SIZE, 85,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(botonReset, javax.swing.GroupLayout.DEFAULT_SIZE, 88,


Short.MAX_VALUE)))

.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)

.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 24,


javax.swing.GroupLayout.PREFERRED_SIZE)

.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)

.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 24,


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)

.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 24,


javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 24,


javax.swing.GroupLayout.PREFERRED_SIZE)

.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 Object [][] {

},

new String [] {

"Num. Mov.", "Disco", "De", "A"

){

Class[] types = new Class [] {

java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class,


java.lang.Integer.class

};

boolean[] canEdit = new boolean [] {

false, false, false, false

};

public Class getColumnClass(int columnIndex) {


return types [columnIndex];

public boolean isCellEditable(int rowIndex, int columnIndex) {

return canEdit [columnIndex];

});

jScrollPane1.setViewportView(tabla);

jLabel8.setFont(new java.awt.Font("Verdana", 1, 14));

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.setFont(new java.awt.Font("Verdana", 1, 14));

jLabel12.setText("Contadores por torre:");

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");

javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);

jPanel6.setLayout(jPanel6Layout);

jPanel6Layout.setHorizontalGroup(

jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel6Layout.createSequentialGroup()

.addContainerGap()

.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 421,


Short.MAX_VALUE)

.addGroup(jPanel6Layout.createSequentialGroup()

.addComponent(jLabel9)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(campoTorreA, javax.swing.GroupLayout.PREFERRED_SIZE, 96,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jLabel10)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(campoTorreB, javax.swing.GroupLayout.DEFAULT_SIZE, 92,


Short.MAX_VALUE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jLabel11)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(campoTorreC, javax.swing.GroupLayout.PREFERRED_SIZE, 94,


javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 421,
Short.MAX_VALUE)

.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()

.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 26,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131,


javax.swing.GroupLayout.PREFERRED_SIZE)

.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(campoTorreB, javax.swing.GroupLayout.DEFAULT_SIZE, 22,


Short.MAX_VALUE)

.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())

);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

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()

.addComponent(panelTablero, javax.swing.GroupLayout.DEFAULT_SIZE, 134,


Short.MAX_VALUE)

.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.setPreferredSize(new java.awt.Dimension(100, 35));

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

private void botonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-


FIRST:event_botonStartActionPerformed

// TODO add your handling code here:

botonStart.setEnabled(false);

DefaultTableModel modelo = (DefaultTableModel) tabla.getModel();

modelo.getDataVector().clear();

tabla.validate();

campoTorreA.setText("0");

campoTorreB.setText("0");

campoTorreC.setText("0");

start();

}//GEN-LAST:event_botonStartActionPerformed

private void botonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-


FIRST:event_botonResetActionPerformed

// TODO add your handling code here:

campoNumeroDiscos.setText("");

campoTorreInicial.setText("");

campoTorreFinal.setText("");

campoVelocidad.setText("");

DefaultTableModel modelo = (DefaultTableModel) tabla.getModel();


modelo.getDataVector().clear();

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

private void botonPausaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-


FIRST:event_botonPausaActionPerformed

// TODO add your handling code here:

if (hiloJuego.isAlive()) {

hiloJuego.stop();

botonStart.setEnabled(true);

}//GEN-LAST:event_botonPausaActionPerformed

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new GUI().setVisible(true);
}

});

// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JButton botonPausa;

private javax.swing.JButton botonReset;

private javax.swing.JButton botonStart;

private javax.swing.JTextField campoNumeroDiscos;

private javax.swing.JTextField campoTorreA;

private javax.swing.JTextField campoTorreB;

private javax.swing.JTextField campoTorreC;

private javax.swing.JTextField campoTorreFinal;

private javax.swing.JTextField campoTorreInicial;

private javax.swing.JTextField campoVelocidad;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel10;

private javax.swing.JLabel jLabel11;

private javax.swing.JLabel jLabel12;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JLabel jLabel6;

private javax.swing.JLabel jLabel7;

private javax.swing.JLabel jLabel8;

private javax.swing.JLabel jLabel9;

private javax.swing.JPanel jPanel1;

private javax.swing.JPanel jPanel2;

private javax.swing.JPanel jPanel4;


private javax.swing.JPanel jPanel5;

private javax.swing.JPanel jPanel6;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JSeparator jSeparator1;

private javax.swing.JToolBar jToolBar1;

private javax.swing.JPanel panelTablero;

private javax.swing.JTable tabla;

// End of variables declaration//GEN-END:variables

import java.awt.Graphics;

import java.util.Stack;

/**

* @author Luis Carlos Prieto Juarez

*/

public class Torre {

private Stack<Disco> todosLosDiscos; //Representa todos los disco que tiene la torre actual

private int posicionX; //Representa la posicion inicial en X

private int posicionY; //Representa la posicion inicial en Y

private int posicionXFinal; //Representa la posicion Final en X

private int posicionYFinal; //Representa la posicion Final en Y

/**

* Constructor inicializa la pila con todos los discos

* @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

*/

public Torre(int posicionX,int posicionY,int posicionXFinal,int posicionYFinal){

this.posicionX = posicionX;

this.posicionY = posicionY;

this.posicionXFinal = posicionXFinal;

this.posicionYFinal = posicionYFinal;

todosLosDiscos = new Stack<Disco>();

public Torre(){

todosLosDiscos = new Stack<Disco>();

/**

* Metodo que devuelve el ultimo disco de la torre,Pero sin eliminarlo

* @return Devuelve el disco del tope de la torre

*/

public Disco peek(){

return todosLosDiscos.peek();

/**

* Metodo utilizado para eliminar el ultimo disco de la pila y devolverlo

* @return Devulve el disco de mas arriba de la torre eliminandolo de la torre

*/

public Disco getDisco(){

return todosLosDiscos.pop();

/**

* Metodo encargado de agregar un disco a al tope de la torre

* @param numeroDisco Es el numero de disco que se le asignara al nuevo disco


*/

public void push(int numeroDisco){

todosLosDiscos.push(new Disco(numeroDisco));

/**

* Metodo utilizado para obtener una copia de la pila de los discos de la torre

* @return Devuelve la pila de todos los discos de la torre

*/

public Stack<Disco> clonarPilaDiscos(){

return (Stack<Disco>) todosLosDiscos.clone();

/**

* Metodo encargado de pintar el palo con todos sus discos

* @param g

*/

public void paint(Graphics g){

Stack<Disco> todosLosDiscosCopia = (Stack) todosLosDiscos.clone();

g.fill3DRect(getPosicionX(),getPosicionY(),getPosicionXFinal(),getPosicionYFinal(), true);

public int getPosicionX() {

return posicionX;

public void setPosicionX(int posicionX) {

this.posicionX = posicionX;

}
public int getPosicionY() {

return posicionY;

public void setPosicionY(int posicionY) {

this.posicionY = posicionY;

public int getPosicionXFinal() {

return posicionXFinal;

public void setPosicionXFinal(int posicionXFinal) {

this.posicionXFinal = posicionXFinal;

public int getPosicionYFinal() {

return posicionYFinal;

public void setPosicionYFinal(int posicionYFinal) {

this.posicionYFinal = posicionYFinal;

class Disco{

//Representa el numero de disco que es,Aparte nos sirve para calcular el tamaño

//El tamaño del mismo multiplicando el numero por 10

int numeroDisco;
public Disco(int numeroDisco){

this.numeroDisco = numeroDisco;

/**

* Metodo encargado de decir el tamaño del disco

* @return regresa el tamaño del disco

*/

public int getSize(){

return numeroDisco * 10;

/**

* Metodo usado para obtener el numero de disco

* @return regresa el numero de disco

*/

public int getNumero(){

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;

/**

* @author Luis Carlos Prieto Juarez


*/

public class generarFichero {

File f;

FileWriter ficheroEscritura;

BufferedWriter escribir;

public generarFichero() {

f = new File("Torres de Hanoi.txt");

if (!f.exists()) {

try {

f.createNewFile();

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error al crear el fichero");

return;

try {

ficheroEscritura = new FileWriter(f, false);

escribir = new BufferedWriter(ficheroEscritura);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error al cargar el fichero");

return;

/**
* Metodo encargado de generar un archivo de texto con los datos de la tabla y los totales de
movimientos

* @param tabla es la tabla que contiene todos los movimientos

* @param totalTorreA Total de movimientos en la torre A

* @param totalTorreB Total de movimientos en la torre B

* @param totalTorreC Total de movimientos en la torre C

*/

public void generarFichero(JTable tabla,int totalTorreA,int totalTorreB,int totalTorreC) {

int totalFilas = tabla.getRowCount();

int totalColumnas = 4;

int i=0;

//Escribimos el titulo

try {

escribir.write("\tLas Torres de Hanoi : Estructura De Datos");

escribir.newLine();

escribir.newLine();

} catch (Exception e) {

JOptionPane.showMessageDialog(null,"Error al escribir" );

//Escribimos los datos de la tabla en archivo de texto

for (int c = 0; c < totalFilas; c++) {

try {

escribir.write("Num.Movimiento:"+(Integer)tabla.getValueAt(c, i++) + " |


Disco:"+(Integer)tabla.getValueAt(c, i++)+" | De la torre Num.:"+(Integer)tabla.getValueAt(c,
i++)+" | A la torre Num.:"+(Integer)tabla.getValueAt(c, i++));

escribir.newLine();

i=0;

} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al escribir una linea "+e);

return;

//Escribimos los totales

try {

escribir.newLine();

escribir.write("\tTotal TorreA:"+totalTorreA+"\tTotal torreB:"+totalTorreB+"\tTotal


torreC:"+totalTorreC);

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) {}

JOptionPane.showMessageDialog(null,"Archivo del juego generado correctamente en Torres


de Hanoi.txt" );

Desktop d = Desktop.getDesktop();

try {
d.open(f);

} catch (Exception e) {}

public static void main(String[] args) {

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;

/**

* @author Luis Carlos Prieto Juarez

*/

public class tablero extends JPanel implements Runnable{

private int torreInicio;//Indica donde deven empesar los discos

private int torreFin; //Indica donde deven terminar los discos

private int torreAyuda; //Indica cual sera el poste de ayuda


private int velocidad; //indica a que velocidad se desarrollara el juego

private int numeroDiscos;//Indic el numero de discos que tendra el juego

private Torre[] torres;

private JButton botonStart;

//Campos con el contador de movimientos

private JTextField campoTorreA;

private JTextField campoTorreB;

private JTextField campoTorreC;

private JTable tabla;

private int contadorMovimientos;

/**

* Constructor que inicializa todos los paramentros

* @param torreInicio Es donde empesaran los discos

* @param torreFin Es donde deven de terminar los discos

* @param torreAyuda Este es el poste que se usara como ayuda para pasar los discos

* @param velocidad Es la velocidad con la que se desarrollara el juego

*/

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;

//Iniciliso las 3 torres


this.torres = new Torre[3];

torres[0] = new Torre();

torres[1] = new Torre();

torres[2] = new Torre();

//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

public void paint(Graphics g) {

Image i = createImage(this.getSize().width,this.getSize().height);

Graphics gra = i.getGraphics();

//Obtenemos las nuevas dimenciones de la pantalla para calcular el la nuevas dimenciones de


las

//Torres ya que las torren creson con respecto a la pantalla

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);

//Se dibujan en el panel las 3 torres

gra.setColor(Color.red);

gra.fill3DRect(torres[0].getPosicionX(), torres[0].getPosicionY(), torres[0].getPosicionXFinal(),


torres[0].getPosicionYFinal(), true);

gra.fill3DRect(torres[1].getPosicionX(), torres[1].getPosicionY(), torres[1].getPosicionXFinal(),


torres[1].getPosicionYFinal(), true);

gra.fill3DRect(torres[2].getPosicionX(), torres[2].getPosicionY(), torres[2].getPosicionXFinal(),


torres[2].getPosicionYFinal(), true);

//Una ves impresos las torres devemos imprimir los discos

for (int c = 0; c < torres.length; c++) {

//Obtenemos las torres del vector de las torres

Torre torre = torres[c];

//Obtenemos la pila con los discos que contiene la torre

Stack<Torre.Disco> pila = torre.clonarPilaDiscos();

//Recuperamos el numeros que tiene actualmente la torre

int totalDiscos = pila.size();

//Imprimimos los discos

for (; !pila.isEmpty() ;) {

Torre.Disco disco = pila.pop();

int posicionX = (torre.getPosicionX()+3)-(disco.getSize()/2);//posicion en x inicial del disco

int posicionY = (this.getSize().height-10)-(10*totalDiscos);//posicion en y inicial del disco


int posicionXFinal = disco.getSize(); //posicion en x final del disco

int posicionYFinal = 10; //posicion en y final del disco

gra.setColor(Color.cyan);

gra.fill3DRect(posicionX, posicionY, posicionXFinal, posicionYFinal, true);

totalDiscos--;

g.drawImage(i, 0, 0, this);

this.validate();

public void run() {

inizializarTablero();

try {

Thread.sleep(velocidad);

} catch (Exception e) {

JOptionPane.showMessageDialog(this, e);

return;

pasar(torreInicio, torreFin, torreAyuda, numeroDiscos);

generarFichero generarF = new generarFichero();

generarF.generarFichero(tabla,Integer.parseInt(campoTorreA.getText()),Integer.parseInt(campoTo
rreB.getText()),Integer.parseInt(campoTorreC.getText()));

botonStart.setEnabled(true);

/**

* Metodo encargado de pasar los discos de un palo a otro

* @param inicio

* @param fin

* @param ayuda
* @param numeroDiscos

*/

public void pasar(int inicio, int fin, int ayuda, int numeroDiscos) {

//Se llevan n-1 discos de la torre origen a la auxiliar.

//Se lleva un solo disco (el que queda) de la Torre origen a la destino

//Se traen los n-1 discos de la varilla auxiliar a la destino.

if (numeroDiscos == 1) {

pasar(inicio, fin);

return;

} else {

pasar(inicio, ayuda, fin, numeroDiscos - 1);

pasar(inicio, fin);

pasar(ayuda, fin, inicio, numeroDiscos - 1);

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

*/

public void pasar(int inicio, int fin) {

//Incrementamos el numero de movimientos

contadorMovimientos++;

//Retiramos el disco del inicio

Torre.Disco disco = torres[inicio].getDisco();


//Introducimos el disco al destino

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)+"" );

DefaultTableModel modelo = (DefaultTableModel) tabla.getModel();

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 );

public void inizializarTablero() {

for (int c = this.numeroDiscos; c > 0; c--) {

//Se crean los discos y se les asigna su numero de disco

torres[torreInicio].push(c);
}

this.repaint();

Diagrama de Clases

You might also like