/////////////////////////////////////////////////////////// // // Linguangem de Programcao V - Java Prof: Ismael // // Programa Ratinho - 2o Trabalho para TV1 // // Solução do Professor - 15/10/1998 // //////////////////////////////////////////////////////////// // import DialogClasses.*; import java.awt.*; import java.applet.*; import java.util.*; class Constantes { static final int NX = 8; static final int NY = 8; static final Posicao POS_FINAL = new Posicao(NX, NY); } class Posicao { /////////////// // Variables // /////////////// private int x; private int y; ////////////////////// // Public Methods // ////////////////////// public Posicao (Posicao p) { x = p.x; y = p.y; } public Posicao (int i, int j) { x = i; y = j; } public void setX (int i) { x = i; } public int getX () { return this.x; } public int getY () { return this.y; } public void setY (int j) { y = j; } public String toString() { return "( " + x + " , " + y + " )"; } public boolean equals( Posicao p ) { return (x==p.getX() && y==p.getY())?true:false; } public void copia (Posicao p) { x = p.x; y = p.y; } } public class RatazanaGab extends Applet { /////////////// // Variables // /////////////// Interface interf; Jogo jogo; ////////////////////// // Public Methods // ////////////////////// public void init() { // Cria Elementos da Interface interf = new Interface(); // Cria Classe responsavel pelos Algoritmos jogo = new Jogo(); // Torna as Classes Interface e Jogo visiveis entre si jogo.SetInterface(this, interf); // interf.SetJogo(jogo); // Monta Layout da Applet com GridBagLayout Panel fundo = new Panel(); GridBagLayout gbl = new GridBagLayout(); fundo.setLayout(gbl); Constrain(fundo, interf.labirinto, 0, 1, Constantes.NX+2, Constantes.NY+2, GridBagConstraints.NONE, GridBagConstraints.NORTH, 1.0, 1.0, 0, 0, 0, 0); Constrain(fundo, new Label(" Labirinto"), Constantes.NX, 0, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0.0, 0.0, 0, 0, 0, 0); Constrain(fundo, new Label("Algoritmo"), Constantes.NX+2+2, 0, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0.0, 0.0, 0, 0, 0, 0); Constrain(fundo, interf.checkBoxes[0], Constantes.NX+2+2, 1, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0.0, 0.0, 0, 0, 0, 0); Constrain(fundo, interf.checkBoxes[1], Constantes.NX+2+2, 2, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0.0, 0.0, 0, 0, 0, 0); Constrain(fundo, interf.lstPassos, Constantes.NX+2+2, 3, 3, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST, 0.0, 0.0, 1, 1, 1, 1); Constrain(fundo, interf.btInicio, Constantes.NX+2+2, 9, 3, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0.0, 0.0, 0, 0, 0, 0); Constrain(fundo, interf.btNovo, Constantes.NX+2+2, 10, 3, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0.0, 0.0, 0, 0, 0, 0); // Monta Layout da Applet com GridBagLayout setLayout(new BorderLayout()); add("Center", fundo); add("North", new Panel()); add("South", new Panel()); add("East", new Panel()); add("West", new Panel()); } public void Constrain(Container container, Component c, int x, int y, int w, int h, int fill, int anchor, double wx, double wy, int top, int left, int bottom, int right) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; gbc.fill = fill; gbc.anchor = anchor; gbc.weightx = wx; gbc.weighty = wy; if( top+left+bottom+right > 0 ) gbc.insets = new Insets(top, left, bottom, right); ((GridBagLayout)container.getLayout()).setConstraints(c, gbc); container.add(c); } public boolean action (Event evt, Object arg) { if( evt.target instanceof Button ) { String temp = (String)arg; if( temp.equals("Novo") ) // Reinicializa Jogo { jogo.NewGame(); } else if( jogo.Iniciou() ) // Eventos ignorados após início do Jogo return true; if( temp.equals("Inicia") ) // Jogo é iniciado { jogo.Inicia (); } else // Repassa eventos para interface { interf.action(evt, arg); } return true; } else return super.action(evt, arg); } } class Interface extends Panel { /////////////// // Variables // /////////////// public Panel labirinto; public Button btInicio; public Button btNovo; public List lstPassos; public Checkbox[] checkBoxes; public Button[][] botoes; private CheckboxGroup checkBoxGroup; ////////////////////// // Public Methods // ////////////////////// public Interface() { // Monta a interface do Jogo // 1 - Labirinto com painel de Botoes labirinto = new Panel(); labirinto.setLayout(new GridLayout(Constantes.NX+2, Constantes.NY+2)); botoes = new Button[Constantes.NX+2][Constantes.NY+2]; // Encapamento do Labirinto para efeito visual !!! for( int j=0; j < Constantes.NY+2; j++ ) { botoes[0][j] = new Button(" "); botoes[0][j].setBackground(Color.yellow); labirinto.add(botoes[0][j]); } for( int i=1; i < Constantes.NX+1; i++ ) { botoes[i][0] = new Button(" "); botoes[i][0].setBackground(Color.yellow); labirinto.add(botoes[i][0]); for( int j = 1; j < Constantes.NY+1; j++ ) { botoes[i][j] = new Button("0"); botoes[i][j].setBackground(Color.lightGray); botoes[i][j].setForeground(Color.white); labirinto.add(botoes[i][j]); } botoes[i][Constantes.NY+1] = new Button(" "); botoes[i][Constantes.NY+1].setBackground(Color.yellow); labirinto.add(botoes[i][Constantes.NY+1] ); } // Encapamento do Labirinto para efeito visual !!! for( int j=0; j < Constantes.NY+2; j++ ) { botoes[Constantes.NX+1][j] = new Button(" "); botoes[Constantes.NX+1][j].setBackground(Color.yellow); labirinto.add( botoes[Constantes.NX+1][j] ); } // 2 - Controles do Jogo btNovo = new Button("Novo"); btInicio = new Button("Inicia"); lstPassos= new List(5, false); checkBoxGroup = new CheckboxGroup(); checkBoxes = new Checkbox[2]; checkBoxes[0] = new Checkbox("Nao-Recursivo", checkBoxGroup, true); checkBoxes[1] = new Checkbox("Recursivo", checkBoxGroup, false); // 3 - Zera listaPassos e coloca o Ratinho e a Saida no labirinto InicializaLabirinto(); } public String getAlgoritmo() { if( checkBoxes[0].getState() ) return checkBoxes[0].getLabel(); else return checkBoxes[1].getLabel(); } public void Move(Posicao oldPosRat, Posicao posRat) { lstPassos.addItem( oldPosRat.toString(), 0 ); marcaPosLivre(oldPosRat); MarcaPosRat(posRat); } public void Back(Posicao oldPosRat, Posicao posRat) { lstPassos.delItem( 0 ); marcaPosLivre(posRat); MarcaPosRat(oldPosRat); } public void MarcaPosRat(Posicao pos) { botoes[pos.getX()][pos.getY()].setLabel("R"); } public boolean action(Event evt, Object arg) { if ( evt.target instanceof Button ) { // Altera labels do Interface for (int i = 1; i < Constantes.NX + 1; i++) for (int j = 1; j < Constantes.NY + 1; j++) if( evt.target == botoes[i][j] ) { Button b = botoes[i][j]; String temp = b.getLabel(); if ( temp.equals("0") ) { b.setLabel("1"); } else if ( temp.equals("1") ) { b.setLabel("0"); } return true; } } return true; } public void InicializaLabirinto() { lstPassos.clear(); for( int i=1; i < Constantes.NX+1; i++ ) { for( int j=1; j < Constantes.NY+1; j++ ) { botoes[i][j].setLabel("0"); } } botoes[1][1].setLabel("R"); botoes[1][1].setForeground(Color.red); botoes[Constantes.NX][Constantes.NY].setLabel("S"); botoes[Constantes.NX][Constantes.NY].setForeground(Color.yellow); } ////////////////////// // Private Methods // ////////////////////// private void marcaPosLivre(Posicao pos) { botoes[pos.getX()][pos.getY()].setLabel("0"); } private void marcaPosProib(Posicao pos) { botoes[pos.getX()][pos.getY()].setLabel("0"); } } class Jogo { private Applet pApplet; private Interface pInterf; // Referencia para Interface private boolean inicio; // indicador do inicio de jogo private Posicao posRat; // posicao corrente do Ratinho private Stack pilha; // Caminho realizado pelo Ratinho private int [][] labirinto; ////////////////////// // Public Methods // ////////////////////// public Jogo () { // Constroi estruturas de dados para o Jogo inicio = false; // 1 - Cria pilha para guardar o caminho do ratinho pilha = new Stack (); // 2 - Cria labirinto encapando a borda para evitar saida labirinto = new int [Constantes.NX + 2] [Constantes.NY + 2]; for( int j=0; j < Constantes.NY+2; j++ ) { labirinto[0][j] = 1; } for( int i=1; i < Constantes.NX+1; i++ ) { labirinto[i][0] = 1; for( int j=1; j < Constantes.NY+1; j++ ) { labirinto[i][j] = 0; } labirinto[i][Constantes.NY+1] = 1; } for( int j=0; j < Constantes.NY+2; j++ ) { labirinto[Constantes.NX+1][j] = 1; } } public boolean Iniciou() { return inicio; } public void SetInterface(Applet applet, Interface interf) { pInterf = interf; pApplet = applet; } public void Inicia() { // Limpa elementos de controle do Jogo inicio = true; while ( !pilha.empty() ) pilha.pop(); posRat = new Posicao(1, 1); // Obtem matriz do labirinto getLabirinto(); // Executa o algoritmo selecionado if ( (pInterf.getAlgoritmo()).equals("Recursivo") ) playR(); else play(); if ( ! pilha.empty () ) { pInterf.lstPassos.addItem( posRat.toString(), 0 ); pInterf.lstPassos.addItem ("--- ACHOU ---", 0); // Marca caminho na interface while ( !pilha.empty() ) { Posicao posRat = (Posicao)pilha.pop(); pInterf.MarcaPosRat(posRat); } InfoDialog dialogo = new InfoDialog(pApplet, "Ratinho", "Encontrou caminho !!!"); dialogo.show (); } else { pInterf.lstPassos.addItem ("--- FALHOU ---", 0); ErrorDialog dialogo = new ErrorDialog(pApplet, "Ratinho", "Nao existe caminho !!!"); dialogo.show (); } } public void NewGame() { inicio = false; inicializaLabirinto (); pInterf.InicializaLabirinto(); } ////////////////////// // Private Methods // ////////////////////// private void inicializaLabirinto() { for( int i=1; i < Constantes.NX+1; i++ ) { for( int j=1; j < Constantes.NY+1; j++ ) { labirinto[i][j] = 0; } } } private void getLabirinto() { for( int i=1; i < Constantes.NX+1; i++ ) { for( int j=1; j < Constantes.NY+1; j++ ) { Button b = pInterf.botoes[i][j]; String temp = b.getLabel(); if ( temp.equals("0") ) { labirinto[i][j] = 0; } else if ( temp.equals("1") ) { labirinto[i][j] = 1; } } } } private boolean podeMover() { if ( labirinto[posRat.getX()+1][posRat.getY()] == 0 ) return true; else if ( labirinto[posRat.getX()][posRat.getY() + 1] == 0 ) return true; else if ( labirinto[posRat.getX()-1][posRat.getY()] == 0 ) return true; else if ( labirinto[posRat.getX()][posRat.getY()-1] == 0 ) return true; else return false; } private void move() { Posicao oldPosRat = new Posicao(posRat); pilha.push(new Posicao(posRat)); if ( labirinto[posRat.getX()+1][posRat.getY()] == 0 ) { posRat.setX(posRat.getX()+1); } else if ( labirinto[posRat.getX()][posRat.getY()+1] == 0 ) { posRat.setY(posRat.getY()+1); } else if ( labirinto[posRat.getX()-1][posRat.getY()] == 0 ) { // Marca posicao corrente como proibida para evitar voltar !!! labirinto[posRat.getX()][posRat.getY()] = 1; posRat.setX(posRat.getX() - 1); } else if ( labirinto[posRat.getX()][posRat.getY()-1] == 0 ) { // Marca posicao corrente como proibida para evitar voltar !!! labirinto[posRat.getX()][posRat.getY()] = 1; posRat.setY(posRat.getY() - 1); } pInterf.Move(oldPosRat, posRat); } private void back() { Posicao oldPosRat = (Posicao)pilha.pop(); labirinto[posRat.getX()][posRat.getY()] = 1; pInterf.Back(oldPosRat, posRat); posRat.copia(oldPosRat); } // // Algoritmo nao recursivo // private void play () { do { for (int t = 0; t < 1000000; t++) ; if ( podeMover() ) { move(); } else { if( !pilha.empty() ) { back(); } else break; } } while ( !posRat.equals(Constantes.POS_FINAL) ); } // // Algoritmo recursivo // private void playR() { for (int t = 0; t < 1000000; t++) ; if ( posRat.equals(Constantes.POS_FINAL) ) { return; } else { if ( podeMover() ) { move(); playR(); } else { if( !pilha.empty() ) { back(); playR(); } else return; } } } } /////////////////////////////////////////////////////////// // // Linguangem de Programcao V - Java Prof: Ismael // // Classes derivadas de Dialog para Exibicao de Mensagens // // Classes Publicas: InfoDialog // ErrorDialog // QuestionDialog // QuitDialog //////////////////////////////////////////////////////////// class InfoDialog extends Frame { protected Button _bt; protected Label _lb; public InfoDialog(Container parent, String title, String msg ) { // Cria a dialog com o titulo janela nao-modal super(title); setBackground(Color.white); setForeground(Color.blue); setLayout(new BorderLayout(15,15)); // Coloca label no centro da window Panel p1 = new Panel(); _lb = new Label(msg); p1.setLayout(new FlowLayout(FlowLayout.CENTER)); p1.setForeground(Color.blue); p1.add(_lb); add("Center", p1); // Coloca botoa centralizado Panel p2 = new Panel(); _bt = new Button("Ok"); p2.setLayout(new FlowLayout(FlowLayout.CENTER,15,15)); p2.add(_bt); add("South", p2); // Resize na window de acordo com os componentes pack(); show(); } public boolean action(Event e, Object o) { if( o.equals("Ok") ) { hide(); dispose(); return true; } else return false; } public boolean handleEvent(Event e) { if( e.target == this && e.id == Event.WINDOW_DESTROY ) dispose(); return super.handleEvent(e); } // Quando a window pegar o foco do keyboard, repassa o foco // para o botao public boolean gotFocus(Event e, Object o) { _bt.requestFocus(); return true; } } class ErrorDialog extends Frame { protected Button _bt; protected Label _lb; public ErrorDialog(Container parent, String title, String msg ) { // Cria a dialog com o titulo janela nao-modal super(title); setBackground(Color.white); setForeground(Color.red); setLayout(new BorderLayout(15,15)); // Coloca label no centro da window Panel p1 = new Panel(); _lb = new Label(msg); p1.setLayout(new FlowLayout(FlowLayout.CENTER)); p1.setForeground(Color.red); p1.add(_lb); add("Center", p1); // Coloca botoa centralizado Panel p2 = new Panel(); _bt = new Button("Ok"); p2.setLayout(new FlowLayout(FlowLayout.CENTER,15,15)); p2.add(_bt); add("South", p2); // Resize na window de acordo com os componentes pack(); show(); } public boolean action(Event e, Object o) { if( o.equals("Ok") ) { hide(); dispose(); return true; } else return false; } public boolean handleEvent(Event e) { if( e.target == this && e.id == Event.WINDOW_DESTROY ) dispose(); return super.handleEvent(e); } // Quando a window pegar o foco do keyboard, repassa o foco // para o botao public boolean gotFocus(Event e, Object o) { _bt.requestFocus(); return true; } }