Attack and Retreat


Collapse Content

Sometimes, retreating is the only way to move forward...

This challenge uses enum types, which are used to specify specific constants, such as RIGHT or LEFT. You can see how they're used below.

Direction

If explorer is under attack, it may need to move back to recharge. You can do this by passing a Direction to the walk method. There are 2 directions:

  • Direction.RIGHT to go forward
  • Direction.LEFT to move backwards.

explorer defaults to Direction.RIGHT if no parameter is passed. For example:

explorer.walk();                 //explorer walks forward
explorer.walk(Direction.LEFT);  //explorer walks backward
Direction direct = Direction.RIGHT; //set the direct paramter
explorer.walk(direct);             //explorer walks forward again

The board now consists of 10 Spaces, with a Wall in the first and last Space. You can use the method isWall() to check if a Space contains a Wall.

More on Enum

Sometimes, your code will deal with a small group of values, such as directions or days of the week. Instead of using Strings or integers to represent their values, you should Enum types. Enums are special classes that define a set of constants. Using a specified set of constants can help prevent errors in your code. For example, this is the Direction enum:

enum Direction {
    LEFT, RIGHT
}

There allows the rest of the code to use two directions:

Direction.LEFT
Direction.RIGHT

API

Explorer Methods

Mutators:

  • walk() - Moves the explorer forward (to the right) one Space. It can also take one Direction parameter, either Direction.RIGHT or Direction.LEFT.
  • poke() - Pokes the next space, causing damage to any Enemy there.
  • recharge() - Adds 9 to health.

Accessors:

  • getSpace() - Returns the next Space on the board.
  • getHealth() - returns the value of health.

Space methods

  • isEnemy() - returns true if the Space contains an Enemy, and false otherwise.
  • isWall() - returns true if the Space contains a Wall, and false otherwise.

Challenge

Out-maneuver the Archers and reach the Goal!

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • I keep getting

    Main.java:519: error: incompatible types: Player.Direction cannot be converted to Direction
    explorer.walk(Direction.LEFT);

    But I added the enum Direction{ LEFT, RIGHT} like it says in the explanation.

    What can I do here?

  • Note that the enum is already included with code that is attached your code. So you do not need to declare the enum yourself and can just use it inside your code. (You should just fill in the class Player.)

Contact Us
Sign in or email us at [email protected]