这是我的代码,我试图让这只猫用a,s,w,d和这个框移动,用箭头键移动。我使用switch case语句和盒子工作,但不是猫。我是编程新手,我真的需要帮助。我是否需要使用键绑定?:
public class Other extends Applet implements ActionListener, KeyListener {
public static final int MOVE_STOP = 0;
public static final int MOVE_UP = 1;
public static final int MOVE_DOWN = 2;
public static final int MOVE_RIGHT = 3;
public static final int MOVE_LEFT = 4;
public static final int MOVE_W = 5;
public static final int MOVE_S = 6;
public static final int MOVE_D = 7;
public static final int MOVE_A = 8;
int CursorDirection = MOVE_STOP;
int cursordirection = MOVE_STOP;
private ArrayList<Integer> keysDown;
public void init()
{
this.addKeyListener(this);
keysDown = new ArrayList<Integer>();
rect = new Rectangle(1000, 715, 35, 35);
}
public void paint(Graphics g){
setSize(2000, 2000);
this.CalculateMappyPosition();
//i edited the background out
}
@Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode()))
keysDown.add(new Integer(e.getKeyCode()));
moveRect();
}
@Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
public void CalculateMappyPosition() {
switch (CursorDirection) {
case MOVE_UP:
rect.y-= 100;
break;
case MOVE_DOWN:
rect.y+= 100;
break;
case MOVE_LEFT:
rect.x-= 5;
break;
case MOVE_RIGHT:
rect.x+= 5;
break;
case MOVE_A:
cat.x1-= 5;
break;
case MOVE_S:
cat.y1+= 100;
break;
case MOVE_D:
cat.x1+= 5;
break;
case MOVE_W:
cat.y1-= 100;
break;
default:
break;
}
}
public void moveRect()
{
repaint();
if(keysDown.contains(KeyEvent.VK_UP))
up();
}
if (keysDown.contains(KeyEvent.VK_DOWN))
down();
}
if(keysDown.contains(KeyEvent.VK_LEFT))
left();
}
if(keysDown.contains(KeyEvent.VK_RIGHT))
right();
}
if(keysDown.contains(KeyEvent.VK_A)){
a();
}
if(keysDown.contains(KeyEvent.VK_S)){
s();
}
if(keysDown.contains(KeyEvent.VK_D)){
}
if(keysDown.contains(KeyEvent.VK_W)){
w();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
public void up(){
CursorDirection = MOVE_UP;
}
public void down(){
CursorDirection = MOVE_DOWN;
}
public void left(){
CursorDirection = MOVE_LEFT;
}
public void right(){
CursorDirection = MOVE_RIGHT;
}
public void a(){
CursorDirection = MOVE_A;
}
public void s(){
CursorDirection = MOVE_S;
}
public void d(){
CursorDirection = MOVE_D;
}
public void w(){
CursorDirection = MOVE_W;
}
}