Lesson 6
Dealing with Sequences of Objects
Chapter 6: An army of robots
Automatically naming your robot
Now, it’s time to enhance your robot project again.
So far, you have a lonely robot navigating to its favourite Ribena drink at grid cell (9, 9).
Let us try to populate more robots into your robot world so that your robot will not be too lonely!
Before we do that, let us prepare your code and modify a few things first to make it easier to add multiple robots.
Firstly, instead of prompting the user to manually input the robot’s name, modify your program so that it generates a name for a robot at random from a list of pre-defined robot names. Hopefully this step will be easy since your code has been neatly refactored!
Create a text file in your robot directory and name it robot_names.txt
. Type in some names for the robot into the file, one name per line.
Now, update your program so that it generates a robot’s name by picking a name at random from your list of pre-defined names in robot_names.txt
. You can generate either a random integer to use as your index, or use random.choice()
to select a random item from a list.
Add robot_names.txt
to your repo, and commit your changes to both files as usual once you are done!
Sample run
Hello. My name is Wall-E. My ID is 1000.
I am currently at (0, 4), facing East.
Moving one step forward.
I am currently at (0, 5), facing East.
Moving one step forward.
I am currently at (0, 6), facing East.
Moving one step forward.
I am currently at (0, 7), facing East.
Moving one step forward.
I am currently at (0, 8), facing East.
Moving one step forward.
I am currently at (0, 9), facing East.
I have a wall in front of me!
Turning 90 degrees clockwise.
I am currently at (0, 9), facing South.
Moving one step forward.
I am currently at (1, 9), facing South.
Moving one step forward.
I am currently at (2, 9), facing South.
Moving one step forward.
I am currently at (3, 9), facing South.
Moving one step forward.
I am currently at (4, 9), facing South.
Moving one step forward.
I am currently at (5, 9), facing South.
Moving one step forward.
I am currently at (6, 9), facing South.
Moving one step forward.
I am currently at (7, 9), facing South.
Moving one step forward.
I am currently at (8, 9), facing South.
Moving one step forward.
I am currently at (9, 9), facing South.
I am drinking Ribena! I am happy!