
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class MyChar extends JFrame{
public MyChar(){
MyPanel mp=new MyPanel();
Thread t=new Thread(mp);
t.start();
mp.addKeyListener(mp);
this.addKeyListener(mp);
this.add(mp);
this.setSize(300,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
MyChar mc=new MyChar();
mc.setVisible(true);
}
}
class MyPanel extends JPanel implements Runnable,KeyListener{
private int[] x=new int[10];
private int[] y=new int[10];
private char[] c=new char[10];
private int score=1000;
public MyPanel(){
for(int i=0;i<10;i++){
x[i]=(int)(Math.random()*280);
y[i]=(int)(Math.random()*200);
c[i]=(char)(Math.random()*26+97);
}
}
public void paint(Graphics g){
super.paint(g);
g.setFont(new Font("黑体",Font.BOLD,20));
for(int i=0;i<10;i++){
g.drawString(new Character(c[i]).toString(),x[i],y[i]);
}
g.setColor(Color.red);
g.drawString("你的成绩为:"+score, 5, 20);
}
public void keyPressed(KeyEvent e){
int nowY=-1;
int nowIndex=-1;
char ch=e.getKeyChar();
for(int i=0;i<10;i++){
if(ch==c[i]){
if(y[i]>nowY){
nowY=y[i];
nowIndex=i;
}
}
}
if(nowIndex!=-1){
x[nowIndex]=(int)(Math.random()*280);
y[nowIndex]=0;
c[nowIndex]=(char)(Math.random()*26+97);
score+=10;
}else{
score-=100;
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
public void run(){
while(true){
for(int i=0;i<10;i++){
y[i]++;
if(y[i]>400){
x[i]=(int)(Math.random()*280);
y[i]=0;
c[i]=(char)(Math.random()*26+97);
score-=100;
}
if(score<0){
score=0;
}
}
try{
Thread.sleep(50);
}catch(Exception e){
}
this.repaint();
}
}
}