Java实现猜拳小游戏

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布)效果图

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛大了2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值