package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GameTest extends JFrame implements ActionListener {
JLabel imguser=new JLabel();
JLabel imgpc=new JLabel();
JLabel result=new JLabel("结果是:");
public static void main(String[] args) {
new GameTest();
}
public GameTest(){
this.setTitle("我的猜拳游戏");
this.setSize(500,700);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel p=new JPanel();
p.setLayout(null);
JLabel a=new JLabel("请出拳:");
a.setBounds(100,10,60,30);
p.add(a);
JButton btn1=new JButton("剪刀");
btn1.setBounds(180,10,60,30);
p.add(btn1);
JButton btn2=new JButton("石头");
btn2.setBounds(260,10,60,30);
p.add(btn2);
JButton btn3=new JButton("布");
btn3.setBounds(340,10,60,30);
p.add(btn3);
JLabel user=new JLabel("您出的是:");
user.setBounds(100,100,80,30);
p.add(user);
JLabel pc=new JLabel("电脑出的是:");
pc.setBounds(100,300,80,30);
p.add(pc);
imguser.setBounds(200,50,180,180);
p.add(imguser);
imgpc.setBounds(200,250,180,180);
p.add(imgpc);
result.setBounds(200,500,80,30);
p.add(result);
btn1.setActionCommand("剪刀");
btn2.setActionCommand("石头");
btn3.setActionCommand("布");
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
this.add(p);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
String action=actionEvent.getActionCommand();
int user=0;
if(action.equals("剪刀")) {
user=1;
}else if(action.equals("石头")){
user=2;
}else{
user=3;
}
ImageIcon img1=new ImageIcon("img/"+user+".jpg");
imguser.setIcon(img1);
Random ran=new Random();
int pc=0;
pc=ran.nextInt(3)+1;
ImageIcon img2=new ImageIcon("img/"+pc+".jpg");
imgpc.setIcon(img2);
if(user==pc){
result.setText("平局");
}else if((user==1&&pc==2)||(user==2&&pc==3)||(user==3&&pc==1)){
result.setText("机器人胜利");
}else{
result.setText("玩家胜利");
}
}
}
(1剪刀2石头3布)效果图