import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Move extends Applet implements KeyListener,ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Button b_go=new Button("go");//一个代表人的按钮
Rectangle rect1,rect2,rect3;
int b_x=0,b_y=0;
public void init()
{
b_go.addKeyListener(this);
setLayout(null);
rect1=new Rectangle(20,40,200,40);//画长方形,也就是设置轨道,大家可以尝试一下更复杂的轨道
rect2=new Rectangle(200,40,40,200);
rect3=new Rectangle(200,220,100,40);
b_go.setBackground(Color.lightGray);//设置背景颜色
add(b_go); //添加按钮到窗口中
b_go.setBounds(22,45,20,20);
b_x=b_go.getBounds().x; //设置按钮每一步的移动为坐标
b_y=b_go.getBounds().y;
b_go.requestFocus();
}
public void paint(Graphics g)
{
g.setColor(Color.green); //为轨道添加颜色,使其更显眼
g.fillRect(20, 40, 200, 40);
g.setColor(Color.YELLOW);
g.fillRect(200,40,40,200);
g.setColor(Color.CYAN);
g.fillRect(200, 220, 100, 40);
g.drawString("出口",310,260);
g.setColor(Color.BLACK);
}
public void keyPressed(KeyEvent e)
{
if((e.getKeyCode()==KeyEvent.VK_UP)) //设置键盘中上键所控制的动作
{
Rectangle rect=new Rectangle(b_x,b_y); //创建一个和按钮一样大的矩形
if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects
(rect3)) //让按钮就只能在轨道中运动
{ //以下都是同理
b_y=b_y-2;
b_go.setLocation(b_x,b_y);
}
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
Rectangle rect=new Rectangle(b_x,b_y,20,20);
if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects(rect3))
{
b_y=b_y+2;
b_go.setLocation(b_x,b_y);
}
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
Rectangle rect=new Rectangle(b_x,b_y,20,20);
if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects(rect3))
{
b_x=b_x-2;
b_go.setLocation(b_x, b_y);
}
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
Rectangle rect=new Rectangle(b_x,b_y,20,20);
if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects(rect3))
{
b_x=b_x+2;
b_go.setLocation(b_x, b_y);
}
}
}
public void keyReleased(KeyEvent arg0)
{
}
public void keyTyped(KeyEvent arg0)
{
}
public void actionPerformed(ActionEvent e)
{
b_go.setBounds(22,45,20,20);
b_x=b_go.getBounds().x;
b_y=b_go.getBounds().y;
b_go.requestFocus();
}
}
这个还是比较简单 没有设置结束,重新开始等等这些机制,轨道也只是随便画了一下。
大家可以尝试更为复杂一点的程序^_^