Prosta gra w Javie

0

Witam,

Muszę napisać prostą grę w Javie, kółko i krzyżyk. Postanowiłem żeby zrobić to na mapach. na razie gra działa na zasadzie gra dla dwóch graczy, a musze zrobic aby grało się z komputerem, komputer musi zawsze wygrać. Proszę o pomoc, jakieś wskazówki co musze dalej zrobić albo co mozna dodać do kodu lub jeszcze inne uwagi. Zaczynam nauke javy

package tictactoe;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 *
 * @author Bartosz
 */
public class NewJFrame extends javax.swing.JFrame {

    private static final int SIZE = 20;
    private Map<String, JButton> map = new HashMap<>();     //Mapa przyjmująca 2 typy generyczne. String określa typ klucza,
    private Map<Boolean, Player> player = new HashMap<>();  //natomiast Jbutton określa typ wartości przyjmowanej.
    private Boolean currentPlayer = false;
    private Boolean gameStatus = true;

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
        player.put(true, new Player("Player1", "X"));
        player.put(false, new Player("Player2", "O"));
        changePlayer();
        gamePanel.setLayout(new GridLayout(SIZE, SIZE));
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                JButton button = new JButton(" ");
                map.put("" + i + "X" + j, button);
                gamePanel.add(button);
                final int x = i;
                final int y = j;
                button.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        
                        if (gameStatus) click(x, y);
                    }
                });
            }
        }
    }

    private void click(int x, int y) {
        String key = "" + x + "X" + y;
        System.out.println(key);
        System.out.println(player.get(currentPlayer).toString());

        if (currentPlayer) {
            map.get(key).setText("X");
        } else {
            map.get(key).setText("O");
        }

        map.get(key).setEnabled(false);
        if (checkWin(player.get(currentPlayer))) {
            System.out.println("Wygrał: " + player.get(currentPlayer).toString());
        }

        changePlayer();

    }

    private int check(int i, int j, int counter, Player player, String direction) {
        if (map.get("" + i + "X" + j).getText().equals(player.getSign())) {
            counter++;
            if (counter == 5) {
                System.out.println("WIN!!!!!!!!!!!!!!!! " + player.getName());
                gameStatus = false;
//                map.get("" + i + "X" + j).setBackground(Color.red);
                JOptionPane.showMessageDialog(this, "Wygrał gracz: " + player.toString() + direction);
            }
        } else {
            counter = 0;
        }

        return counter;
    }

    private Boolean checkWin(Player player) {

        System.out.println("sprawdzanie dla gracza: " + player.toString());

        //sprawdzenie w poziomie
        int counter = 0;
        int counter2 = 0;
        for (int i = 0; i < SIZE; i++) {
            counter = 0;
            for (int j = 0; j < SIZE; j++) {
                counter = check(i, j, counter, player, "poziom");
            }
        }

        //sprawdzenie w pionie
        counter = 0;
        for (int j = 0; j < SIZE; j++) {
            counter = 0;
            for (int i = 0; i < SIZE; i++) {
                counter = check(i, j, counter, player, "pion");
            }
        }

        //sprawdzenie skos
        counter = 0;
        for (int x = 0; x < SIZE; x++) {
            //skos 1
            counter = 0;
            for (int i = x, j = 0; i < SIZE && j < SIZE; i++, j++) {
                counter = check(i, j, counter, player, "skos11");
            }

            //skos2
            counter2 = 0;
            for (int i = 0, j = x + 1; i < SIZE && j < SIZE; i++, j++) {
                counter2 = check(i, j, counter2, player, "skos12");
            }

        }

        //sprawdzenie skos 2
        counter = 0;
        for (int x = 0; x < SIZE; x++) {
            //skos 1
            counter = 0;
            for (int i = x, j = 0; i >= 0 && j < SIZE; i--, j++) {
                counter = check(i, j, counter, player, "skos21");
            }

            //skos2
            counter2 = 0;
            for (int i = SIZE - 1, j = x + 1; i >= 0 && j < SIZE; i--, j++) {
                counter2 = check(i, j, counter2, player, "skos22");
            }

        }

        return false;
    }
    
  
            

    private void changePlayer() {
        currentPlayer = !currentPlayer;
        setTitle("Ruch gracza: " + player.get(currentPlayer).toString());
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        gamePanel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        gamePanel.setLayout(new java.awt.GridLayout(1, 0));
        jScrollPane1.setViewportView(gamePanel);

        jButton1.setText("New Game");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 855, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(31, 31, 31))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 589, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
               map.get("" + i + "X" + j).setText(" ");
               map.get("" + i + "X" + j).setEnabled(true);
//               map.get("" + i + "X" + j).setBackground(Color.lightGray); //nie działa przy wyłączonym przycisku
               gameStatus = true; //zmiana statusu gry
               if (!currentPlayer) changePlayer();  //zawsze zaczyna krzyżyk
            }
 
                
            }
    }                                        

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel gamePanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                   
}
0

Proszę o pomoc w algorytmie

0

Jeśli chodzi Ci o algorytm, to umieściłeś post w złym dziale.

komputer musi zawsze wygrać

Skąd wiesz, że taki algorytm istnieje dla "grającego białymi" lub dla "grającego czarnymi"? A jeśli istnieje, to użytkownik programu może się nie zgodzić by grać zawsze jednym kolorem.

1 użytkowników online, w tym zalogowanych: 0, gości: 1