标签:
1 package com.java7.mychar.main; 2 import java.awt.Color; 3 import java.awt.Frame; 4 import java.awt.Graphics; 5 import java.awt.Panel; 6 import java.awt.event.KeyEvent; 7 import java.awt.event.KeyListener; 8 9 public class MyChar { 10 public static void main(String[] args) { 11 Frame w = new Frame(); 12 w.setSize(600, 800); 13 14 MyPanel mp = new MyPanel(); 15 w.add(mp); 16 17 Thread t = new Thread(mp); 18 t.start(); 19 20 w.addKeyListener(mp); 21 mp.addKeyListener(mp); 22 23 w.show(); 24 } 25 } 26 27 class MyPanel extends Panel implements Runnable , KeyListener { 28 int x[] = new int[10]; 29 int y[] = new int[10]; 30 char c[] = new char[10]; 31 int score = 1000; 32 // structure method 33 MyPanel() { 34 for(int i = 0; i < 10; i++) { 35 x[i] = (int)(Math.random() * 580); 36 y[i] = (int)(Math.random() * 600); 37 c[i] = (char)(Math.random() * 26 + 97); 38 } 39 } 40 public void paint(Graphics g) { 41 for(int i = 0; i < 10; i++) { 42 g.setColor(Color.BLUE); 43 g.drawString(new Character(c[i]).toString(), x[i], y[i]); 44 } 45 g.setColor(Color.RED); 46 g.drawString("你的成绩是:" + score, 5, 15); 47 } 48 // 利用线程的repaint方法,让字母由上至下滑落 49 public void run() { 50 while(true) { 51 for(int i = 0; i < 10; i++) { 52 y[i]++; 53 // 如字母滑到底部没有被消除,则重新回到顶部生成随机字母,并扣100分 54 if(y[i] > 700) { 55 y[i] = 0; 56 x[i] = (int)(Math.random() * 550); 57 c[i] = (char)(Math.random() * 26 + 97); 58 score -= 100; 59 } 60 } 61 try { 62 Thread.sleep(30); 63 } catch(Exception e) { 64 65 } 66 repaint(); 67 } 68 } 69 @Override 70 public void keyPressed(KeyEvent arg0) { 71 // 将用户输入的字符存入keyC中 72 char keyC = arg0.getKeyChar(); 73 int nowY = -1; 74 int nowIndex = -1; 75 // 扫描整个数组,看有没有匹配的字符 76 for(int i = 0; i < 10; i++) { 77 if(keyC == c[i]) { // 如果匹配(可能同时匹配多个) 78 if(y[i] > nowY) { // 从0-9扫描索引,寻找最大的y坐标 79 // 若发现更大的y坐标,则将该坐标值赋给nowY,直至nowY => y[i] 80 nowY = y[i]; 81 nowIndex = i; 82 } 83 } 84 } 85 // 消除最底下的匹配字母并从顶部重新生成随机字母 86 if(nowIndex != -1) { 87 y[nowIndex] = 0; 88 x[nowIndex] = (int)(Math.random() * 580); 89 c[nowIndex] = (char)(Math.random() * 26 + 97); 90 score += 10; 91 } else { // 92 score -= 100; 93 } 94 } 95 @Override 96 public void keyTyped(KeyEvent e) { 97 // TODO Auto-generated method stub 98 99 } 100 @Override 101 public void keyReleased(KeyEvent e) { 102 // TODO Auto-generated method stub 103 104 } 105 }
标签:
原文地址:http://www.cnblogs.com/fatoland/p/4198714.html