Advanced Python Development Course
Chapter
>
Level
Generators
Manually advancing a Generator
Objective
Use generator in a manual sequence to put together and produce materials to make bread.
Ahead there is a facility where you can put together some bread dough using the presses. Normally you would use the combine() function to put together materials but this is not the case here, the materials need to be refined first before they can be put together.
For this task we can use generators as they can be customized to output different file types as well as have their sequence be called on command rather than automatically output like functions and loops do. Here is an example:
def bread():
yield 5
yield "grain"
The above code has a generator with two yield statements, one of which produces a real number and another a string. We can produce the values of the generator at will using the next() function. Like this:
recipe = bread() # Sets up Generator player.place(next(recipe)) # First value is called player.collect(next(recipe)) # Second value is called
In the example above, the generator is set up and the next() function is used with the generator to call the first yield value for use in a place() function. This is repeated with the second value but is instead used in a collect() function. This makes it easy to call values of various types in a sequence without having to use multiple lists or variables.
A generator named bread() will be defined in the code editor but it will require amount numbers for each ingredient in order for you to refine the bread dough. These numbers are written in the sign next to the facility. Set up the generator for use by referencing it, like this: recipe = bread()
First walk to the light X mark next to the milk tank and collect() the last of the milk in the tank using the generator next() function, like this: player.collect(next(recipe)). Then walk to the gold X mark next to the sign and use the speak() function to get the amount numbers needed for the generator to produce the bread and write them down in the generator. The data is stored in a constant named "sign" and would be called like this: player.speak(sign).
Once all values are entered in the generator, go into the facility and use player.place(next(recipe)) on dark X marks and player.collect(next(recipe)) on light X marks in order to complete the level.