import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; public class Myjava extends JFrame implements Runnable,KeyListener{ JPanel panel; long start,finish; JLabel me; int che = 1; public Myjava(int width,int height){ panel = new JPanel(); panel.setLayout(null); panel.setBackground(Color.yellow); me = new JLabel(); me.setBackground(Color.blue); me.setOpaque(true); me.setSize(10,10); me.setLocation(width/2,height-100); add(me); add(panel); addKeyListener(this); setSize(width,height); paintFrame(); start = System.currentTimeMillis(); } public void paintFrame(){ setTitle("有一定几率跑过火"); Dimension screenSize = getToolkit().getDefaultToolkit().getScreenSize(); setLocation(screenSize.width/2-getWidth()/2,screenSize.height/2-getHeight()/2); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public void element(){ int i =0; int time = 0; Random r = new Random(); int wei = r.nextInt(getWidth()); while(time<100) time = r.nextInt(500); JLabel label = new JLabel("火"); label.setSize(15,20); // label.setOpaque(true); label.setBackground(Color.yellow); // label.setForeground(Color.red); panel.add(label); label.setLocation(wei,0); while(true){ try{ Thread.sleep(time); }catch(InterruptedException e){System.out.println(e.getMessage());} i+=10; label.setLocation(wei,i); if(i>this.getHeight()){label.setLocation(wei=r.nextInt(getWidth()),0);i=0;} pzh(label.getLocation()); if(time>20)time-=1; if(che==0)break; } } public void run(){ element(); } public void pzh(Point pl){ Point pm = me.getLocation(); if(Math.abs(pl.y-pm.y)<10&&Math.abs(pl.x-pm.x)<10){ finish = System.currentTimeMillis(); int n=JOptionPane.showConfirmDialog(null,"得分:"+(finish-start)/100+"再来一次","你挂了",JOptionPane.YES_NO_OPTION); if(n==JOptionPane.YES_OPTION){ che = 0; dispose(); start(); } else System.exit(0); } } public void keyPressed(KeyEvent e){ int step = 10; Point pm = me.getLocation(); switch(e.getKeyCode()){ case KeyEvent.VK_LEFT:me.setLocation(pm.x-step,pm.y);break; case KeyEvent.VK_RIGHT:me.setLocation(pm.x+step,pm.y);break; case KeyEvent.VK_UP:me.setLocation(pm.x,pm.y-step);break; case KeyEvent.VK_DOWN:me.setLocation(pm.x,pm.y+step);break; } } public void keyReleased(KeyEvent e){ } public void keyTyped(KeyEvent e){ } public static void start(){ Myjava my = new Myjava(400,400); for(int i=0;i<8;i++) new Thread(my).start(); } public static void main(String[] args){ start(); } }