Python Development Course
Chapter
>
Level
Using Dictionaries
Custom functions using dictionaries
Objective
Use a custom function that loops through the field, planting and watering crops.
The field has several trees that need planting, grab the bag containing seeds then refill your water by the well. Use a custom function with a dictionary to loop through the field, and plant then water the seeds.
Grab the bag of seeds which will grant you the following tree seeds in a dictionary: "orange : 3" , "pear : 4" , "apple : 3" , "peach : 2" . Walk to the light X mark next to the well and use the collect() function to gather water, like this: player.collect("water") .
Once you collect all necessary materials, create a custom function named sow_field using the seeds and water to plant and irrigate the field. The custom function will take three (3) arguments, those being: tree , loops and direction . Using these arguments the custom function will perform a for loop to irrigate the field.
def sow_field(tree,loops,direction):
for x in range(loops):
if direction == "right":
player.move_forward(2)
player.turn_left()
player.plant(seeds,tree)
player.water()
player.turn_right()
player.move_forward()
if direction == "left":
player.move_forward()
player.turn_right()
player.plant(seeds,tree)
player.water()
player.turn_left()
player.move_forward(2)
The first argument, tree is the name of the key used in the dictionary, those being "orange" , "pear" , "apple" and "peach" . Select the appropriate name when planting.
The next argument is loops and this determines the number of cycles you wish for the function to loop for. This is equal to the number of seeds of each type in the field. The last argument is direction, those being "left" and "right" , choose which direction you would like the player to move towards when looping the function.
Head to the upper most part of the map after collecting the water and use the custom function, like this: sow_field("orange", 3, "right") . Do this for all tree seeds in order to complete the level.