Game - Paper Rock Scissor
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class game extends JFrame implements ActionListener {
JRadioButton rb1,rb2,rb3;
ButtonGroup grp;
JButton btn;
public game(){
setSize(500,300);
setVisible(true);
setLayout(null);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1 = new JRadioButton("Rock");rb1.setBounds(30,30,100,30);
rb2 = new JRadioButton("Scissor");rb2.setBounds(30,65,100,30);
rb3 = new JRadioButton("Paper");rb3.setBounds(30,100,100,30);
grp = new ButtonGroup();
grp.add(rb1);
grp.add(rb2);
grp.add(rb3);
btn = new JButton("Result: ");btn.setBounds(30,140,450,30);
rb1.addActionListener(this);
rb2.addActionListener(this);
rb3.addActionListener(this);
add(rb1);
add(rb2);
add(rb3);
add(btn);
}
public void actionPerformed(ActionEvent ae){
String options[] = {"Rock","Scissor","Paper"};
int rand = (int)(Math.random() * (3)) + 1;
System.out.println("Random: "+rand);
if(rand>0){
rand -=1;
}
System.out.println("Random: "+rand);
String str = "";
String yourchoice="";
if(rb1.isSelected()){
yourchoice = "Rock";
}else if(rb2.isSelected()){
yourchoice = "Scissor";
} else if(rb3.isSelected()){
yourchoice = "Paper";
}
if(yourchoice.equals(options[rand]))
{
str = "Same Selection-- Your choice:"+yourchoice+" Computer's Choice: "+options[rand];
btn.setBackground(Color.GREEN);
}else
{
str = "Different Selection-- Your choice:"+yourchoice+" Computer's Choice: "+options[rand];
btn.setBackground(Color.RED);
}
btn.setText(str);
}
public static void main(String[] aa){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new game();
}
});
}
}