import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Rat here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Rat extends Actor
{
private int speed = 1;
/**
* Act - do whatever the Rat wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (int i = 0; i < speed; i++) move();
}
private void move()
{
int dx = 0, dy = 0;
if (Greenfoot.isKeyDown("up")) dy--;
if (Greenfoot.isKeyDown("down")) dy++;
if (Greenfoot.isKeyDown("left")) dx--;
if (Greenfoot.isKeyDown("right")) dx++;
setLocation(getX() + dx, getY());
if (getOneIntersectingObject(Wall.class) != null)
{
if (dy == 0)
{
setLocation(getX(), getY() + 1);
if (getOneIntersectingObject(Wall.class) == null) return;
setLocation(getX(), getY() - 2);
if (getOneIntersectingObject(Wall.class) == null) return;
setLocation(getX() - dx, getY() + 1);
return;
}
setLocation(getX() - dx, getY());
}
setLocation(getX(), getY() + dy);
if (getOneIntersectingObject(Wall.class) != null)
{
if (dx == 0)
{
setLocation(getX() + 1, getY());
if (getOneIntersectingObject(Wall.class) == null) return;
setLocation(getX() - 2, getY());
if (getOneIntersectingObject(Wall.class) == null) return;
setLocation(getX() + 1, getY() - dy);
return;
}
setLocation(getX(), getY() - dy);
}
}
}
