In: Computer Science
ITP 100 Programming Assignment 1
This program uses the Little-Crab-3 scenario complete the following steps. Start with a fresh un-edited copy of Little-Crab-3. When finished paste each of your class source code files into word and submit through Canvas.
1. Change the code to make the crabs turn left when the l (lowercase L) key is pressed. Make the crabs turn right when the r key is pressed.
public void act()
{
if(Greenfoot.isKeyDown("l"))
{
turn(-15);
}
if (Greenfoot.isKeyDown("r"))
{
turn(15);
}
}
2. Make changes to the code so that the worms will randomly move between 1 and 10 each time act is pressed
public void act()
{
if( Greenfoot.getRandomNumber(1));
{
move(4);
}
if( Greenfoot.getRandomNumber(10));
}
Move(4);
}
3. Make changes to the code so that the worm will randomly eat lobsters 15% of the time (you may need to check if you are touching a Lobster first)
public void act()
{
if ( isAtEdge())
{
turn(17);
}
if( Greenfoot.getRandomNumber(100)<15 )
{
turn(4);
}
move(5);
}
4. Create a method named mover that has an integer parameter named distance, and no return type. This method causes the crab to move the value of the distance parameter.
public void act()
{ randomMove();
}
void randomMove()
{
move(Greenfoot.getRandomNumber(15);
}
5. Add code that will cause the crab to turn 17 if the q button is pressed
public void act()
{
turnCrab();
}
void turnCrab()
{
if(Greenfoot.isKeyDown("q"))
{
turn(17);
}
}
6. Add code that will cause the crab to turn -17 if they w button is pressed
public void act()
{
turnCrab();
}
void turnCrab()
{
if(Greenfoot.isKeyDown("w"))
{
turn(-17);
}
}
I am working on this assignment - Is there anyone who can help me check my answer - I think I am making some mistakes - correct me with explanation please
Answering the first Question i.e. 1:
Modified Code:
public void act()
{
if(Greenfoot.isKeyDown("l"))
{
turn(-15);
}
if (Greenfoot.isKeyDown("r"))
{
turn(15);
}
}
Reason:
1. This code is correct.
2. Here, when the l (lowercase L) key is pressed, a left turn is made using turn(-15).
3. Here, when the r key is pressed, a right turn is made using turn(15).
4. To judge the key pressing action, code use Greenfoot.isKeyDown() function