6
MAKING MINI-GAMES WITH IF STATEMENTS

image

In Chapter 5, you learned how to ask questions in Python. You used comparison operators (like ==, !=, >, <, and so on) and logical operators (and, or, not) to find out whether a condition or set of conditions evaluated to True or False. In this chapter, you’ll use the answers to these questions—the results of the conditions you test—to decide what code to run.

You make decisions based on conditions every day. Is it nighttime? If so, you wear your diamond armor and bring a sword to fight off monsters. If not, you might leave all your gear in your secret base. Are you hungry? If that’s true, you eat some bread or an apple. If not, you might go off on a grand adventure to work up an appetite. Just as you make decisions in everyday life, your programs need to do different tasks depending on a condition.

We’ll use a bit of Python code to help your programs make decisions. if statements tell your program whether or not to run a particular piece of code. An if statement means “If this condition is true, run this code.” For example, you could check whether the player is standing in a forbidden room and turn the floor to lava if they are. Or, you could check whether they placed a certain block at a certain location and open a hidden door if they did. Using conditions and if statements, you can begin to make your own mini-games in Minecraft.

USING IF STATEMENTS

Being able to control the execution of your program is a very powerful ability; in fact, it’s crucial to coding! Programmers sometimes call this concept flow control. The easiest way to add this kind of control is by using the simple if statement, which runs code when a condition is True.

An if statement has three parts:

• The if operator

• A condition to test

• A body of code to run if the condition is True

Let’s look at an if statement in action. The following code will print "That's a lot of zombies." only if there are more than 20 zombies. Otherwise, it won’t do anything.

zombies = int(input("Enter the number of zombies: "))
if zombies > 20:
    print("That's a lot of zombies.")

Here, zombies > 20 is the condition we’re testing, and print("That's a lot of zombies.") is the body of the if statement; it’s the code that runs if zombies > 20 is True. The colon (:) at the end of the if line tells Python that the next line will start the body of the if statement. The indentation tells Python which lines of code make up this body. Indentation means there is extra space at the beginning of a line of text. In Python you indent lines by four spaces. If we wanted to add more lines of code to run inside the if statement, we would put the same number of spaces in front of all of them, indenting them just like print("That's a lot of zombies.").

Try running this code a few times, testing each condition, and see what happens. For example, try entering a number that is less than 20, the number 20, and a number that is greater than 20. Here is what happens if you enter 22:

Enter the number of zombies: 22
That's a lot of zombies.

Okay, the result makes sense. Let’s run it another time and see what happens when the condition isn’t met.

Enter the number of zombies: 5

Notice that nothing happens if the condition is False. The body of the if statement is entirely ignored. An if statement will execute the code in its body only if the condition is True. When the if statement is finished, the program continues on the line after the if statement.

Let’s look at another example to better understand how this works. The following code uses an if statement to check whether a password is correct:

password = "cats"
attempt = input("Please enter the password: ")
if attempt == password:
    print("Password is correct")
print("Program finished")

The expression after the if statement is the condition: attempt == password. The indented line after if attempt == password: is the if statement’s body: print("Password is correct").

The code will print "Password is correct" only if the value stored in the attempt variable is the same as the value in the password variable. If they are not the same, it will not print anything. The last line will run and print "Program finished" whether or not the body of the if statement runs.

Now let’s try something a little more explosive.

MISSION #26: BLAST A CRATER

You’ve already learned how to make the player teleport and jump high. Now you’ll make the blocks around the player disappear.

When the program runs, the blocks above, below, and around the player will turn into air. This power is very destructive, so be careful when you use it. To be safe, the program will ask the user whether they are sure they want to destroy the blocks, and it will only do so if the user’s answer is yes.

Listing 6-1 creates a crater around the player by deleting all the blocks above, below, and around them. Then it posts "Boom!" to chat. Save this program as crater.py in a new folder called ifStatements.

crater.py

   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()

   answer = input("Create a crater? Y/N ")

# Add an if statement here

   pos = mc.player.getPos()
mc.setBlocks(pos.x + 1, pos.y + 1, pos.z + 1, pos.x - 1, pos.y - 1, pos.z - 1, 0)
   mc.postToChat("Boom!")

Listing 6-1: This code creates a crater, no matter what the user enters.

The answer variable uses the input() function to ask the user whether they want to create a crater. At the moment, however, the code will create a crater no matter what the user enters—Y, N, something else, or nothing.

To complete this program, you’ll need to add an if statement to check whether the user has input Y in response to the question. You can add that logic to the game at . Remember that the user’s response is stored in the answer variable, so your if statement should check the answer variable. After you add your if statement, the program should only run the last three lines of code when the player inputs Y. To do this, you must indent these lines by four spaces.

Keep in mind that the very last argument of the setBlocks() function should be the block type you want to set. Here, the last argument is 0, the block type for air. In other words, the crater is created using setBlocks() to set the blocks to air , making it look like all the blocks around the player have been destroyed. By adding and subtracting 1 to the values of pos.x, pos.y, and pos.z, the code places air blocks around the player’s position as a 3 by 3 cube. This is the crater.

After you’ve made the changes to the program, save it and run it. The question Create a Crater? Y/N will appear in the Python shell. Enter either Y or N. Make sure the Y is a capital letter, or the program won’t work properly.

When the user enters Y, a crater will appear, as shown in Figure 6-1.

image

Figure 6-1: Boom! There’s a crater around me.

ELSE STATEMENTS

Now we’ll look at a more advanced statement to use if we want to run a different piece of code when the if condition is False. That’s where the else statement comes in.

An else statement works together with an if statement. First you write an if statement to run some code if the condition is True. After the if, you write an else statement to run other code when the condition evaluates to False. It’s like you’re saying, “If the condition is true, do this. Otherwise, do something else.”

The following program will print "Ahhhh! Zombies!" if more than 20 zombies are in a room; otherwise, it will print "You know, you zombies aren't so bad."

zombies = int(input("Enter the number of zombies: "))
if zombies > 20:
    print("Ahhhh! Zombies!")
else:
    print("You know, you zombies aren't so bad.")

Like the if statement, the else statement uses a colon and indentation to indicate which code belongs to the body of the else statement. But the else statement can’t be used by itself; an if must come before it. The else statement does not have its own condition; the body of the else statement runs only if the if statement’s condition (zombies > 20 in this example) is not True.

Going back to the earlier password example, we can add an else statement to print a message when the password is incorrect, like this:

password = "cats"
attempt = input("Please enter the password: ")
if attempt == password:
    print("Password is correct.")
else:
    print("Password is incorrect.")

When the value of attempt matches the value of password, the condition will be True. The program runs the code that prints "Password is correct."

When attempt does not match password, the condition will be False. The program runs the code that prints "Password is incorrect."

What if an else statement is used without an if statement? For example, if a program had just these two lines:

else:
    print("Nothing happened.")

Python wouldn’t understand what was going on, and you’d get an error.

MISSION #27: PREVENT SMASHING, OR NOT

In Mission #17 (page 82), you made a program that stopped the player from smashing blocks by making the world immutable using mc.setting("world_immutable", True). The program helped you protect your precious creations from accidents or vandals. But even though it was useful, the program wasn’t very flexible. Turning it off required a second program, which is pretty inconvenient!

Using an if statement, an else statement, and console input, you can make a program that turns immutable on and off. Your program will ask whether you want the blocks to be immutable and then set immutable to True or False depending on your response.

Open IDLE and create a new file. Save the file as immutableChoice.py in the ifStatements folder. Follow these instructions to complete the program:

  1. The program needs to ask the user whether they want to make the blocks immutable:

    "Do you want blocks to be immutable? Y/N"

    Add this string as an argument inside input() and store the input in a variable called answer.

  2. The program checks whether the value stored in the answer variable is "Y". If it is, it runs the following code:

    mc.setting("world_immutable", True)
    mc.postToChat("World is immutable")

    Copy this code and put it in an if statement so it runs only if the value of the answer variable is equal to "Y". Don’t forget to indent!

  3. The program runs the following code if the answer variable is not "Y".

    mc.setting("world_immutable", False)
    mc.postToChat("World is mutable")

    Copy this code and put it in an indented else statement.

Save and run the program. When it asks whether or not you want to make the blocks immutable, type Y or N and press ENTER. Test the program. When you choose to make blocks immutable, they shouldn’t break; otherwise, they should be breakable.

Figure 6-2 shows the output message and question in the shell.

You’ll get the same result if you enter "N" as you will if you enter nonsensical input like "banana". Why do you think this happens?

image

Figure 6-2: I can choose to make the world immutable, and now I can’t destroy any of the blocks.

ELIF STATEMENTS

Using an if statement and an else statement, your program was able to run some code if a condition was True and different code if the condition was False. But what if you want more than two blocks of code to run?

To do this, you can use an else-if statement, or elif in Python. First you write an if statement, then you write an elif statement, and then you write an else statement. When you use these statements together, you’re saying, “If a condition is True, run this code. Otherwise, if a second, different condition is True, run some other code. Finally, if neither of those two conditions is True, run some other code.”

Let’s take a look at it. Say you’re deciding what flavor to buy at the ice cream shop. You might say, “If there’s any chocolate ice cream left, I’ll get that. If there isn’t chocolate, but there’s strawberry, I’ll get strawberry. If there isn’t chocolate or strawberry, I’ll get vanilla.”

In a program, this decision process looks like this:

hasChocolate = False
hasStrawberry = True
if hasChocolate:
    print("Hooray! I'm getting chocolate.")
elif hasStrawberry:
    print("I'm getting the second best flavor, strawberry.")
else:
    print("Vanilla is OK too, I guess.")

The first two lines just set the stage for the scenario: we’ll assume that today, the ice cream shop doesn’t have any chocolate left but does have strawberry. So we set hasChocolate to False and hasStrawberry to True.

Next is the logic of the decision process: an if statement prints "Hooray! I'm getting chocolate." if hasChocolate is True. But in this example, it’s False, so that message isn’t printed. Instead, the program goes on to the elif statement and tests whether hasStrawberry is True. Because it is, the code in the body of the elif statement runs and prints "I'm getting the second best flavor, strawberry."

As you can see, this elif statement has its own condition and body. The elif statement executes only when the condition of the if statement is False and the condition of the elif statement is True.

Finally, the else statement after the elif statement executes when the if statement’s condition is False and the elif statement’s condition is also False. In this example, the else statement’s code would run if both hasChocolate and hasStrawberry were False, printing "Vanilla is OK too, I guess."

For another example, let’s go back to the program that printed "Ahhhh! Zombies!" if more than 20 zombies were in a room. We can add an elif statement to test another condition when the if statement’s condition is False:

zombies = int(input("Enter the number of zombies: "))
if zombies > 20:
    print("Ahhhh! Zombies!")
elif zombies == 0:
    print("No zombies here! Phew!")
else:
    print("You know, you zombies aren't so bad.")

We add an elif statement to compare zombies and 0. If zombies == 0 is True, the code in the elif statement’s body prints "No zombies here! Phew!" If this elif statement’s condition is False, the code moves on to the else statement and prints "You know, you zombies aren't so bad."

MISSION #28: OFFER A GIFT

Let’s create a program that checks whether a certain block has a gift placed on it and outputs different responses to chat depending on what the gift is.

The program will allow you to place one of two different gifts. One gift is a diamond block, and because not everyone has that many diamond blocks, the other is a tree sapling.

Listing 6-2 checks whether a block at position 10, 11, 12 is a diamond block or a tree sapling or if there’s no gift. However, the program is not complete.

gift.py

   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()
   x = 10
   y = 11
   z = 12
   gift = mc.getBlock(x, y, z)

   # if gift is a diamond block
if

   # else if gift is a sapling
elif

   else:
       mc.postToChat("Bring a gift to " + str(x) + ", " + str(y) + ", " + str(z))

Listing 6-2: The start of the code that checks whether you’ve delivered a gift

Create a new file in IDLE and save it as gift.py in the ifStatements folder. Copy Listing 6-2 into the file. The code that gets the block type has been done for you. The block type is stored in the gift variable. The else statement will run if neither a diamond block nor a tree sapling has been placed, and it will post a message to chat instructing the player to bring a gift to these coordinates. You can change the coordinates in the x, y, and z variables to any location you like.

To complete the program, follow these steps:

  1. Complete the if statement at so it checks whether the gift variable contains the value for a diamond block (57). If it does, make it post this message to chat: "Thanks for the diamond."

  2. Add an elif statement under the second comment at that checks whether the gift variable contains the value for a tree sapling (6). If it does, make it post this message to chat: "I guess tree saplings are as good as diamonds..."

After making the changes, save and run the program. Try putting a diamond block at the coordinates and see what happens. Do the same with a tree sapling, and also try leaving nothing at the coordinates. Don’t forget that the sapling needs to be planted in a dirt or grass block! Do you get the correct response in each situation? You’ll need to rerun the program each time to check that it works. Figure 6-3 shows my working program.

image

Figure 6-3: I’ve placed a tree sapling as a gift.

CHAINING TOGETHER ELIF STATEMENTS

There is no limit to the number of elif statements that you can include with an if statement. You can have one elif statement or 100 elif statements. Python just evaluates them one after the other.

Here’s an example using the “number of zombies” program:

   zombies = int(input("Enter the number of zombies: "))
   if zombies > 20:
       print("Ahhhh! Zombies!")
elif zombies > 10:
       print("There's just half a Minecraft zombie apocalypse.")
   elif zombies == 0:
       print("No zombies here! Phew!")
   else:
       print("You know, you zombies aren't so bad.")

Here we’ve added a new elif statement at , right after the if statement, to check if more than 10 zombies are in the room. If there are, it prints "There's just half a Minecraft zombie apocalypse."; otherwise, the code moves on to the next elif.

The order of the if and elif statements is very important. If you put them in the wrong order, some of the code may never be reached, and your program will not run as expected.

For example, if we swap the if statement’s condition with the first elif statement’s condition, we run into a problem:

zombies = int(input("Enter the number of zombies: "))
if zombies > 10:
    print("There's just half a Minecraft zombie apocalypse.")
elif zombies > 20:
    print("Ahhhh! Zombies!")
elif zombies == 0:
    print("No zombies here! Phew!")
else:
    print("You know, you zombies aren't so bad.")

Why is this wrong? Let’s look at what happens when zombies is, say, 22. Because 22 is greater than 10, the first if statement’s condition, zombies > 10, is True, and the if statement’s code runs. Once this happens, none of the other elif and else statements will run. The program never reaches elif zombies > 20 because it already ran the body of the if statement. This is a bug.

If you ever get unexpected results from your if statements, always double-check that your if and elif statements are in the correct order.

MISSION #29: TELEPORT TO THE RIGHT PLACE

When if and elif statements are in the wrong order, code you expect to run will not run, and code you don’t expect to run will run. This can cause weird bugs in your programs. To fix the program, you need to put the conditions in the right order. Let’s give this a try.

Listing 6-3 won’t work. It’s supposed to teleport the player to different locations depending on how many points the user enters. The points match up to the correct locations, but it looks like the conditions are not in the right order.

The more points a player has, the better the location. Here’s the code. The conditions are set using setPos() for each location transport.

teleportScore.py

from mcpi.minecraft import Minecraft
mc = Minecraft.create()

points = int(input("Enter your points: "))
if points > 2:
    mc.player.setPos(112, 10, 112)
elif points <= 2:
    mc.player.setPos(0, 12, 20)
elif points > 4:
    mc.player.setPos(60, 20, 32)
elif points > 6:
    mc.player.setPos(32, 18, -38)
else:
    mc.postToChat("I don't know what to do with that information.")

Listing 6-3: Depending on your points, you will teleport to a different location.

There’s a separate condition for greater than 6 points, greater than 4 points, greater than 2 points, and then 2 or fewer points.

The last line, inside the else statement, won’t run unless the user inputs something totally weird, like a string of text instead of their points, or enters nothing at all.

Create a new file in IDLE and save it as teleportScore.py in the ifStatements folder. Change the program so the conditions are in the correct order and all the locations can be reached. Test the program with different numbers of points to make sure the code for each teleport destination can run. Figure 6-4 shows the program not working.

image

Figure 6-4: I didn’t expect to end up here!

Because the program doesn’t work at the moment, when I enter 5, it teleports me to the location for more than 2 points, even though I should go to the location for more than 4 points.

NESTED IF STATEMENTS

Say you have an if statement, and if its condition is True, you want to test another condition (and run some code if this second condition is True). For example, if you’re trying to make the entrance to your home base extra secret, you might write some code that checks whether you’re standing on a switch. If that’s true, another line of code checks whether you’re holding the secret item that will unlock the door. How would you do that?

You can put one if statement inside the body of another if statement. This is known as a nested if statement.

Listing 6-4 is an example of a nested if statement. A simple cash machine checks whether you have enough money and then asks you to confirm your withdrawal if you do. If you confirm, the program performs the withdrawal.

   withdraw = int(input("How much do you want to withdraw? "))
   balance = 1000

if balance >= withdraw:
       confirm = input("Are you sure? ")
     if confirm == "Yes":
           print("Here is your money.")
   else:
       print("Sorry, you don't have enough money.")

Listing 6-4: An imaginary cash machine written with Python

Notice that the second if statement is indented inside the first if statement. If the outer if statement’s condition is True, you have enough money in your account, and the line confirm = input("Are you sure? ") runs. Then, if the inner if statement’s condition is True, the code prints "Here is your money."

MISSION #30: OPEN A SECRET PASSAGE

In this mission, you’ll expand on the previous example a bit. You’ll create a building with a secret passage that opens only when a diamond block is placed on a pedestal. When any other type of block is placed on the pedestal, the floor will turn to lava!

First, build a building. To do this quickly, find the building.py program (page 56) in the math folder and run it. Don’t add a door to the building. Outside, where you want to code the entrance to the building, place a single block to represent the pedestal. When you place a diamond block on top of the pedestal, the code will open a secret entrance in the side of the building. Listing 6-5 provides some skeleton code that you can use to get started.

secretDoor.py

from mcpi.minecraft import Minecraft
mc = Minecraft.create()

x = 10
y = 11
z = 12
gift = mc.getBlock(x, y, z)
if gift != 0:
    # Add your code here
else:
    mc.postToChat("Place an offering on the pedestal.")

Listing 6-5: The start of the code to open a secret door when you place a gift on a pedestal

Create a new file in IDLE and save it as secretDoor.py in the ifStatements folder. Change the coordinates in this program to match the location where your diamond block key will need to be placed in your Minecraft world.

Copy Listing 6-5 and add code for these tasks:

• If a diamond block (57) is on the pedestal, open a secret passage to the secret room. (Hint: To create an opening in the building, try setting the blocks to air.)

• When a block that is not diamond is on the pedestal, make the floor under the player turn to lava (10).

You’ll need to use a nested if statement to complete this program.

Because this is a more complex program, you should build and test it in stages. When you’ve added a feature, run the program and make sure that part works before moving on. Debugging small code pieces is easier than fixing lengthy code pieces. Figure 6-5 shows the secret passage opening.

image

Figure 6-5: The secret passage to the temple is now open.

USING IF STATEMENTS TO TEST A RANGE OF VALUES

As you learned in Chapter 5, you can determine whether one value is between two other values in Python. Because a range check evaluates to True or False, you can use a range check as the condition in an if statement, just like you’d use a simple less than/greater than or equal to/not equal to comparison. Any expression that evaluates to True or False can be a condition of an if statement.

Say you’ve spent all day gathering ingredients to bake some delicious Minecraft cakes. You find enough ingredients to bake 30 cakes, and now you want to sell the cakes. The person buying cakes from you must buy 1 cake but less than 30; otherwise, you won’t sell cakes to that person. They can’t hog all the cakes!

This code represents the cake situation:

   cakes = int(input("Enter the number of cakes to buy: "))
if 0 < cakes < 30:
       print("Here are your " + str(cakes) + " cakes.")
elif cakes == 0:
       print("Don't you want some delicious cake?")
else:
       print("That's too many cakes! Don't be selfish!")

If the cakes variable has a value between 0 and 30, such as 15, we print "Here are your 15 cakes." . Otherwise, we print a different message. If cakes has a value of 0, we print "Don't you want some delicious cake?" and if it’s greater than 30, we print "That's too many cakes! Don't be selfish!" .

We can test a more complicated expression by adding a Boolean operator. If I was really weird and didn’t want people to buy a quantity of bread between 20 and 30, I could do this using the not operator:

bread = int(input("Enter the amount of bread: "))
if not 20 <= bread <= 30:
    print("Here are your " + bread + " breads.")
else:
    print("I don't sell that amount of bread for some reason.")

Here I use a not operator and the greater than or equal to comparisons to test a range of values as the first condition. The range check determines whether the amount of bread people want to buy is between 20 and 30. Then, the not flips a True to False and a False to True. So if bread is in the range, the overall expression evaluates to False, and we run the code in the else statement. If bread is not in the range between 20 and 30—say it’s 40—the overall expression is True, and we print "Here are your 40 breads."

If someone tries to buy 23 breads, I won’t let them. But 17 or 32 is just fine.

MISSION #31: RESTRICT TELEPORT LOCATIONS

Remember the teleport program you created back in Chapter 2? It was called teleport.py. In this mission, you’ll use range checks and if statements to limit where the player can teleport to. If you’re using Minecraft on the Raspberry Pi, there are places outside the game world that don’t exist, but your program will still let you teleport to them. If you’re using the desktop edition of Minecraft, your world is much bigger, so you don’t have the same restrictions as in the Pi edition of the game, but this program is still useful. For example, you could use it in a game of hide-and-seek to limit the area where players can hide.

Listing 6-6 is supposed to get the x-, y-, and z-coordinates from the user’s input and teleport them to that position. But the program isn’t complete.

teleportLimit.py

from mcpi.minecraft import Minecraft
mc = Minecraft.create()
valid = True

x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))

if not -127 < x < 127:
    valid = False

# check if y is not between -63 and 63

# check if z is not between -127 and 127

if valid:
    mc.player.setPos(x, y, z)
else:
    mc.postToChat("Please enter a valid location")

Listing 6-6: A program to limit the locations that the player can teleport to

In order to restrict where the player can teleport to, we make a variable called valid. This variable will store a True or a False to represent whether or not all the coordinates in the destination are valid. We ask the user to input values for x, y, and z. Then we have an if statement check whether the x variable is not between –127 and 127. If it’s not, this x-coordinate is invalid, and the valid variable is set to False.

When the program reaches the final if statement, setPos() will be called only if valid is True. And valid will be True only if all three conditions have been met. Otherwise, the player doesn’t get to teleport, and we post a chat message telling the user to enter a valid location.

Create a new file in IDLE and copy Listing 6-6 into it. Save the program as teleportLimit.py in the ifStatements folder.

Complete the program so it uses if statements and range checks on the y and z variables and sets valid to False if the values are not valid.

When you think you’ve finished the program, run it. The program should teleport you when you enter values that are within the –127 to 127 range for the x and z variables and within the –63 to 63 range for the y variable. When you enter a value that isn’t in these ranges, the program shouldn’t teleport you. Figure 6-6 shows how the game should look when the user enters an invalid number.

image

Figure 6-6: The z variable was too big, so I didn’t teleport.

BOOLEAN OPERATORS AND IF STATEMENTS

In the previous mission, you used not in your if statements. You can also use and and or. In this case, the if statement will act just like it did with one simple condition: if the overall expression evaluates to True, the body of the statement will run. Here’s a program that asks someone if they have cake and whether they want to give us some cake:

hasCake = input("Do you have any cake? Y/N")
wouldShare = input("Would you give me some cake? Y/N")

if hasCake == "Y" and wouldShare == "Y":
    print("Yay!")
else:
    print("Boo!")

This code uses the and operator, so Python will only print "Yay!" if the person has cake (hasCake == "Y" is True) and is willing to share it (wouldShare == "Y" is True). If either of these comparisons is not True, the code inside the else statement will print "Boo!"

You can replace and with the or operator to make Python print "Yay!" if the person either has cake or would be willing to share it:

hasCake = input("Do you have any cake? Y/N")
wouldShare = input("Would you give me some cake? Y/N")

if hasCake == "Y" or wouldShare == "Y":
    print("Yay!")
else:
    print("Boo!")

If either hasCake == "Y" or wouldShare == "Y" is True, the whole expression evaluates to True, and we print "Yay!" The only time we print "Boo!" is if neither condition is True: the person doesn’t have cake and wouldn’t share it if they did.

Let’s try using the not operator with an if statement:

wearingShoes = input("Are you wearing shoes? Y/N")
if not wearingShoes == "Y":
    print("You're not wearing shoes.")

This program asks the user to enter Y if they are wearing shoes and N if they aren’t. It stores the input in wearingShoes. Next is a comparison between wearingShoes and "Y" to see whether they’re equal. The not operator reverses the result of a comparison—True becomes False and False becomes True—so if the user entered Y, the comparison starts off True and not makes it False, making the overall expression False. We don’t print a message. If the user didn’t enter Y, the comparison is False and not makes it True. The overall expression evaluates to True, and we print "You're not wearing shoes."

MISSION #32: TAKE A SHOWER

The best Minecraft houses have a lot of attention to detail. Many people include wooden flooring, fireplaces, and pictures in their houses to make them feel more like home. You’ll go one step further and make a working shower.

To get the shower to work, you need to use range checks and Boolean operators. You’ll create a shower area, and when the player walks into the shower, the water will switch on. In other words, when the player walks within a range of coordinates, the program should create water blocks above them.

Listing 6-7 provides the basic structure of the program with a few lines of code to help you get started. It’s your job to fill in the rest.

shower.py

   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()

shwrX =
   shwrY =
   shwrZ =

width = 5
   height = 5
   length = 5

   pos = mc.player.getTilePos()
   x = pos.x
   y = pos.y
   z = pos.z

if shwrX <= x < shwrX + width and
       mc.setBlocks(shwrX, shwrY + height, shwrZ,
                    shwrX + width, shwrY + height, shwrZ + length, 8)
   else:
       mc.setBlocks(shwrX, shwrY + height, shwrZ,
                  shwrX + width, shwrY + height, shwrZ + length, 0)

Listing 6-7: The start of the shower program

Copy Listing 6-7 and save it as shower.py in the ifStatements folder.

To finish the program, add the coordinates for your shower in the shwrX, shwrY, and shwrZ variables . Next, add the size of the shower in the width, height, and length variables . I’ve included a default value of 5, but you should change this to make your shower the size you want it to be.

Finish the if statement so it checks whether the y and z variables are within the shower area . I’ve included the check for the x position to help you out (shwrX < x < shwrX + width). The expressions for the y and z positions are similar to this. Hint: You’ll want to combine all these checks using and.

The shower is switched on and off using the setBlocks() function . The blocks are set to water (block ID 8) to switch on the shower and air (block ID 0) to switch off the shower.

The setBlocks() functions in the last if/else statement are broken across two lines because their arguments are very long. Python allows you to do this. They could be written on a single line; I wrote them on two lines just to make them easier to read.

Figure 6-7 shows my shower working.

image

Figure 6-7: Here I am, having a shower.

When you run the program, it will create water above you if you’re standing in the shower. The water will not stop until you leave the shower and run the program again. Have fun!

WHAT YOU LEARNED

Your programs can now make decisions. In this chapter, you learned how to use conditions with if statements, else statements, and elif statements. In Chapter 7, you’ll learn about while loops. Like if statements, while loops help your program decide what to do and when. But unlike if and else statements—which you use to run some code if a condition is true and different code if it’s not true—while loops run code while a condition is true and keep running it repeatedly until the condition becomes false.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.114.125