我正在为我的计算机科学课制作一个游戏,我正在尝试使用箭头键移动一个扩展 Bug 的角色对象。我应该把代码用箭头键移动到 Character 类还是 World 类中?代码应该是什么样的?现在我已经在 Character 类中得到了这段代码,它符合要求,但是当我尝试在网格中运行它时,当我按下箭头键时没有任何反应。
public class Character extends Bug
{
Random pokemon;
public Character()
{
}
public void act(KeyEvent e)
{
move(e);
pokemon = new Random();
if(pokemon.nextInt(10) == 5)
System.out.println("It works!!");
}
public void move(KeyEvent e)
{
Grid<Actor> gr = getGrid();
Location loc = getLocation();
if(gr == null)
return;
if( e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(!(getDirection() == 90))
setDirection(90);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(!(getDirection() == 270))
setDirection(270);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_UP)
{
if(!(getDirection() == 0))
setDirection(0);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(!(getDirection() == 180))
setDirection(180);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
public class Character extends Bug
{
Random pokemon;
public Character()
{
}
public void act(KeyEvent e)
{
move(e);
pokemon = new Random();
if(pokemon.nextInt(10) == 5)
System.out.println("It works!!");
}
public void move(KeyEvent e)
{
Grid<Actor> gr = getGrid();
Location loc = getLocation();
if(gr == null)
return;
if( e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(!(getDirection() == 90))
setDirection(90);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(!(getDirection() == 270))
setDirection(270);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_UP)
{
if(!(getDirection() == 0))
setDirection(0);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(!(getDirection() == 180))
setDirection(180);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
此代码对于 KeyEvent 是否正确,我如何从 World 类调用此代码?任何帮助将不胜感激!