Как добавить один actionListener для нескольких кнопок, чтобы добавить последовательность нажатых кнопок в arrayList? - PullRequest
0 голосов
/ 18 июня 2020

Я пишу программу для игры в Simon. Моя цель - сохранить последовательность нажатых кнопок в списке массивов, а затем сравнить ее с другим списком массивов, который имеет случайно сгенерированную последовательность. Моя проблема в том, что мой код может зарегистрировать только одно нажатие кнопки. Мой код размещен ниже. Я просмотрел похожие сообщения, но не смог придумать способ адаптировать объяснения для решения проблемы самостоятельно. Мой код ниже. Спасибо.

  import java.awt.*;
  import java.awt.event.*;
  import java.util.ArrayList;
  import javax.swing.*;
  import java.util.List;
  import java.util.Random;

  public class Simon implements ActionListener, MouseListener
  {
      private List<Integer> input;
      private List<Integer> pattern;

      private int round, score, flashed;

      private Random rand = new Random();
      JButton b1, b2, b3, b4, b5;
      public Simon()
      {
          input = new ArrayList<>();
          pattern = new ArrayList<>();

          round = 1;
          score = 0;

          JFrame f=new JFrame("Simon");
          b1 = new JButton("");
          b2 = new JButton("");
          b3 = new JButton("");
          b4 = new JButton("");
          b1.setBounds(0,0,200,200);
          b1.setBackground(Color.GREEN);
          b2.setBounds(0,200,200,200);
          b2.setBackground(Color.BLUE);
          b3.setBounds(200,200,200,200);
          b3.setBackground(Color.RED);
          b4.setBounds(200,0,200,200);
          b4.setBackground(Color.YELLOW);

          b1.addActionListener(this);
          b2.addActionListener(this);
          b3.addActionListener(this);
          b4.addActionListener(this);

          b5 = new JButton("Start");
          b5.setBounds(100, 500, 70, 30);
          b5.setBackground(Color.DARK_GRAY);

          f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);
          f.setSize(600,600);
          f.setLayout(null);
          f.setVisible(true);

          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }


    public void play()
    {
        for (int i = 0; i <= score; i++)
        {
            flashed = rand.nextInt(4) + 1;
            if (flashed == 1)
            {
                pattern.add(1);
                b1.setBackground(Color.DARK_GRAY);
                try { Thread.sleep(1000); } catch (InterruptedException ex) { }
                b1.setBackground(Color.GREEN);
            }

            if (flashed == 2)
            {
                pattern.add(2);
                b2.setBackground(Color.DARK_GRAY);
                try { Thread.sleep(1000); } catch (InterruptedException ex) { }
                b2.setBackground(Color.BLUE);
            }

            if (flashed == 3)
            {
                pattern.add(3);
                b3.setBackground(Color.DARK_GRAY);
                try { Thread.sleep(1000); } catch (InterruptedException ex) { }
                b3.setBackground(Color.RED);
            }

            if (flashed == 4)
            {
                pattern.add(4);
                b4.setBackground(Color.DARK_GRAY);
                try { Thread.sleep(1000); } catch (InterruptedException ex) { }
                b4.setBackground(Color.YELLOW);
            }

            System.out.println("pattern: " + pattern);
        }

    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == b1)
            input.add(1);
        if (e.getSource() == b2)
            input.add(2);
        if (e.getSource() == b3)
            input.add (3);
        if (e.getSource() == b4)
            input.add(4);
        System.out.println("input: " + input);

        result();
    }

    public void result()
    {
        if ( pattern.equals(input))
        {
            score++;
            round++;
            pattern.clear();
            input.clear();
            play();
        }
        else
        {
            pattern.clear();
            input.clear();
            round = 1;
            System.out.println("Game over. Score: " + score);
            score = 0;
        }

    }



    public static void main(String[] args)
    {

        Simon app = new Simon();
        for (int i = 0; i < app.round; i++)
        {
            app.play();
        }


    }
 }
...