0

Right now I'm working on a rock paper scissors project.

It is pretty simple, but I am new to java and am struggling with a few aspects of the game.

I have the basic game all working and good, but I am trying to add in a scoring system that is shown in either the top or bottom corners and every time you win your score goes up, and same with the computer, I haven't really decided yet where to put them though.

I am using JLabels for the numbers and I have been trying a few methods, some of the failed ones are still there though.

I have been using integer to String for the label. I am having trouble with both updating the number when someone scores, and positioning the JLabels.

So far most of the stuff pertaining the score is in the score method near the bottom of the code and the variables for most of the scoring thing are yourNum, yourScore, compScore, compNum.

For the positioning issue, I hope to use absolute positioning but i don't fully understand how I would use this with my JLabel, so if someone could explain how to use it in my situation that would be great. Here is my full code.

public class main extends JFrame implements ActionListener {

    JButton rock;
    JButton scissors;
    JButton paper;
    JLabel left;
    ImageIcon rock1;
    ImageIcon scissors1;
    ImageIcon scissors2;
    ImageIcon paper2;
    ImageIcon paper1;
    ImageIcon rock2;
    ImageIcon back;
    ImageIcon scissorsb;
    JLabel right;
    String[] RPS = {"Rock", "Paper", "Scissors"};
    Random rand = new Random();
    int num = rand.nextInt(RPS.length);
    int yourChoice = -1;
    JTextField texter;
    JLabel winner;
    Container contentPane = this.getContentPane();
    SpringLayout layout = new SpringLayout();
    String Tie = "Tie";
    String compwins = "Computer wins!";
    String youwin = "You win!";
    int yourNum = 9;
    JLabel yourScore;
    int compNum = 0;
    JLabel compScore;
    Font winnerFont = new Font("Font", Font.PLAIN, 35);

    public main() {
        super("Rock Paper Scissors");
        back = new ImageIcon("image1233450665506.png");
        paper1 = new ImageIcon("paper1.png");
        paper2 = new ImageIcon("paper2.png");
        scissors1 = new ImageIcon("scissors1.png");
        scissors2 = new ImageIcon("scissors2.png");
        rock1 = new ImageIcon("rock1.png");
        rock2 = new ImageIcon("rock2.png");
        JLabel background = new JLabel(back);
        left = new JLabel();
        right = new JLabel();
        winner = new JLabel();
        yourScore = new JLabel();
        compScore = new JLabel();
        right.setVisible(true);
        this.setVisible(true);
        this.setSize(1280, 985);
        winner.setFont(winnerFont);
        winner.setHorizontalAlignment(SwingConstants.CENTER);
        yourScore.setFont(winnerFont);
        compScore.setFont(winnerFont);
        contentPane.setLayout(layout);
        contentPane.add(winner);
        contentPane.add(left);
        contentPane.add(right);
        contentPane.add(yourScore);
        contentPane.add(compScore);
        layout.putConstraint(SpringLayout.NORTH, left, 300, SpringLayout.NORTH, contentPane);
        layout.putConstraint(SpringLayout.NORTH, right, 300, SpringLayout.NORTH, contentPane);
        layout.putConstraint(SpringLayout.EAST, right, 0, SpringLayout.EAST, contentPane);
        rock = new JButton("Rock");
        paper = new JButton("Paper");
        scissors = new JButton("Scissors");
        layout.putConstraint(SpringLayout.WEST, rock, 500, SpringLayout.WEST, contentPane);
        this.add(rock, BorderLayout.NORTH);
        layout.putConstraint(SpringLayout.SOUTH, rock, -30, SpringLayout.SOUTH, contentPane);
        layout.putConstraint(SpringLayout.WEST, rock, 40, SpringLayout.NORTH, contentPane);
        this.add(paper, BorderLayout.NORTH);
        layout.putConstraint(SpringLayout.SOUTH, paper, -30, SpringLayout.SOUTH, contentPane);
        layout.putConstraint(SpringLayout.WEST, paper, 200, SpringLayout.NORTH, contentPane);
        this.add(scissors, BorderLayout.NORTH);
        layout.putConstraint(SpringLayout.SOUTH, scissors, -30, SpringLayout.SOUTH, contentPane);
        layout.putConstraint(SpringLayout.WEST, scissors, 360, SpringLayout.NORTH, contentPane);
        rock.setBackground(Color.GRAY);
        rock.setPreferredSize(new Dimension(140, 50));
        paper.setBackground(Color.WHITE);
        paper.setPreferredSize(new Dimension(140, 50));
        scissors.setBackground(Color.LIGHT_GRAY);
        scissors.setPreferredSize(new Dimension(140, 50));
        rock.repaint();
        scissors.repaint();
        paper.repaint();
        contentPane.add(background);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        rock.doClick();
        paper.doClick();
        scissors.doClick();
        rock.addActionListener(this);
        paper.addActionListener(this);
        scissors.addActionListener(this);

    }

    public static void main(String args[]) {
        main framer = new main();
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (arg0.getSource() == rock) {
            left.setIcon(rock1);
            yourChoice = 0;
        } else if (arg0.getSource() == paper) {
            left.setIcon(paper1);
            yourChoice = 1;
        } else if (arg0.getSource() == scissors) {
            left.setIcon(scissors1);
            yourChoice = 2;
        }
        computerMove();
        Score();
    }

    public void Score() {
        layout.putConstraint(SpringLayout.NORTH, winner, 50, SpringLayout.NORTH, contentPane);
        layout.putConstraint(SpringLayout.WEST, winner, 560, SpringLayout.WEST, contentPane);
        layout.putConstraint(SpringLayout.SOUTH, compScore, 100, SpringLayout.SOUTH, contentPane);
        layout.putConstraint(SpringLayout.EAST, compScore, 600, SpringLayout.EAST, contentPane);
        yourScore = new JLabel(Integer.toString(yourNum));
        compScore = new JLabel(Integer.toString(compNum));

        if (num == 0 && yourChoice == 0) {
            winner.setText(Tie);
            winner.repaint();
        } else if (num == 1 && yourChoice == 0) {
            yourNum++;
            yourScore.repaint();
            winner.setText(compwins);
            winner.repaint();
        } else if (num == 2 && yourChoice == 0) {
            compNum++;
            compScore.repaint();
            winner.setText(youwin);
            winner.repaint();
        } else if (num == 0 && yourChoice == 1) {
            yourNum++;
            yourScore.repaint();
            winner.setText(youwin);
            winner.repaint();
        } else if (num == 1 && yourChoice == 1) {
            winner.setText(Tie);
            winner.repaint();
        } else if (num == 2 && yourChoice == 1) {
            compNum++;
            compScore.repaint();
            winner.setText(compwins);
            winner.repaint();
        } else if (num == 0 && yourChoice == 2) {
            compNum++;
            compScore.repaint();
            winner.setText(compwins);
            winner.repaint();
        } else if (num == 1 && yourChoice == 2) {
            yourNum++;
            yourScore.repaint();
            winner.setText(youwin);
            winner.repaint();
        } else if (num == 2 && yourChoice == 2) {
            winner.setText(Tie);
            winner.repaint();
        }
        winner.repaint();
        yourScore.repaint();
        compScore.repaint();
        yourScore.setForeground(Color.RED);
        compScore.setForeground(Color.RED);
        winner.setForeground(Color.RED);
    }

    public void computerMove() {
        num = rand.nextInt(RPS.length);
        if (num == 0) {
            right.setIcon(rock2);
        } else if (num == 1) {
            right.setIcon(paper2);
        } else if (num == 2) {
            right.setIcon(scissors2);
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366

2 Answers2

0

First of all, I hate absolute positioning.

If you want to use absolute positioning you have to set to null the layout of the parent container (that can be a JFrame or whatever you want).

Then you can add a new JLabel an positionate it with setLocation() method.

By the way I think there are some problem with your code, maybe copy paste issues. if you want to post something and have someone to read it try to poste an SSCCE

But I always suggest to use something like BoxLayout. Please take a look at this answer of mine that is interesting for graphics:

Positioning of components (how to place a few buttons center screen same size)

Jframe not the right size when its executed, any reason why?

Community
  • 1
  • 1
Gianmarco
  • 2,536
  • 25
  • 57
  • I have no problem not using absolute positioning, if there's a better way and I could get it to work. the method I have used previously for positioning other items hasn't worked for these, but I think this is because I'm doing something wrong. If you could look at what I have done previously (I don't know what its called) and see how I could make that work for my JLabels that would be great. Also for some reason SSCCE is not working for me and I can't connect, so if you could tell me what my errors were that would help. Thanks! – The Floating Llama Oct 17 '12 at 23:00
  • Try to use a layout, instead to insist to have your code corrected, I think you will lose less time ;). sscce is a short self contained correct example. Something I can copy-paste to my IDE and work without other stuff. – Gianmarco Oct 18 '12 at 02:52
0

I would avoid absolute layouts with a passion.

Not only do you need to monitor for changes to each component to see when it might change size, you need to take into consideration how those changes might effect each other component and monitor for changes to the parent container...And don't even get me started on differences between platforms, fonts, screen resolutions...

Why waster your time when Swing already does all this for you...

I'd use a compound layouts to contain the individual areas of interest.

For example, I'd put all the player controls into a panel, I'd place any computer output into it's own panel and I'd put the score into there own panel.

This separates the responsibility to each container, allowing you to use different layouts for each part without need to spend time trying to get them to align through a single layout.

Now this is just my take, you could do loads of other things and approach the problem from many different ways...

enter image description here

public class RPS {

    public static void main(String[] args) {
        new RPS();
    }

    public RPS() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new RockPaperScissors());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class RockPaperScissors extends JPanel implements ActionListener {

        public static final String[] NAMES = {"Rock", "Paper", "Scissors"};

        public static final int ROCK = 0;
        public static final int PAPER = 1;
        public static final int SCISSORS = 2;

        private JButton rockButton;
        private JButton paperButton;
        private JButton scissorsButton;
        private JLabel playerChoice;
        private JLabel computerChoice;

        private JLabel playerScore;
        private JLabel computerScore;
        private JLabel winner;

        private int playerScoreValue = 0;
        private int computerScoreValue = 0;

        public RockPaperScissors() {

            JPanel playerPane = new JPanel(new GridBagLayout());
            rockButton = new JButton("Rock");
            rockButton.setActionCommand("rock");
            paperButton = new JButton("Paper");
            paperButton.setActionCommand("paper");
            scissorsButton = new JButton("Scissors");
            scissorsButton.setActionCommand("scissors");

            rockButton.addActionListener(this);
            paperButton.addActionListener(this);
            scissorsButton.addActionListener(this);

            playerPane.setBorder(new TitledBorder("Player"));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.CENTER;
            playerPane.add(rockButton);
            gbc.gridx++;
            playerPane.add(paperButton);
            gbc.gridx++;
            playerPane.add(scissorsButton);

            playerChoice = new JLabel(" ");
            gbc.gridx = 0;
            gbc.gridy = 1;
//            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.gridwidth = 3;
            gbc.insets = new Insets(12, 12, 12, 12);
            playerPane.add(playerChoice, gbc);

            computerChoice = new JLabel(" ");
            computerChoice.setHorizontalAlignment(JLabel.CENTER);
            JPanel computerPane = new JPanel(new BorderLayout());
            computerPane.setBorder(new TitledBorder("Computer"));
            computerPane.add(computerChoice);

            JPanel competitorsPane = new JPanel(new GridLayout(1, 2));
            competitorsPane.add(playerPane);
            competitorsPane.add(computerPane);

            JPanel scoresPane = new JPanel(new GridLayout(1, 3));
            scoresPane.setBorder(new TitledBorder("Scores"));
            playerScore = new JLabel("0");
            playerScore.setHorizontalAlignment(JLabel.CENTER);
            computerScore = new JLabel("0");
            computerScore.setHorizontalAlignment(JLabel.CENTER);
            winner = new JLabel("");
            winner.setHorizontalAlignment(JLabel.CENTER);
            scoresPane.add(playerScore);
            scoresPane.add(winner);
            scoresPane.add(computerScore);

            setLayout(new BorderLayout());
            add(competitorsPane);
            add(scoresPane, BorderLayout.SOUTH);

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JButton choice = (JButton) e.getSource();
            playerChoice.setText(choice.getText());

            int playerValue = -1;
            if (playerChoice.getText().equalsIgnoreCase("Rock")) {
                playerValue = 0;
            } else if (playerChoice.getText().equalsIgnoreCase("Paper")) {
                playerValue = 1;
            } else if (playerChoice.getText().equalsIgnoreCase("Scissors")) {
                playerValue = 2;
            }

            int myChoice = (int)Math.round(Math.random() * 2);
            computerChoice.setText(NAMES[myChoice]);

            String whoWon = "Computer wins";
            if (playerValue == myChoice) {
                whoWon = "Draw";
            } else if ((playerValue == ROCK && myChoice != PAPER) ||
                    (playerValue == PAPER && myChoice != SCISSORS) ||
                    (playerValue == SCISSORS && myChoice != ROCK)) {
                whoWon = "Player Wins";
                playerScoreValue++;
            } else {
                computerScoreValue++;
            }

            winner.setText(whoWon);
            playerScore.setText(Integer.toString(playerScoreValue));
            computerScore.setText(Integer.toString(computerScoreValue));

        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366