Java - random number buttons

0

I have a new question (which is a continuation of my previous question ). I have a button ( JButton ) with the name "shuffle" that is already implemented. I wanted to do the following: when this button is pressed, it shuffles the numbers as described above. There is no need to restart the application.

public void actionPerformed(ActionEvent e)
{

        if (baralharBtn == e.getSource())
        {
            //setArrayListText();
            List<Integer> lista = Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1);
            Collections.shuffle(lista);
            gameList.addAll(lista);
        }
}

The problem is: When I click the Shuffle button, the numbers hold the same positions as when I started the application, but I wanted it to shuffle again and as described in the previous random number question . I wanted to keep the 4x4 grid that contains the 16% with equal% s. The only difference is that in the Shuffle button, when triggered, it generates new random numbers. (and deletes or overrides numbers that were previously).

Sorry, you're right, I did not post the whole code because I thought it would make it difficult. That ceiling is making mistakes. That's why I've posted the complete code to make it easier.

I'm using notepadd ++.

Complete code with imports:

    import java.awt.*;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.event.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.ButtonGroup;
    import javax.swing.JRadioButton;
    import javax.swing.event.ChangeListener;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Vector;
    import java.util.List;
    import java.applet.Applet;

    public class MemoryGame extends JFrame implements ActionListener

{

    private JCheckBox check1,check2,check3;
    Font f; 
    TextField msg1, msg2, password,t;
    CheckboxGroup cbg;
    Checkbox courier, timesRoman, helvetica;
    String s;
    Label mostra;           
    public int delay = 1000; //1000 milliseconds

    public void Contador()
    {
        ActionListener counter = new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                tempo++;
                TempoScore.setText("Tempo: " + tempo);
            }
        };
        new Timer(delay, counter).start();
    }

    public void updateHitMiss() 
    {
        HitScore.setText("Acertou: " + Hit);
        MissScore.setText("Falhou: " + Miss);
        PontosScore.setText("Pontos: " + Pontos);
    }

    private JFrame window = new JFrame("Jogo da Memoria");
    private static final int WINDOW_WIDTH = 500; // pixels
    private static final int WINDOW_HEIGHT = 500; // pixels
    private JButton exitBtn, baralharBtn, solveBtn, restartBtn, maximoBtn, definicoesBtn;
    ImageIcon ButtonIcon = createImageIcon("card1.png");
    private JButton[] gameBtn = new JButton[16];
    private ArrayList<Integer> gameList = new ArrayList<Integer>();
    //List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
    private int Hit, Miss, Pontos, Maximo;
    public int tempo = 0;   
    private int counter = 0;
    private int[] btnID = new int[2];
    private int[] btnValue = new int[2];
    private JLabel HitScore, MissScore, TempoScore, PontosScore, MaximoScore;
    private JPanel gamePnl = new JPanel();
    private JPanel buttonPnl = new JPanel();
    private JPanel scorePnl = new JPanel();

    protected static ImageIcon createImageIcon(String path) 
    {
        java.net.URL imgURL = MemoryGame.class.getResource(path);
        if (imgURL != null) 
        {
            return new ImageIcon(imgURL);
        } 
        else  return null;
    }

    public MemoryGame()
    {
        createGUI();
        createJPanels();
        setArrayListText();
        window.setTitle("Jogo da Memoria");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        window.setVisible(true);
        Contador();
    }

    public void createGUI()
    {
        for (int i = 0; i < gameBtn.length; i++)
        {
            gameBtn[i] = new JButton(ButtonIcon);
            gameBtn[i].addActionListener(this);
        }
        HitScore = new JLabel("Acertou: " + Hit);
        MissScore = new JLabel("Falhou: " + Miss);
        TempoScore = new JLabel("Tempo: " + tempo);
        PontosScore = new JLabel("Pontos: " + Pontos);  
        exitBtn = new JButton("Sair");
        exitBtn.addActionListener(this);
        baralharBtn = new JButton("Baralhar");
        baralharBtn.addActionListener(this);
        solveBtn = new JButton("Resolver");
        solveBtn.addActionListener(this);
        restartBtn = new JButton("Recomecar");
        restartBtn.addActionListener(this);
        maximoBtn = new JButton("Pontuacoes");
        maximoBtn.addActionListener(this);
        definicoesBtn = new JButton("Definicoes");
        definicoesBtn.addActionListener(this);
    }

    public void createJPanels()
    {
        gamePnl.setLayout(new GridLayout(4, 4));
        for (int i = 0; i < gameBtn.length; i++)
        {
            gamePnl.add(gameBtn[i]);
        }
        buttonPnl.add(baralharBtn);
        buttonPnl.add(exitBtn);
        buttonPnl.add(solveBtn);
        buttonPnl.add(restartBtn);
        buttonPnl.add(maximoBtn);
        buttonPnl.add(definicoesBtn);
        buttonPnl.setLayout(new GridLayout(2, 1));
        scorePnl.add(HitScore);
        scorePnl.add(MissScore);
        scorePnl.add(TempoScore);
        scorePnl.add(PontosScore);
        scorePnl.setLayout(new GridLayout(1, 0));
        window.add(scorePnl, BorderLayout.NORTH);
        window.add(gamePnl, BorderLayout.CENTER);
        window.add(buttonPnl, BorderLayout.SOUTH);
    }

    public void setArrayListText()
    { 
        List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
        Collections.shuffle(lista);
        gameList.addAll(lista);
    }

    public boolean sameValues()
    {
        if (btnValue[0] == btnValue[1])
        {
            return true;
        }
        return false;
    }

    public void pass() 
    {
        s = "123";
        msg1 = new TextField("Digite a password:"); msg1.setEditable(false);
        password = new TextField(12); password.setEchoCharacter('*');
        msg2 = new TextField(30); msg2.setEditable(false);
        add(msg1); add(password); add(msg2);
    }
    /*
    public boolean action(Event e, Object o) 
    {
        if (e.target instanceof TextField)
        if (e.target ==password)
        if (e.arg.equals(s)) msg2.setText("Acesso permitido");
        else msg2.setText("Password invalida.");
        return true;
    } */
    /*
    class EscutaJanela extends WindowAdapter
    {
        public void windowClosing(WindowEvent e) 
        setVisible(true);
        dispose();
    }
    */

    public void actionPerformed(ActionEvent e)
    {
            if (exitBtn == e.getSource())
            {
                System.exit(0);
            }

            if (baralharBtn == e.getSource())
            {
                //setArrayListText();

                List<Integer> lista = Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1);
                Collections.shuffle(lista);
                //gameList.addAll(lista);
                /*for (int i = 0; i < gameBtn.length; i++)
                {
                    gameBtn[i] = new JButton(ButtonIcon);
                    gameBtn[i].addActionListener(this);
                }*/
                for (int i = 0; i < gameBtn.length; i++)
                {
                    //gameBtn[i].setEnabled(false);                  
                    //gameBtn[i].setVisible(true);
                    gameBtn[i].setText("" + gameList.addAll(lista));
                }
            }

            if (solveBtn == e.getSource())
            {
                for (int i = 0; i < gameBtn.length; i++)
                {
                    gameBtn[i].setEnabled(false);                  
                    gameBtn[i].setVisible(true);
                    gameBtn[i].setText("" + gameList.get(i));       
                }
            }

            for (int i = 0; i < gameBtn.length; i++)
            {           
                if (gameBtn[i] == e.getSource())
                {
                    gameBtn[i].setText("" + gameList.get(i));
                    gameBtn[i].setEnabled(false);
                    counter++;

                    if(Hit==7)
                    {
                        if (counter == 2)
                        {
                            gameBtn[btnID[0]].setEnabled(false);
                            gameBtn[btnID[1]].setEnabled(false);
                            gameBtn[btnID[0]].setVisible(false);
                            gameBtn[btnID[1]].setVisible(false);
                            Hit = Hit +1;
                            Pontos = Pontos + 25;
                        }                   
                    }

                    if(Hit==8)
                    {  
                        int PontuacaoMax=0;
                        PontuacaoMax=Pontos;
                        window = new JFrame(" FIM DO JOGO ");           
                        JLabel label3 = new JLabel("\n PARABENS FINALIZOU O JOGO ! TOTAL DE PONTOS: "+PontuacaoMax);    
                        int[] anArray;
                        int w=0;
                        anArray = new int[20];
                        anArray[w] = PontuacaoMax;
                        System.out.println(PontuacaoMax);
                        w++;
                        window.add("Center", label3);               
                        window.show();                      
                        ImageIcon img = new ImageIcon("fogo.jpg");                  
                        JLabel label = new JLabel(img);
                        window.add(label, BorderLayout.NORTH);
                        window.pack();  
                        window.setVisible(true); 
                        gameBtn[btnID[0]].setEnabled(false);
                        gameBtn[btnID[1]].setEnabled(false);
                        gameBtn[btnID[0]].setVisible(true);
                        gameBtn[btnID[1]].setVisible(true);

                        //AudioClip audio = Applet.newAudioClip(cl.getResource("bottle-open.wav"));
                        //audio.play();                 
                    }

                    if (counter == 3)
                    {               
                        if (sameValues())
                        {
                            gameBtn[btnID[0]].setEnabled(false);
                            gameBtn[btnID[1]].setEnabled(false);
                            gameBtn[btnID[0]].setVisible(true);
                            gameBtn[btnID[1]].setVisible(true);
                            Hit = Hit +1;
                            Pontos = Pontos + 25;
                        }
                        else
                        {
                            gameBtn[btnID[0]].setEnabled(true);
                            gameBtn[btnID[0]].setText("");
                            gameBtn[btnID[1]].setEnabled(true);
                            gameBtn[btnID[1]].setText("");
                            Miss = Miss +1;
                            Pontos = Pontos - 5;                       
                        }
                        counter = 1; 
                    }
                    /*if (Pontos <= 0)
                    {
                        Pontos=0;
                    } */
                    if (counter == 1) // se carregar 1º botão
                    {
                        btnID[0] = i;
                        btnValue[0] = gameList.get(i);
                    }
                    if (counter == 2) // se carregar 2º botão
                    {
                        btnID[1] = i;
                        btnValue[1] = gameList.get(i);
                    }
                }
            }

            if (restartBtn == e.getSource()) // apaga a grelha
            { 
                Hit=0;
                Miss=0;
                tempo=-1;
                Pontos=0;
                for (int i = 0; i < gameBtn.length; i++)
                {
                    gameBtn[i].setText("");
                    gameBtn[i].setEnabled(true);
                    gameBtn[i].setVisible(true);    
                }
            }  

            if (maximoBtn == e.getSource()) //mostra melhor pontucao
            {
                window = new JFrame(" Jogo da Memoria - Melhores Pontuacoes:"); 
                int Max=0,PontuacaoMax=0;           

                //private static int maxValue(char[] chars) 
                //{
                    //int  = chars[0]; 
                    /*
                    int[] anArray;
                    anArray = new int[20];
                    for (int w = 0; w < anArray.length; w++) 
                    {
                        if (anArray[w]>= Max) 
                        {
                            Max = anArray[w];
                            JLabel label2 = new JLabel(" Pontuacao Maxima: "+Max);
                            window.add("Center", label2);
                        }
                    }

                    System.out.println(PontuacaoMax);
                    JLabel label5 = new JLabel(" Pontuacao: " +PontuacaoMax );
                    window.add("Center", label5); */
                    //return Pontos;
                //}
                /*
                anArray[w]=0;
                int w;
                for(w=0;w<20;w++)
                {
                    if (anArray[w]>=PontuacaoMax)
                    {
                        PontuacaoMax=anArray[w];
                        JLabel label2 = new JLabel(" Pontuacao Maxima: "+PontuacaoMax);
                        window.add("Center", label2);
                    }
                } 
                */ 
                if (Pontos >= PontuacaoMax)
                {
                    PontuacaoMax = Pontos;
                    JLabel label2 = new JLabel(" Pontuacao Maxima: "+PontuacaoMax); 
                    //Vector<Integer> v = new Vector<>();
                    //v.add(PontuacaoMax);System.out.println(PontuacaoMax);
                    window.add("Center", label2);
                }
                if (Pontos < PontuacaoMax)
                {
                    PontuacaoMax = Pontos;
                    JLabel label2 = new JLabel(" Pontuacao Maxima: 0");         
                    window.add("Center", label2);
                }    

                window.show();                      
                ImageIcon img = new ImageIcon("trofeu.jpg");           
                JLabel label = new JLabel(img); 
                window.add(label, BorderLayout.NORTH);
                window.pack();  
                window.setVisible(true); 
            }

            if (definicoesBtn == e.getSource()) //mostra melhor pontucao
            { /*
                window = new JFrame(" Jogo da Memoria - Password:");
                window.setLayout(new BorderLayout());   
                // pass(); 
                s = "123";
                msg1 = new TextField("Digite a password:"); 
                msg1.setEditable(false);
                password = new TextField(12); 
                password.setEchoCharacter('*');
                msg2 = new TextField(30); 
                msg2.setEditable(false);
                add(msg1); 
                add(password); 
                add(msg2); 

                window.resize(300,300);
                window.show();                      
                window.pack();  
                window.setVisible(true);    
                //action(e,o);  */      

                definicoesBtn.addActionListener(new ActionListener()
                {    
                    public void actionPerformed(ActionEvent evento)
                    {    
                        window = new JFrame(" Jogo da Memoria - Definicoes:");              
                        JLabel label3 = new JLabel("Escolha Nivel Dificuldade:");           
                        window.add("West", label3);                                     
                        ImageIcon img = new ImageIcon("definicoes.jpg");
                        JLabel label = new JLabel(img); 
                        window.add(label, BorderLayout.NORTH);
                        JPanel panel = new JPanel(new GridLayout(0, 1));
                        ButtonGroup group = new ButtonGroup();
                        JRadioButton aRadioButton = new JRadioButton(" Facil ");
                        JRadioButton bRadioButton = new JRadioButton(" Medio ");
                        JRadioButton cRadioButton = new JRadioButton(" Dificil ");

                        ChangeListener changeListener = new ChangeListener() 
                        {
                              public void stateChanged(ChangeEvent changEvent) 
                              {
                                    AbstractButton aButton = (AbstractButton)changEvent.getSource();
                                    ButtonModel aModel = aButton.getModel();
                                    boolean armed = aModel.isArmed();
                                    boolean pressed = aModel.isPressed();
                                    boolean selected = aModel.isSelected();

                                    aRadioButton.addActionListener(new ActionListener()
                                    {
                                        public void actionPerformed(ActionEvent e) 
                                        {                           
                                            gamePnl.setLayout(new GridLayout(4, 4));
                                            //System.out.println("4x4");
                                        }
                                    });
                                    bRadioButton.addActionListener(new ActionListener()
                                    {
                                        public void actionPerformed(ActionEvent e) 
                                        {                                       
                                            JButton[] gameBtn = new JButton[18];

                                             for (int i = 0; i < gameBtn.length; i++)
                                            {
                                                gameBtn[i] = new JButton(ButtonIcon);
                                                gameBtn[i].addActionListener(this);
                                            } 

                                            gamePnl.setLayout(new GridLayout(6, 6)); /*
                                            for (int i = 0; i < gameBtn.length; i++)
                                            {
                                                gamePnl.add(gameBtn[i]);
                                            }           */                                                  
                                        }
                                    });
                                    cRadioButton.addActionListener(new ActionListener()
                                    {
                                        public void actionPerformed(ActionEvent e) 
                                        {                                                                                   
                                            gamePnl.setLayout(new GridLayout(5, 5));                                                
                                        }
                                    });
                               }
                        };
                        panel.add(aRadioButton);
                        group.add(aRadioButton);
                        panel.add(bRadioButton);
                        group.add(bRadioButton);
                        panel.add(cRadioButton);
                        group.add(cRadioButton);
                        aRadioButton.addChangeListener(changeListener);
                        bRadioButton.addChangeListener(changeListener);
                        cRadioButton.addChangeListener(changeListener);
                        window.add(panel);                      
                        window.pack();  
                        window.setVisible(true); 
                    }    
                });             
            }
        updateHitMiss();
    }

    public static void main(String[] args)
    {      
        new MemoryGame();
    }
}
    
asked by anonymous 17.04.2015 / 13:27

1 answer

1

I think what you want is something like this. I can not be sure why you did not give the complete code, so it's hard to help you!

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;

public class JogoDaMemoria extends JFrame {
    private int counter;
    private JButton baralharBtn;
    private JButton solveBtn;
    private int[] btnID = new int[16];
    private int[] btnValue = new int[16];
    private JButton[] gameBtn = new JButton[16];

    private List<Integer> gameList;

    public void createGUI() {
        for (int i = 0; i < gameBtn.length; i++) {
            int idx = i;
            gameBtn[i] = new JButton(/*ButtonIcon*/);
            gameBtn[i].addActionListener(e -> clicou(idx));
        }

        baralharBtn = new JButton("Baralhar");
        baralharBtn.addActionListener(e -> baralhar());

        solveBtn = new JButton("Solucionar");
        solveBtn.addActionListener(e -> solucionar());
    }

    private void baralhar() {
        gameList = Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1);
        Collections.shuffle(gameList);
    }

    private void solucionar() {
        for (int i = 0; i < gameBtn.length; i++) {
            gameBtn[i].setEnabled(false);
            gameBtn[i].setVisible(true);
            gameBtn[i].setText("" + gameList.get(i));
        }
    }

    private void clicou(int i) {
        gameBtn[i].setText("" + gameList.get(i));
        gameBtn[i].setEnabled(false);
        counter++;
        if (counter == 1) // se carregar 1º botão
        {
            btnID[0] = i;
            btnValue[0] = gameList.get(i);
        }
        if (counter == 2) // se carregar 2º botão
        {
            btnID[1] = i;
            btnValue[1] = gameList.get(i);
            //outra parte do codigo, pode ser que ajude
            if (counter == 1) // se carregar 1º botão
            {
                btnID[0] = i;
                btnValue[0] = gameList.get(i);
            }
            if (counter == 2) // se carregar 2º botão
            {
                btnID[1] = i;
                btnValue[1] = gameList.get(i);
            }
        }
    }
}

What to watch for in this code:

  • Your problem is that you were adding the scrambled numbers to the list, rather than being the list itself. As a result, the list always grew, but the first 16 positions remained the same.
  • Do not put all buttons in the same ActionListener , this is a bad programming practice that unfortunately is very widespread and should be combated. In particular putting your JFrame implementing ActionListener is also a bad programming practice.

And now the ear tug:

After three questions, I have here a code in half that might solve your problem. If you had already posted a full and compilable code from the beginning, not just small snippets of variables with unknown purpose and meaning to the respondent, you would have good response in a few minutes.

This is because to answer your question, we use the compiler to compile programs, but the compiler does not accept incomplete code. There is no way to tell what happens in your program if it references a bunch of classes and variables that are not in the code you provided.

In addition, requiring other users to guess what's in the rest of your code to help you, will only serve to get a little help and lots of negative and closing votes.

Then next time, post a complete and computable code, including imports!

    
17.04.2015 / 15:24