栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现猜拳小游戏

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1007127.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号