Movement

Game objective

  • Move your character around the board

Coding skills

  • Import modules
  • Function calls
  • Random Number Generator (RNG)

One step at a time

In this game, we use the four cardinal directions: "north", "south", "east", and "west". This line will tell your character to move one step to the east:

Python

game.execute("move", {"direction": "east"})

Java

game.execute("move direction:east");

Move character with a for loop

Like I mentioned, game.execute("move direction:east") will move your character by one step. What if you want to move five steps? Typing this would be inefficient:

game.execute("move", {"direction": "east"})
game.execute("move", {"direction": "east"})
game.execute("move", {"direction": "east"})
game.execute("move", {"direction": "east"})
game.execute("move", {"direction": "east"})

Don't even try to use this:

game.execute("move", {"direction": "east"}) * 5

Instead, we can use a for loop:

Python

for x in range(1, 5):
  game.execute("move", {"direction": "east"})

Java

for (int i = 0; i < 5; i++) {
  game.execute("move direction:east");
}

How does a for loop work? The heading, for x in range(1, 5), tells the computer to start at x = 1 and work its way to x = 5, increasing x by 1 each time the code inside runs. The colon, :, at the end of the heading indicates that every indented line following are inside the for loop. Don't forget, indentation is important in Python!

Move randomly

Suppose your character were to suddenly acquire an indecisive personality. Let's make him/her move spontaneously.

Python

import random   #lets you access all the functions in the "random" module

for x in range(1, 50):   #repeat 50 times
  #choose a random direction
  dir = random.choice("east", "west", "north", "south")
  game.execute("move", {"direction": dir})

Java

Random rand = new Random();
String[] directions = {"east", "west", "north", "south"};

for (int i = 0; i < 5; i++) {
  int n = rand.nextInt(4);
  game.execute("move direction:" + directions[n]);
}

Coding Ideas

Here are some ideas for coding practice that you can try out:

  1. (Easy) Build a bot to walk straight lines up/down or left/right
  2. (Medium) Build a bot that can cover the whole map
  3. (Medium) Build a bot that only walks along the borders.
  4. (Medium) Build a bot that can walk diagonally
  5. (Difficult) Build a bot that walks along an outward spiral path.

results matching ""

    No results matching ""