Program branches using If and Else. Python and Minecraft
In previous lessons, we learned how to ask questions in Python. Also, we learned how to use the comparison operator in the code ("equal", "not equal", "more", "less", etc.) and logical operations (and, or, not) to find out whether those or Other conditions or sets of conditions - that is, they return True or False.
In this lesson we will discuss how to teach a program to choose a particular code based on the result of such tests.
Playing Minecraft, you often make decisions depending on different conditions. Is it night now?
To teach your program, use the special construction of Python if. It determines whether to execute the specified code fragment, while the program understands it as follows: "If this condition is met, you need to run the following code".
With the if construct, you can create your own mini-games in the world of Minecraft
Example 1.
age = int (input ("How old are you:"))
if years = 18: print ("You're already an adult!")
Example 2.
password = int (input ("Enter password:"))
if age = 1235: print ("That's right!")
else: print ("Password incorrect!")
The else construct works in conjunction with if. First you write the if statement that runs the code snippet if the condition returns True, and then add else so that the program can execute another code fragment if the condition returns False. The computer understands this as follows: "If the condition is met, you need to do one thing, and if not, another".
Example 3.
password = input ("Create magma? Yes / No")
if password == "Yes":
pos = mc.player.getPos ()
mc.setBlocks (pos.x + 1, pos.y-1, pos.z + 1, pos.x-1, pos.y-1, pos.z-1,213)
mc.postToChat ("Babah")
else: mc.postToChat ("Magma was not created")
The program uses the input () function to ask the user whether to create a magma.
The last argument to the setBlocks () function must be the block type of the future cuboid. In this case it is 213 - "magma".
Adding and subtracting 1 from the values pos.x, pos.y and pos.z, you specify the size of the cuboid 3 by 3 blocks.
After making changes to the program, save it and run it. In the window of the IDLE program a query will appear: "Create a magma? D / H." Enter the capital letter "D" (yes) or "H" (none). When you enter "D", the program must create a magma