Ir ao conteúdo
  • Cadastre-se

Java Como implementar jogada da maquina ?


Posts recomendados

Eu fiz um jogo da velha mas eu preciso dar a opção de jogar sozinho contra a maquina e a maquina fazer as próprias jogadas, mas não sei como implementar isso no meu código, e eu tive que deixar como comentada a função sair, do botão sair, pois quando aciono o botão opções o jogo fecha sozinho.


import javax.swing.JButton;
import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author igorhugentobler
 */
public class Principal extends javax.swing.JFrame {

    int quantidade;// verifica quantidade de jogadas
    int player;//Esse atributo vai verificar quem é o jogador que está jogando no momento, sabendo que o Jogador X é 1 e o Jogador 0 é 2.
    int matriz[][] = new int[3][3];//Esse atributo vai marcando a posição que cada jogador jogou, e assim, verifica se algum jogador conseguiu fazer o jogo.
    JButton b[] = new JButton[9];// Esse atributo mapeia os botões do jogo
    String ganhador;// Esse atributo armazena o nome do ganhador
    String jogador1; //Esse atributo armazena o nome do jogador 1
    String jogador2;// Esse atributo armazena o nome do jogador2

    /**
     * Creates new form Principal
     */
    public Principal() {//comandos para a inicialização dos atributos
        initComponents();
        quantidade = 1;
        player = 1;
        b[0] = bt1;
        b[1] = bt2;
        b[2] = bt3;
        b[3] = bt4;
        b[4] = bt5;
        b[5] = bt6;
        b[6] = bt7;
        b[7] = bt8;
        b[8] = bt9;

    }

    public void jogada(JButton b, int x, int y) {//Esse procedimento verificará qual foi a jogada de qual jogador, e automaticamente ele verificará se houve algum ganhador através do procedimento checarjogada.
        b.setEnabled(false);
        if (player == 1) {
            matriz[x][y] = 1;
            b.setText("X");
            player = 2;
            ganhador = jogador1;
            checarjogada(1);
        } else {
            matriz[x][y] = 2;
            b.setText("0");
            player = 2;
            ganhador = jogador2;
            checarjogada(2);
        }
        quantidade++;
    }

    public void checarjogada(int x) {
        if (vitoria(x) == true)//Esse procedimento verifica se houve algum ganhador através da função vitoria, se houve ele exibirá o nome do vencedor.
        {
            JOptionPane.showMessageDialog(null, "Jogador: " + ganhador + " " + "Venceu!", "Vitória", JOptionPane.INFORMATION_MESSAGE);
            fimjogo();
        }
    }

    public boolean vitoria(int x)//Essa função verifica se houve algum vencedor.
    {
        for (int i = 0; i < matriz.length; i++) {
            if (matriz[i][0] == x && matriz[i][1] == x && matriz[i][2] == x) {
                return true;
            }
            if (matriz[0][i] == x && matriz[1][i] == x && matriz[2][i] == x) {
                return true;
            }
        }
        if (matriz[0][0] == x && matriz[1][1] == x && matriz[2][2] == x) {
            return true;
        }
        if (matriz[0][2] == x && matriz[1][1] == x && matriz[2][0] == x) {
            return true;
        }
        return false;
    }

    public void fimjogo()//Esse procedimento finaliza o jogo no exato momento que houver um vencedor ou empate
    {
        for (int i = 0; i < 9; i++) {
            b[i].setEnabled(false);
        }
    }

    public void limpar()//Esse procedimento inicializa o jogo.
    {
        for (int i = 0; i < 9; i++) {
            b[i].setEnabled(true);
            b[i].setText("");
        }
        for (int x = 0; x < 3; x++) {
            for (int y = 0; y < 3; y++) {
                matriz[x][y] = 0;
            }
        }
        player = 1;
        jogador1 = "";
        jogador2 = "";
        ganhador = "";
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        bt1 = new javax.swing.JButton();
        bt2 = new javax.swing.JButton();
        bt3 = new javax.swing.JButton();
        bt4 = new javax.swing.JButton();
        bt5 = new javax.swing.JButton();
        bt6 = new javax.swing.JButton();
        bt7 = new javax.swing.JButton();
        bt8 = new javax.swing.JButton();
        bt9 = new javax.swing.JButton();
        jMenuBar3 = new javax.swing.JMenuBar();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu6 = new javax.swing.JMenu();

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        bt1.setEnabled(false);
        bt1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt1ActionPerformed(evt);
            }
        });

        bt2.setEnabled(false);
        bt2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt2ActionPerformed(evt);
            }
        });

        bt3.setEnabled(false);
        bt3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt3ActionPerformed(evt);
            }
        });

        bt4.setEnabled(false);
        bt4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt4ActionPerformed(evt);
            }
        });

        bt5.setEnabled(false);
        bt5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt5ActionPerformed(evt);
            }
        });

        bt6.setEnabled(false);
        bt6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt6ActionPerformed(evt);
            }
        });

        bt7.setEnabled(false);
        bt7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt7ActionPerformed(evt);
            }
        });

        bt8.setEnabled(false);
        bt8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt8ActionPerformed(evt);
            }
        });

        bt9.setEnabled(false);
        bt9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt9ActionPerformed(evt);
            }
        });

        jMenu3.setText("Opção");
        jMenu3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu3ActionPerformed(evt);
            }
        });

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F8, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setMnemonic('N');
        jMenuItem1.setText("Novo Jogo");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem1);

        jMenuBar3.add(jMenu3);

        jMenu6.setText("Sair");
        jMenu6.addMenuListener(new javax.swing.event.MenuListener() {
            public void menuCanceled(javax.swing.event.MenuEvent evt) {
            }
            public void menuDeselected(javax.swing.event.MenuEvent evt) {
            }
            public void menuSelected(javax.swing.event.MenuEvent evt) {
                jMenu6MenuSelected(evt);
            }
        });
        jMenuBar3.add(jMenu6);

        setJMenuBar(jMenuBar3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(bt7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
                    .addComponent(bt4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bt2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt8, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bt3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt9, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bt2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bt3, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bt4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt6, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bt7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt9, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>                        

    private void bt2ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt2, 0, 1);
    }                                   

    private void bt1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt1, 0, 0);
    }                                   

    private void bt3ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt3, 0, 2);
    }                                   

    private void bt4ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt4, 1, 0);
    }                                   

    private void bt5ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt5, 1, 1);
    }                                   

    private void bt6ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt6, 1, 2);
    }                                   

    private void bt7ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt7, 2, 0);
    }                                   

    private void bt8ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt8, 2, 1);
    }                                   

    private void bt9ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        jogada(bt9, 2, 2);
    }                                   

    private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        //limpar();
        //jogador1 = JOptionPane.showInputDialog("Dgite o Nome do primeiro Jogador: ");
        //jogador2 = JOptionPane.showInputDialog("Digite o Nome do Segundo Jogador:");
    }                                      

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        limpar();
        jogador1= JOptionPane.showInputDialog("Digite o nome do primero Jogador:");
        jogador2= JOptionPane.showInputDialog("Digite o nome do segundo Jogador");
    }                                          
/*
    private void jMenu6MenuSelected(javax.swing.event.MenuEvent evt) {                                    
        // TODO add your handling code here:
        //System.exit(0);
    }                                   

    /**
     * @param args the command line arguments
     */
     
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton bt1;
    private javax.swing.JButton bt2;
    private javax.swing.JButton bt3;
    private javax.swing.JButton bt4;
    private javax.swing.JButton bt5;
    private javax.swing.JButton bt6;
    private javax.swing.JButton bt7;
    private javax.swing.JButton bt8;
    private javax.swing.JButton bt9;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuBar jMenuBar3;
    private javax.swing.JMenuItem jMenuItem1;
    // End of variables declaration                   
}

 

  • Amei 1
Link para o comentário
Compartilhar em outros sites

@Igor Hugentobler     para o pc fazer a jogada precisa de uma IA , e tem de vários tipos , uma bem conhecida é a mini max ,  e baseada nessa fiz uma para o joga da velha na linguagem c ,  dê uma olhada e faça adaptações para o java ,

int raciocinio_do_pc(int p){  /*nivel muito fácil*/
    if(vl_nivel > 0){    /*  nivel fácil*/
        if(vet[2][2]==0){
            vet[2][2]=1;
            return 1;
        }
        if(vet[1][1]==p&&vet[2][1]==p&&vet[3][1]==0){
            vet[3][1]=1;
            return 1;
        }
        if(vet[1][1]==p&&vet[3][1]==p&&vet[2][1]==0){
            vet[2][1]=1;
            return 1;
        }
        if(vet[2][1]==p&&vet[3][1]==p&&vet[1][1]==0){
            vet[1][1]=1;
            return 1;
        }
        if(vet[1][2]==p&&vet[2][2]==p&&vet[3][2]==0){
            vet[3][2]=1;
            return 1;
        }
        if(vet[1][2]==p&&vet[3][2]==p&&vet[2][2]==0){
            vet[2][2]=1;
            return 1;
        }
        if(vet[2][2]==p&&vet[3][2]==p&&vet[1][2]==0){
            vet[1][2]=1;
            return 1;
        }
        if(vet[1][3]==p&&vet[2][3]==p&&vet[3][3]==0){
            vet[3][3]=1;
            return 1;
        }
        if(vl_nivel > 1){     /*nivel medio*/
            if(vet[1][3]==p&&vet[3][3]==p&&vet[2][3]==0){
                vet[2][3]=1;
                return 1;
            }
            if(vet[2][3]==p&&vet[3][3]==p&&vet[1][3]==0){
                vet[1][3]=1;
                return 1;
            }
            if(vet[1][1]==p&&vet[3][1]==p&&vet[2][1]==0){
                vet[2][1]=1;
                return 1;
            }
            if(vet[2][1]==p&&vet[2][2]==p&&vet[2][3]==0){
                vet[2][3]=1;
                return 1;
            }
            if(vet[2][1]==p&&vet[2][3]==p&&vet[2][2]==0){
                vet[2][2]=1;
                return 1;
            }
            if(vet[2][2]==p&&vet[2][3]==p&&vet[2][1]==0){
                vet[2][1]=1;
                return 1;
            }
            if(vet[3][1]==p&&vet[3][2]==p&&vet[3][3]==0){
                vet[3][3]=1;
                return 1;
            }
            if(vl_nivel > 2){     /*nivel difícil*/
                srand(time(NULL));
                if(rand()%100 > 20){
                    if(vet[3][1]==p&&vet[3][3]==p&&vet[3][2]==0){
                        vet[3][2]=1;
                        return 1;
                    }
                    if(vet[3][2]==p&&vet[3][3]==p&&vet[3][1]==0){
                        vet[3][1]=1;
                        return 1;
                    }
                    if(vet[1][1]==p&&vet[2][2]==p&&vet[3][3]==0){
                        vet[3][3]=1;
                        return 1;
                    }
                    if(vet[1][1]==p&&vet[3][3]==p&&vet[2][2]==0){
                        vet[2][2]=1;
                        return 1;
                    }
                    if(vet[2][2]==p&&vet[3][3]==p&&vet[1][1]==0){
                        vet[1][1]=1;
                        return 1;
                    }
                    if(vet[1][3]==p&&vet[2][2]==p&&vet[3][1]==0){
                        vet[3][1]=1;
                        return 1;
                    }
                    if(vet[1][3]==p&&vet[3][1]==p&&vet[2][2]==0){
                        vet[2][2]=1;
                        return 1;
                    }
                    if(vet[2][2]==p&&vet[3][1]==p&&vet[1][3]==0){/* posição na matriz de 3 x 3 */
                        vet[1][3]=1;
                        return 1;
                    }
                }
            }
        }
    }
    return 0;
}

 

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...