50,542
社区成员
发帖
与我相关
我的任务
分享
class MovingRabbit extends JFrame implements KeyListener{
int position; //从0到39循环
int getCol(){
if (position <= 10) return position;
else if (position <= 20) return 10;
else if (position <= 30) return 30-position;
else return 0;
}
int getRow(){
if (position <= 10) return 0;
else if (position <= 20) return position-10;
else if (position <= 30) return 10;
else return 40-position;
}
public MovingRabbit(){
this.setTitle("兔子游戏");
this.setBounds(0, 0, 200+20, 200+40);
this.position = 2; //兔子起始位置
this.addKeyListener(this);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(10, 30, 200, 200);
g.setColor(Color.RED);
g.fillOval(getCol()*20+5,
getRow()*20+25,
5,5);
}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){
char c = e.getKeyChar();
if (c=='\u001B') System.exit(0);
int num = c - '0';
if (num>=0 && num<=9)
if (num%2==0) position -= 1;
else position -= 3;
if (position<0) position += 40;
this.repaint();
}
public static void main(String[] args){
JFrame f = new MovingRabbit();
}
}