Code:
package com.mxs.util;import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class ZiMu extends JFrame {ZiMu() {this.setSize(300, 600);this.setResizable(false);this.setTitle("打字游戏");this.setBackground(Color.BLACK);MyPanel mp = new MyPanel();this.add(mp);this.addKeyListener(mp);Thread t = new Thread(mp);t.start();}public static void main(String args[]) {ZiMu w = new ZiMu();w.setVisible(true);}
}class MyPanel extends JPanel implements Runnable, KeyListener {int x[] = new int[10];int y[] = new int[10];int sum = 0;String z[] = new String[10];MyPanel() {for (int i = 0; i < 10; i++) {x[i] = (int) (Math.random() * 300);y[i] = (int) (Math.random() * 300);z[i] = new String("" + (char) (Math.random() * 25 + 65));}}public void paint(Graphics g) {super.paint(g);this.setBackground(Color.black);g.setColor(Color.WHITE);g.drawString("一分钟正确打对的字母: " + sum, 10, 560);for (int i = 0; i < 10; i++) {g.drawString(z[i], x[i], y[i]);}}public void run() {long g = System.currentTimeMillis();while (System.currentTimeMillis() - g <= 60000) {for (int i = 0; i < 10; i++) {y[i]++;if (y[i] >= 600) {sum -= 1;y[i] = (int) (Math.random() * 50);x[i] = (int) (Math.random() * 280);z[i] = new String("" + (char) (Math.random() * 25 + 65));}}try {Thread.sleep(20);} catch (Exception e) {}this.repaint();}}public void keyTyped(KeyEvent e) {// TODO: Add your code here}public void keyPressed(KeyEvent e) {String keychar = new String("" + e.getKeyChar());int yy = 0;int j = -1;for (int i = 0; i < 10; i++) {if (keychar.equals(z[i])) {if (yy < y[i]) {yy = y[i];j = i;}}}if (j != -1) {z[j] = new String("" + (char) (Math.random() * 25 + 65));y[j] = 0;sum += 1;} else {sum -= 1;}}public void keyReleased(KeyEvent e) {// TODO: Add your code here}
}