标签:
1 package MyTest; 2 3 import java.awt.*; 4 import java.awt.event.KeyEvent; 5 import java.awt.event.KeyListener; 6 7 import javax.swing.*; 8 9 public class CharGame { 10 public static void main(String args[]){ 11 JFrame w = new JFrame(); 12 w.setBounds(0, 0, 300, 520); 13 14 charPanel cp = new charPanel(); 15 w.add(cp); 16 17 cp.setBackground(Color.BLACK); 18 w.setBackground(Color.BLACK); 19 20 Thread t = new Thread(cp); 21 t.start(); 22 23 w.addKeyListener(cp); 24 cp.addKeyListener(cp); 25 26 w.setVisible(true); 27 28 } 29 30 } 31 class charPanel extends JPanel implements Runnable,KeyListener{ 32 int []x = new int[10]; 33 int []y = new int[10]; 34 char []c = new char[10]; 35 int []r = new int[255]; 36 int []a = new int[255]; 37 int []b = new int[255]; 38 int score = 100; 39 charPanel(){ 40 for(int i=0;i<10;i++){ 41 x[i] = (int)(Math.random()*300); 42 y[i] = (int)(Math.random()*500); 43 c[i] = (char)(Math.random()*26+97); 44 r[i] = (int)(Math.random()*255); 45 a[i] = (int)(Math.random()*255); 46 b[i] = (int)(Math.random()*255); 47 } 48 } 49 public void paint(Graphics g){ 50 super.paint(g); 51 Font f2 = new Font("",Font.BOLD,20); 52 g.setFont(f2); 53 g.setColor(Color.RED); 54 if(score<0){ 55 g.drawString("Game over", 100, 200); 56 return; 57 } 58 g.drawString("您的分数为:"+score, 10, 20); 59 Font f1 = new Font("",Font.BOLD,25); 60 g.setFont(f1); 61 for(int i=0;i<10;i++){ 62 g.setColor(new Color(r[i],a[i],b[i])); 63 g.drawString(""+(char)c[i], x[i], y[i]); 64 } 65 } 66 public void run() { 67 // TODO Auto-generated method stub 68 while(true){ 69 for(int i=0;i<10;i++){ 70 y[i]++; 71 if(y[i]>500){ 72 y[i]=0; 73 score-=10; 74 } 75 } 76 try{ 77 Thread.sleep(30); 78 }catch(Exception e){} 79 repaint(); 80 } 81 } 82 public void keyPressed(KeyEvent e) { 83 int yy = -1; 84 int index = -1; 85 // TODO Auto-generated method stub 86 for(int i=0;i<10;i++){ 87 if(e.getKeyChar()==c[i]){ 88 if(yy<y[i]){ 89 yy=y[i]; 90 index=i; 91 } 92 93 } 94 } 95 if(index>-1){ 96 y[index]=0; 97 x[index]=(int)(Math.random()*300); 98 c[index]=(char)(Math.random()*10+97); 99 score+=10; 100 } 101 } 102 public void keyReleased(KeyEvent arg0) { 103 // TODO Auto-generated method stub 104 105 } 106 public void keyTyped(KeyEvent arg0) { 107 // TODO Auto-generated method stub 108 109 } 110 }
标签:
原文地址:http://www.cnblogs.com/srxhmxx/p/4564384.html