ES2015 Lesson 4: Classes – Solutions


Exercise 1. Create a PlayerCharacter and a NonPlayerCharacter with a common ancestor Character. The characters are located in a 10×10 game field. All characters appear at a random location. Create the three classes, and make sure you can query where each character is.


This exercise has many solutions. We will stick to just one.

For the sake of simplicity, we will choose not to model the game field. We will place x and y inside the character objects as coordinates.

At this stage, there is no difference between player and non-player characters. We still created them to match the requirements.

Example execution:

Exercise 2. Each character has a direction (up, down, left, right). Player characters initially go right, and their direction can be changed using the faceUp, faceDown, faceLeft, faceRight methods. Non-player characters move randomly. A move is automatically taken every 5 seconds in real time. Right after the synchronized moves, each character console logs its position. The player character can only influence the direction he is facing. When a player meets a non-player character, the non-player character is eliminated from the game, and the player’s score is increased by 1.


We will model the direction of each character with the dx and dy variables, describing the change in coordinates during one step. For instance, if the character faces upwards, dx is 0, and dy is -1.

The specification allows non-player characters to occupy the same position.

Feel free to play around with the game in the console. If you want to test that updating the score works, you have a 50% chance of catching a wumpus by executing the following sequence:

Exercise 3. Make sure the Character class cannot be instantiated.

Solution: Place the following lines in the constructor of the Character class.