1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| package practice1;
import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*;
public class MyTest { public static void main(String args[]) { JFrame w = new JFrame(); w.setSize(800, 600);
MyPanel mp = new MyPanel(); w.add(mp); Thread t = new Thread(mp); t.start(); w.addKeyListener(mp); mp.addKeyListener(mp); w.setVisible(true); } }
class MyPanel extends JPanel implements Runnable, KeyListener { int[] x = new int[300]; int[] y = new int[300]; char[] c = new char[10]; int[] cx = new int[10]; int[] cy = new int[10]; int score = 0; public MyPanel() { for (int i = 0; i < 300; i++) { x[i] = (int)(Math.random()*800); y[i] = (int)(Math.random()*600); } for (int i = 0; i < 10; i++) { c[i] = (char)(Math.random()*26 + 97); cx[i] = (int)(Math.random()*700); cy[i] = (int)(Math.random()*100); }
} public void paint(Graphics g) { setBackground(Color.black); super.paint(g); g.setColor(Color.white); for (int i = 0; i < 300; i++) { g.drawString("*", x[i], y[i]); } for (int i = 0; i < 10; i++) { g.setFont(new Font("Tahoma", Font.BOLD, 35)); g.setColor(Color.green); g.drawString((new Character(c[i])).toString(), cx[i], cy[i]); } g.setColor(Color.red); g.drawString("Score:"+score, 50, 50); } public void run() { while(true) { for (int i = 0; i < 300; i++) { if (y[i] > 600) { y[i] = 0; } else { y[i]++; } } for (int i = 0; i < 10; i++) { if (cy[i] > 600) { cy[i] = 0; score -=100; } else { cy[i]++; } } try { Thread.sleep(20); } catch(Exception e) { } repaint(); } }
@Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { char keyCode = e.getKeyChar(); boolean mark = false; for (int i = 0; i < 10; i++) { if (keyCode == c[i]) { c[i] = (char)(Math.random()*26 + 97); cx[i] = (int)(Math.random()*700); cy[i] = (int)(Math.random()*100); mark = true; break; } } if (mark) { score += 10; } } @Override public void keyReleased(KeyEvent e) { } }
|