import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.util.Vector; import javax.swing.JFrame; public class keyTest extends Window implements KeyListener, Runnable { int width, height; BufferedImage buf; Graphics gc; boolean play = true; Vector<oneChar> keys = new Vector<oneChar>(); int ok = 0, fail = 0, error = 0, sum = 0; Font small = new Font("宋体", 0, 30); Font big = new Font("宋体", 0, 50); long time = System.currentTimeMillis(); keyTest(Frame f) { super(f); Dimension s = getToolkit().getScreenSize(); width = (int) s.getWidth(); height = (int) s.getHeight(); this.setBounds(0, 0, width, height); this.buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); gc = buf.getGraphics(); this.setVisible(true); this.setAlwaysOnTop(true); this.buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); gc = buf.getGraphics(); new Thread(this).start(); } public static void main(String s[]) { JFrame help = new JFrame("打字练习"); help.setVisible(true); help.setDefaultCloseOperation(3); help.addKeyListener(new keyTest(help)); } public void keyTyped(KeyEvent e) { } public synchronized void keyPressed(KeyEvent e) { if (e.getKeyCode() == 27) { play = false; this.dispose(); System.exit(0); } char s = e.getKeyChar(); if (s >= 'a' && s <= 'z' || (s >= 'A' && s <= 'Z')) { String l = "" + s; for (int i = 0; i < keys.size(); i++) { if (l.equals(((oneChar) keys.elementAt(i)).s)) { keys.removeElementAt(i); ok++; return; } } error++; } } public void keyReleased(KeyEvent e) { } @Override public void update(Graphics g) { gc.setColor(Color.BLACK); gc.fillRect(0, 0, width, height); gc.setColor(Color.red); int l = (ok + error) > 0 ? (ok * 100 / (ok + error)) : 100; gc.setFont(small); gc.drawString("成功:" + ok + " 错误:" + error + " 失败:" + fail + " 正确率:" + l + "% 时间:" + (System.currentTimeMillis() - time) / 1000, 10, height - 30); gc.setFont(big); oneChar o; for (int i = 0; i < keys.size(); i++) { o = keys.elementAt(i); gc.setColor(o.c); gc.drawString(o.s, o.x, o.y += 6); if (o.y > height - 10) { fail++; keys.removeElementAt(i); } } g.drawImage(buf, 0, 0, null); } public void run() { while (play) { try { sum++; if (sum % 5 == 0) { newchar(); } Thread.sleep(80); repaint(); } catch (InterruptedException ex) { ex.printStackTrace(); } } } private void newchar() { keys.add(oneChar.getinstance(width)); } } package chen; import java.awt.Color; public class oneChar { static java.util.Random r = new java.util.Random(); public static oneChar getinstance(int maxX) { oneChar a = new oneChar(); int b = r.nextInt(26); a.s = "" + (char) (b + (r.nextInt(4) > 1 ? 'a' : 'A')); a.x = r.nextInt(maxX - 30); a.c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)); return a; } int x, y; Color c; String s; }
gui 打字游戏
最新推荐文章于 2020-07-10 17:26:42 发布