Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- import java.util.Random;
- class buttonGame
- {
- public static void main(String[] args) {
- buttonGameFrame myFrame = new buttonGameFrame();
- myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- }
- class buttonGameFrame extends JFrame implements ActionListener {
- JButton[][] buttons = new JButton[5][4];
- JPanel mPanel = new JPanel();
- JPanel bPanel = new JPanel();
- JPanel leftPanel = new JPanel();
- JPanel rightPanel = new JPanel();
- JPanel bottomPanel = new JPanel();
- JTextArea textArea = new JTextArea();
- Container c = getContentPane();
- int randomRow;
- int randomCol;
- int counter = 0;
- public buttonGameFrame() {
- buttonGenerator();
- generateRandomShot();
- changeSide();
- bPanel.setLayout(new GridLayout(5,4));
- mPanel.setLayout(new BorderLayout());
- mPanel.add(bPanel, BorderLayout.CENTER);
- mPanel.add(leftPanel, BorderLayout.WEST);
- mPanel.add(rightPanel, BorderLayout.EAST);
- bottomPanel.add(textArea);
- textArea.setText("Pozostało ruchów: 20");
- mPanel.add(bottomPanel, BorderLayout.SOUTH);
- c.add(mPanel);
- setTitle("Egzamin 25.02.2020");
- setSize(800,400);
- setLocation(200,200);
- setVisible(true);
- }
- private void buttonGenerator() {
- for(int i=0;i<5;i++)
- for(int j=0;j<4;j++) {
- buttons[i][j] = new JButton();
- buttons[i][j].setBackground(Color.yellow);
- buttons[i][j].setActionCommand("button" +i +"_" +j);
- buttons[i][j].addActionListener(this);
- bPanel.add(buttons[i][j]);
- }}
- private void generateRandomShot(){
- Random generator = new Random();
- randomRow = generator.nextInt(4);
- randomCol = generator.nextInt(3);
- System.out.println("Kolumna: " +(randomCol+1) + ", Wiersz: " + (randomRow+1));
- }
- public void changeSide(){
- if(counter%2==0) {
- leftPanel.setBackground(Color.red);
- rightPanel.setBackground(Color.white);
- } else if(counter%2!=0){
- leftPanel.setBackground(Color.white);
- rightPanel.setBackground(Color.red);
- }}
- public void actionPerformed(ActionEvent e) {
- if(e.getActionCommand().contains("button"))
- {
- int i = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll("_", "").charAt(0)));
- int j = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll("_", "").charAt(1)));
- if(j==randomCol && i==randomRow){
- JOptionPane.showMessageDialog(null, "Przegrałeś!");
- System.exit(0);
- }
- if(counter<20){
- counter++;
- changeSide();
- textArea.setText("Pozostało ruchów: " + (20-counter));
- } buttons[i][j].setBackground(Color.blue);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement