当前位置: 代码迷 >> 综合 >> Java打地鼠游戏
  详细解决方案

Java打地鼠游戏

热度:11   发布时间:2023-10-22 23:45:19.0

今天晚上写了一个打地鼠游戏,这里用到了线程,就复习了一下线程。

具体的实现代码如下。

package com.mouse; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Random;import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel;import org.omg.PortableServer.THREAD_POLICY_ID; public class PlayMouse extends JFrame implements Runnable{private int num;private JLabel back;private JLabel[] mouses;//9个老鼠 这里用一个数组来表示private ImageIcon imgMouse;private JLabel Jtext;public PlayMouse() {// TODO Auto-generated constructor stubthis.setResizable(false);//不能修改窗口大小this.getContentPane().setLayout(null);//手动布局,不用自带布局this.setTitle("打地鼠游戏");back=new JLabel();ImageIcon icon=new ImageIcon(this.getClass().getResource("3.jpg"));back.setIcon(icon);back.setBounds(0, 0, 400, 224);//这里图片的位置是相对窗口的位置this.setBounds(600,400,400,224);//四个参数,后面两个是背景图片大小,//前面两个是窗口出来的位置 相对屏幕的位置this.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(Toolkit.getDefaultToolkit().getImage("src/com/mouse/chuizi.png"), new Point(), "self"));//上面这句是把鼠标变成一个锤子,让游戏体验更好imgMouse=new ImageIcon(this.getClass().getResource("2.png"));mouses = new JLabel[9];for(int i=0;i<9;i++){mouses[i]=new JLabel();mouses[i].setSize(40,40);//mouses[i].setIcon(imgMouse);//给鼠标添加监听器mouses[i].addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {//加分功能Object object=e.getSource();if(object instanceof JLabel){JLabel label=(JLabel)object;if(label.getIcon()!=null){num++;Jtext.setText("您的得分是:"+num+"分"); }label.setIcon(null);}}});this.getContentPane().add(mouses[i]);}Jtext=new JLabel();Jtext.setBounds(150, 2, 150, 50);Jtext.setFont(new Font("", 10, 20));Jtext.setForeground(Color.white.brighter());Jtext.setText("您的得分是: 分");mouses[0].setLocation(72,51);mouses[1].setLocation(165,51);mouses[2].setLocation(265,51);mouses[3].setLocation(57,93);mouses[4].setLocation(164,93);mouses[5].setLocation(265,93);mouses[6].setLocation(52,140);mouses[7].setLocation(163,140);mouses[8].setLocation(272,140);this.getContentPane().add(Jtext);this.getContentPane().add(back);this.setVisible(true);} @Overridepublic void run() {while(true){try {Thread.sleep(500);int index=(int)(Math.random()*9);//产生一个0-8的随机数if(mouses[index].getIcon()==null){//如果这个位置没有图片,给它个反应时间,然后显示图片mouses[index].setIcon(imgMouse);Thread.sleep(800);//800毫秒 这里可以根据难度的不同,设置反应时间//如果给的反应时间之内,图片没有被点击,就消失if(mouses[index].isShowing()){mouses[index].setIcon(null);}}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void main(String[] args){PlayMouse p1=new PlayMouse();Thread t1=new Thread(p1);t1.start();} }