javaswingx

How can you compare an image generated by random in Java?


So I'm making a mini game called Rock,Paper,and Scissors in java using Swing. enter image description here

How can I compare my user(left) image to the computer(right) generated image? So that I can put on a JLabel in the middle stating whether "You Win!" or "You Lose!" or "DRAW!"?

Here's my code I'm trying to figuring out how to enable my comparison of the image:

btrock.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        user.setIcon(new ImageIcon("ROCK LEFT.PNG"));
        int index = (int) (Math.random() * (images.length - 0));
        computer.setIcon(new ImageIcon(images[index]));
        String blah = new Integer(index).toString();
        if(user.getIcon() == computer.getIcon(images[index])){
            lbl1.setText("DRAW!");
        }
    }
});

Solution

  • for beginners you could map your Images with an according enum. then you can easily compare the values of the gesture instead of comparing images.

    enum Gesture {ROCK, SCISSOR; PAPER}
    
    Map<Gesture, ImageIcon> leftImages;
    Map<Gesture, ImageIcon> rightImages;
    
    Gesture rightGesture;
    Gesture leftGesture;
    
    void setLeftGesture(Gesture gesture) {
        leftGesture = gesture;
        setLeftImage(leftImages.get(gesture);
    }
    
    //TODO
    void setRightGesture(...);
    
    boolean isEqualGesture(){
        return rightGesture == leftGesture;
    }
    
    boolean leftWins(){
        return rightGesture == Gesture.ROCK && leftGesture == Gesture.PAPER;
    }
    
    //TODO
    boolean rightWins(){...}
    

    so whenever you set your gesture left or right you simply call these code snippets above.

    public void actionPerformed(ActionEvent e) {
        //let's assume we are on rocks:
        setLeft(Gesture.ROCK);
        setRight(randomGesture());
    
        if(isEqualGesture()) {
            //write "draw" in your text box
        }else if(leftWins()){
            //player did win, write a notification
        }else if(rightWins()){
            //computer did win
        }
    }
    

    possible implementations

    create a map:

    Map<Gesture, ImageIcon> rightImages = new HashMap<>();
    ImageIcon rightRock = new ImageIcon...//i don't know that part of your implementations
    ImageIcon rightScissor = ...
    ImageIcon rightPaper = ...
    rightImages.put(Gesture.ROCK, rightRock);
    rightImages.put(Gesture.SCISSOR, rightScissor);
    rightImages.put(Gesture.PAPER, rightPaper);
    

    the same applies for the left images. The setting up of the map should happen in the very beginning of your app. Doing so has the effect, that you load the images ONLY ONCE and can re-use them again and again. Best practice would be to create a init() methode, where you do all the setup stuff...