5
FIGURING OUT WHAT’S TRUE AND FALSE WITH BOOLEANS

image

You ask yes-or-no questions all the time: Is it raining? Is my hair too long? Once you know whether the answer is yes or no, you can decide what to do next: bring an umbrella, or not; trim your hair, or not. In all these situations, what you do depends on whether the answer to the question is yes or no. Deciding what to do based on the answer to a question is also important in programming. In this chapter, you’ll learn how to ask questions in Python.

In programming, the questions you ask are usually about comparing values. Is one value equal to another? Is a value bigger or smaller than another? The yes-or-no question is called a condition, and the answer isn’t yes or no but True or False. Say you ask the question “Do I have more gold blocks than my friend?” or, in other words, “Is my gold stash greater than my friend’s gold stash?” To make that question into a condition that Python can understand, we have to phrase it as a statement (such as “My gold stash is greater than my friend’s”) that can be true or false.

Testing whether a condition is true or false is so useful in Python that there’s a special data type just for storing the values True and False. So far you’ve seen a few other data types: integer, float, and string data types. The data type that stores True and False values is the Boolean data type. Booleans can only be True or False. When you use Python to ask questions, the result is either True or False. When a condition is true or false, programmers say that it evaluates to True or evaluates to False.

In this chapter you’ll use Booleans, comparison operators, and logical operators to test different conditions involving values. Then you’ll be ready for Chapter 6, where you’ll use the answers to questions to make decisions about what to do next in a program.

BOOLEAN BASICS

A Boolean is a bit like a light switch: it is either True (on) or False (off). In Python, you can declare a Boolean variable like this to represent that the light is on:

light = True

Here you assign the value True to the variable light. To turn the light off, you could assign the value False to light:

light = False

Always capitalize the first letter of True and False. If you don’t, Python won’t recognize the value as a Boolean and will throw an exception instead of evaluating your calculation!

In the next mission, you’ll use Booleans to stop the player from smashing blocks in the game world.

MISSION #17: STOP SMASHING BLOCKS!

In Minecraft, it’s easy to smash blocks, which is great when you want to mine for resources. But it’s annoying to spend ages building a really cool structure and then accidentally smash and destroy it! In this mission, you’ll make your Minecraft world indestructible.

By using setting("world_immutable", True) you can make blocks immutable, which means they can’t be changed. The setting() line of code is a function like the setTilePos() and setPos() functions you’ve seen. Listing 5-1 shows how to make the world immutable.

immutableOn.py

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

mc.setting("world_immutable", True)

Listing 5-1: Code that stops blocks from being broken

The setting() function has options that you can set to True to turn them on. One of the options is "world_immutable". To turn a setting() option on, you write True after the name of the setting inside the parentheses.

Type Listing 5-1 into IDLE and save it as immutableOn.py in a new folder called booleans. When you run it, you shouldn’t be able to smash most blocks, as shown in Figure 5-1. But what happens when you do want to break blocks again? Copy your program into a new file and change it to allow the player to smash blocks. (Hint: Use a Boolean!) Save the new file as immutableOff.py in the booleans folder.

image

Figure 5-1: No matter how hard I try, the block won’t break!

CONCATENATING BOOLEANS

Like integers and floats, Booleans must be converted to strings before they can be concatenated. For example, you concatenate Booleans and strings when you want to output Booleans using the print() function. To do this, use the str() function:

>>> agree = True
>>> print("I agree: " + str(agree))
I agree: True

The agree variable stores a Boolean. It is converted to a string on the second line with str(agree), concatenated to the "I agree: " string, and printed.

COMPARATORS

You are very good at comparing values. You know that 5 is greater than 2, 8 and 8 are the same number, and 6 and 12 are not the same number. A computer is also good at comparing values; you just need to tell it exactly which kind of comparison you want by typing in a symbol called a comparator. For example, do you want it to check if one value is bigger than the other, or do you want it to check if it’s smaller?

Comparators (or comparison operators) in Python let you compare data. Python uses six comparators:

• Equal to (==)

• Not equal to (!=)

• Less than (<)

• Less than or equal to (<=)

• Greater than (>)

• Greater than or equal to (>=)

Each comparator returns a Boolean value (True or False) that states whether the condition has been met. Let’s look at these comparators and explore how to use them!

EQUAL TO

When you want to find out whether two values are the same, you can use the equal to comparator (==). When the values are the same, the comparison returns the Boolean value True. When the values are different, the comparison returns False.

For example, let’s assign the value of two variables and then use the equal to operator to compare them:

>>> length = 2
>>> width = 2
>>> length == width
True

The result is True because the values of the length and width variables are the same.

But if they are different, the result is False:

>>> length = 4
>>> width = 1
>>> length == width
False

You can use the equal to comparator on all variable types: strings, integers, floats, and Booleans.

Notice how I used == to compare length and width instead of =, which is used to set a variable. Python uses the == operator to tell the difference between a comparison (asking whether two values are equal) and setting a variable (making a variable equal some value). Try to remember this difference to avoid bugs in your code. Don’t worry; even I make the mistake of using = instead of == once in a while!

MISSION #18: AM I SWIMMING?

Now you’ll use comparators to make a program that states whether or not you’re standing in water. The results will be posted to Minecraft chat.

To find out the block type at certain coordinates, you’ll use the getBlock() function. This function takes coordinates as three arguments and returns the block type as an integer. For example:

blockType = mc.getBlock(10, 18, 13)

Here, I stored the result of mc.getBlock(10, 18, 13) in a variable called blockType. If the block type at coordinates (10, 18, 13) is melon (block value 103), the blockType variable will hold a value of 103.

Let’s put the getBlock() function to work. Listing 5-2 checks whether the player is standing on dry land.

swimming.py

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

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

blockType = mc.getBlock(x, y, z)
mc.postToChat(blockType == 0)

Listing 5-2: This code checks the block type where the player’s legs are.

Here, I get the three coordinates of the player’s position and pass those coordinates as arguments to getBlock(). I store the result of mc.getBlock(x, y, z) in blockType. The expression blockType == 0 checks whether the block is air; if it is air, you know you’re just standing somewhere in your Minecraft world, the expression is True, and True is posted to chat. If it’s not air, False is posted to chat, so you must be underwater or maybe drowning in sand!

Copy Listing 5-2 and save it as swimming.py in the Chapter 5 directory. Then change the code so it checks whether the player is standing in water (block type 9) and run it.

Try standing in water and running the program. Make sure that when the player is in water, the chat displays True. When the player isn’t in water, the chat should display False.

The output of the program should look like Figure 5-2.

NOTE

At this point, you will not be able to run this program continuously. You must run the program every time you want to check the block below the player. This applies to all the other missions in this chapter as well.

image

Figure 5-2: Although I can see that I am standing in water, Python kindly confirms this.

NOT EQUAL TO

The not equal to comparator is the opposite of the equal to comparator. Instead of checking whether two values are the same, it checks whether they are different. When the two values are different, the comparison evaluates to True. When they are the same, it evaluates to False.

Say you want to make sure that an object is a rectangle but not a square. Because a non-square rectangle has a different length and width, you could write a comparison to check that the length and width are not equal:

>>> width = 3
>>> length = 2
>>> width != length
True

The width != length expression asks whether the values of width and length are different.

The result of this comparison is True because the width variable and the length variable have different values.

But if these values are the same, the comparison returns False:

>>> width = 3
>>> length = 3
>>> width != length
False

The not equal to comparator also works with strings, integers, floats, and Booleans, just like the equal to comparator.

MISSION #19: AM I STANDING IN SOMETHING OTHER THAN AIR?

Let’s say you want to check whether you’re standing in something other than air, such as water, lava, dirt, gravel, or any other type of block. In Mission #18, you checked whether the block at your current position was air, and you worked out how to check whether you were standing in water. You could copy and paste the program many times, changing it slightly each time to check for lava, dirt, gravel, and so on, one by one. But that would be very boring. Instead, use the not equal to comparator to check whether you’re underground, trapped in sand, at the bottom of the ocean, or even drowning in lava!

Open the program from Mission #18 (swimming.py) and save it as notAir.py in the booleans folder. Delete the last line of the program and replace it with Listing 5-3.

notAir.py

notAir = blockType == 0
   mc.postToChat("The player is not standing in air: " + str(notAir))

Listing 5-3: Changes to the swimming program

The last line of this code will print whether you’re not standing in air. The result of the comparison is stored in the notAir variable . When the comparison evaluates to True, the value of the notAir variable will be True, and when the comparison evaluates to False, the value of the notAir variable will be False.

But the comparison on the first line isn’t quite right . It currently checks whether the blockType is equal to air using the equal to comparator (==). Instead it should check whether the blockType variable is not equal to air using the not equal to comparator (!=). Change the first line to use the not equal to comparator instead of the equal to comparator. This will check whether the block at the player’s current position is not equal to air.

When you run the program, make sure it works when you’re standing in air and when you’re underwater, in lava, in gravel, in sand, or teleported into the ground. The message posted to the chat when the condition is True is shown in Figure 5-3.

image

Figure 5-3: Just taking a nice, relaxing swim in some water, which is not air.

GREATER THAN AND LESS THAN

When you need to figure out whether one value is bigger than another, you use the greater than comparator. The greater than comparator will return True when the value on the left is greater than the value on the right. If the value on the left is less than or the same as the value on the right, the comparison will return False.

Say we have a minecart that can’t lift more than 99 blocks of obsidian. As long our minecart’s lifting limit is greater than the number of obsidian blocks it’s trying to lift, the blocks can be lifted:

>>> limit = 100
>>> obsidian = 99
>>> limit > obsidian
True

Brilliant! Our minecart can carry any number of obsidian blocks that is less than 100, and 99 is less than 100, so limit > obsidian evaluates to True. But what if someone adds another block of obsidian to the pile?

>>> limit = 100
>>> obsidian = 100
>>> canLift = limit > obsidian
False

Oh no, now the limit has been reached! The result is now False: 100 is not greater than 100; it’s the same. Our minecart can’t lift the obsidian.

The less than comparator works the same way.

A van driving under a bridge needs to know whether it’s small enough to fit under it:

>>> vanHeight = 8
>>> bridgeHeight = 12
>>> vanHeight < bridgeHeight
True

In this case, the van will fit because it’s smaller than the bridge height: 8 is less than 12. Later in its journey, the same van might encounter another bridge that is too low to drive under:

>>> vanHeight = 8
>>> bridgeHeight = 7
>>> vanHeight < bridgeHeight
False

Because 8 is not less than 7, the result is False.

GREATER THAN OR EQUAL TO AND LESS THAN OR EQUAL TO

Like the greater than comparator, the greater than or equal to comparator determines whether one value is greater than another. Unlike the greater than comparator, it will also evaluate to True if the values are the same.

Let’s say I’m giving stickers to all the people who came to see my amazing program presentation. I need to check whether I have enough stickers for everyone:

>>> stickers = 30
>>> people = 30
>>> stickers >= people
True

I have enough stickers: 30 is the same as 30, so stickers >= people evaluates to True. But say one of my friends thinks the stickers look cool and wants one. Now, 31 people want stickers:

>>> stickers = 30
>>> people = 31
>>> stickers >= people
False

I don’t have enough stickers: 30 is not greater than or equal to 31. It looks like my friend can’t have a sticker.

By now, you’re ready to tackle almost any comparison. While you’re at IDLE, try out the less than or equal to comparator (<=) to see how it works, too.

NOTE

The greater than, greater than or equal to, less than, and less than or equal to comparators don’t work with strings, although they do work with integers, floats, and Booleans.

MISSION #20: AM I ABOVE THE GROUND?

The y-coordinate of a player in Minecraft shows how high they are in the game. Blocks are also stored using coordinates, which allows you to get the block types at specific coordinates using getBlock() and to create blocks at specific coordinates using setBlocks().

To get the highest block in Minecraft, you can use the getHeight() function. The function takes an x- and z-coordinate and returns the y-coordinate for the highest block at that position, as shown in Listing 5-4.

aboveGround.py

from mcpi.minecraft import Minecraft
mc = Minecraft.create()
pos = mc.player.getTilePos()
x = pos.x
y = pos.y
z = pos.z
highestBlockY = mc.getHeight(x, z)
mc.postToChat(highestBlockY)

Listing 5-4: Code to find the y-coordinate of the highest block at the player’s current location

This program gets the current position of the player, gets the y-coordinate for the highest block at the player’s position, and then posts this value to Minecraft chat.

By combining this program with a greater than or equal to comparator, you can check whether or not the player is above the ground. Let’s do that now.

Copy the program in Listing 5-4 and save it as aboveGround.py. Change the program to check whether the player’s y-coordinate is greater than the highestBlockY variable. Then, add code to post the result to chat in the format of "The player is above the ground: True/False".

HINT

Remember that you can store the result of a comparison in a variable. For example, if I wanted to check whether y is greater than or equal to 10 and store the answer in a variable called highEnough, I would use the following statement: highEnough = y >= 10.

Run the program when you’ve made these changes. The output for the program’s False outcomes are shown in Figure 5-4.

image

Figure 5-4: Now I’m in a cave, so Python is very much correct that I’m not above ground.

MISSION #21: AM I CLOSE TO HOME?

As you wander around the Minecraft world, you might get lost and forget where your home is. You could wander for hours only to discover you were close to home when you first lost your way.

With a single line of code, you can check how far you are from any coordinates in the game. For example, you could use the coordinates of your house and your current position to calculate how far away you are. By adding a comparator, you can also check whether or not you are within a certain number of blocks from your house. We’ll say you’re close to home if you’re only 40 blocks away.

Let’s write a Python program to check this for you! The code for this mission should check how far you are from your house, as shown in Listing 5-5.

farFromHome.py

   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()
   import math
homeX = 10
   homeZ = 10
   pos = mc.player.getTilePos()
   x = pos.x
   z = pos.z
distance = math.sqrt((homeX - x) ** 2 + (homeZ - z) ** 2)
mc.postToChat(distance)

Listing 5-5: Code that outputs the distance to your house

This code assumes your house is at the coordinates x = 10 and z = 10, which are set with the homeX and homeZ variables . In this case, we don’t need to know about the y-coordinate. I use the getTilePos() function to get the player’s position and set the x and z values.

To calculate the distance variable, we use a formula called the Pythagorean theorem. It calculates the length of a side of a right triangle, and you can use it in Minecraft to work out the distance between two points. You may have seen this formula written in math class as a2 + b2 = c2, where a and b are the two legs of a right triangle, and c is the hypotenuse of the triangle, as shown in Figure 5-5. At , we’re solving for c, which is represented by the variable distance.

Save Listing 5-5 as farFromHome.py in the booleans folder.

To finish the program, use a less than or equal to comparator to check whether the value of the distance variable is less than or equal to 40 and post the result to chat in the format of "Your house is nearby: True/False" . Use concatenation to combine the string with the result of the comparison. Update the contents of the postToChat() function to output the string.

image

Figure 5-5: A right triangle

Test the program. When you are within 40 blocks of your house, you should receive a True message; when you aren’t within 40 blocks, you should see a False message. Figure 5-6 shows the program in operation.

image

Figure 5-6: I’m definitely within 40 blocks of my house. In fact, there’s the front door!

LOGICAL OPERATORS

Combining two or more comparators is often necessary in programs. You might want to determine whether two conditions are True: for example, you might want a car that is red and costs less than $10,000.

To combine two or more comparators, you use logical operators. Like comparators, you can use logical operators anywhere that you would use a Boolean value. Logical operators are also called Boolean operators. You’ll learn about three kinds of logical operators: and, or, and not.

AND

Use the and operator when you want to check whether two comparisons are both True. For an expression with an and operator to be True, both comparisons must be True. If either comparison is False, the statement will return False.

Say I want to find out whether a person is older than 18 and owns a car. I might write the following program:

>>> age = 21
>>> ownsCar = True
>>> age > 18 and ownsCar == True
True

Here, we’re combining two comparators at and with and. Because the age of the person is greater than 18 (age > 18 evaluates to True) and they own a car (ownsCar == True), the entire expression age > 18 and ownsCar == True evaluates to True.

If one of these comparisons was False, the statement would evaluate to False. Say the person doesn’t own a car but is older than 18:

>>> age = 25
>>> ownsCar = False
>>> age > 18 and ownsCar == True
False

Here, age > 18 evaluates to True and ownsCar == True evaluates to False, making the entire expression False.

Table 5-1 summarizes the results of all of the possible Boolean combinations and results when using the and operator.

Table 5-1: The Different Combinations of True and False with the and Operator

Comparison A

Comparison B

A and B

TRUE

TRUE

TRUE

TRUE

FALSE

FALSE

FALSE

TRUE

FALSE

FALSE

FALSE

FALSE

MISSION #22: AM I ENTIRELY UNDERWATER?

In Mission #18 (page 85), you checked whether the player was swimming. The program returned True or False depending on whether the block at the player’s current position was equal to water. That told you whether the player’s legs were underwater, but it would give the same result whether or not the player’s head was underwater. How would you check whether both the player’s legs and head were underwater?

With a few simple changes to include an and operator, the swimming.py program can check whether the player’s legs and head are underwater. Open swimming.py and save it as underwater.py.

Make the following changes so the program checks whether the player is entirely underwater:

  1. Add a second variable that checks the block type at the player’s y position + 1. This variable stores the block type at the player’s head. Call this variable blockType2.

  2. Check whether blockType is equal to water and whether blockType2 is equal to water.

  3. Post the result of the comparison to chat with this message: "The player is underwater: True/False".

HINT

To check whether blockType and blockType2 are equal to water, you can use the and operator. First, you check whether blockType is equal to water with the expression blockType == 9. Second, you check whether blockType2 is equal to water with the expression blockType2 == 9. To combine the two, you put an and operator in the middle, like this: blockType == 9 and blockType2 == 9.

When you run the program, make sure you test that it works in all three cases (when the player is above the water, when only the player’s legs are in the water, and when they’re entirely under the water). Figure 5-7 shows an example of the program working.

image

Figure 5-7: The player is under the water, running along the seafloor.

OR

The or operator works differently than and. When either or both comparisons are True, the or expression will return True. As long as one comparison is True, the expression will still be True. But if neither comparison is True, the expression will evaluate to False.

Let’s say I want to adopt a cat that is either black or orange in color. I could use the following code to get user input, and then see if the value of the string is either "black" or "orange":

catColor = input("What color is the cat?")
myCatNow = catColor == "black" or catColor == "orange"
print("Adopt this cat: " + str(myCatNow))

As long as the catColor is either "black" or "orange", I’ll adopt it. But if it’s a different color, like "gray", myCatNow would be False and I wouldn’t adopt the cat.

Table 5-2 contains all of the possible combinations and results of using the or operator with Booleans.

Table 5-2: The Different Combinations of True and False with the or Operator

Comparison A

Comparison B

A or B

TRUE

TRUE

TRUE

TRUE

FALSE

TRUE

FALSE

TRUE

TRUE

FALSE

FALSE

FALSE

MISSION #23: AM I IN A TREE?

The programs you’ve created so far in this chapter have displayed True or False depending on whether the player is standing on or in a particular block type. But what if you wanted to check whether the player is in a tree? How would you do this? Because trees are made of wood and leaves, you’d have to check whether the player is standing on wood or leaves.

Let’s write a program. Open swimming.py again and save it as a new program called inTree.py.

Change the program so it checks the type of block that is one block below the player. You’ll want to use the or operator to check whether the block below the player is leaves (block type 18) or wood (block type 11), then post the result to chat.

Recall that you can check the block below the player using y = y - 1.

NOTE

Although trees and leaves both come in different colors, all trees share the same block ID, and all leaves share the same block ID. (The only exceptions are Acacia and Dark Oak wood and leaves, which are a different block type. For now, let’s just ignore Acacia and Dark Oak.) The color is set using a second value, which you’ll learn about in a later chapter.

When you run the program, you should see the same output as in Figure 5-8.

image

Figure 5-8: I’m in a tree.

NOT

The not operator is quite a bit different from the and and or operators. It’s used on a single Boolean value or comparison and simply changes its value to the opposite.

In other words, not changes True to False and False to True:

>>> not True
False
>>> not False
True

The not operator is handy when you start combining it with other logical operators. Let’s assign the value of timeForBed if you’re not hungry and you are sleepy.

>>> hungry = False
>>> sleepy = True
>>> timeForBed = not hungry and sleepy
>>> print(timeForBed)
True

The not operator only applies to the Boolean it is in front of. Here it reverses the value of the hungry variable and leaves the sleepy variable alone. Because we set hungry to False earlier, writing not hungry now changes the value to True. The value of sleepy is True. Both values are now True, so timeForBed is True.

MISSION #24: IS THIS BLOCK NOT A MELON?

You’re hungry and want to know whether you have food at home. Your favorite food is melon, which you always store in the same space in your house. But you can’t remember if you have any melon left, and you need to decide whether to get food on your way home.

Thankfully, you’re learning Python! With a bit of brain power, you can write a Python program to check whether you have a melon at home.

In this mission, you’ll create a program that says whether or not you need to find food before you return to your Minecraft house. The program will check whether there is a melon at certain coordinates. The coordinates you’ll check are up to you—they could be in your house, on your farm, or anywhere you might decide to keep some melon. Placing a melon at these coordinates is also up to you.

Copy Listing 5-6 and save it as notAMelon.py.

notAMelon.py

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

   x = 10
   y = 11
   z = 12
melon = 103
block = mc.getBlock(x, y, z)

noMelon = # Check the block is not a melon

mc.postToChat("You need to get some food: " + str(noMelon))

Listing 5-6: The start of the code to check whether there is a melon at a specific location

The code is meant to check whether the block at a specific position is a melon block. I’ve included a variable called melon that stores the block ID of a melon (103) , and I’ve called the getBlock() method and stored the result in a variable called block . To complete this program, you need to finish the line at that checks whether the melon variable is not equal to the block variable. The result should be stored in the noMelon variable so that it can be output to the Minecraft chat on the last line .

You can write the check to see if the melon and block variables are not equal in two ways: you can use the not equal to comparator or the not logical operator. Although the program will work either way, try using the not logical operator for this program.

Run the program when you’ve made the changes. The result should look something like Figure 5-9.

image

Figure 5-9: There’s a melon on my farm, so I don’t need to find some other food.

LOGICAL OPERATOR ORDER

You can combine as many logical operators as you want in a single statement. For example, here’s a pretty fancy combination using and, or, and not:

>>> True and not False or False
True

This code evaluates to True. Are you surprised? In this example, the not False part of the statement is evaluated first to True. This is equivalent to:

>>> True and True or False
True

The and is then evaluated, and True and True evaluates to True, which is equivalent to:

>>> True or False
True

Finally, the or is evaluated, so True or False becomes True.

When Python evaluates logical operators, it uses a certain order. If you get the order wrong, you might get a result you weren’t expecting! Here’s what Python evaluates first, second, and third:

  1. not

  2. and

  3. or

Practice creating statements with logical operators in IDLE and see if you can guess the result of each.

IS MY NUMBER BETWEEN TWO OTHERS?

Often, you’ll want to check whether a value is less than one value and greater than another. Let’s imagine you wanted to make sure that you had between 10 and 20 wolves, because you love wolves and want more than 10, but 20 or more might cause problems as you’d run out of food. You could test for this condition by using an and operator:

wolves = input("Enter the number of wolves: ")
enoughWolves = wolves > 10 and wolves < 20
print("Enough wolves: " + str(enoughWolves))

But you could also do it another way. Instead of using the and operator, write the variable once in the middle of two comparisons:

wolves = input("Enter the number of wolves: ")
enoughWolves = 10 < wolves < 20
print("Enough wolves: " + str(enoughWolves))

If you run either of these programs and enter a number between 10 and 20 but not equal to either, then enoughWolves will be True. You can do the same using the greater than or equal to operators (>=) and the less than or equal to operators (<=):

wolves = input("Enter the number of wolves: ")
enoughWolves = 10 <= wolves <= 20
print("Enough wolves: " + str(enoughWolves))

In this case, entering 10 or 20 would also give enoughWolves a value of True.

MISSION #25: AM I IN THE HOUSE?

With Python code, you can make cool actions happen when you walk onto a certain area on the map. You could make a secret door open when the player walks onto a specific block, or you could trap them in a box when they walk over a trap. In this mission, I’ll show you how to detect if someone is in your Minecraft house.

In Mission #8 (page 55), you created a program that automatically builds the walls, ceiling, and floor of a building. You saved the program as building.py in the math folder. Open this program.

Read the code in the building.py program and make a note of the values of the width, height, and length variables (by default the values were 10, 5, and 6, respectively). Also, write down the coordinates that you are currently standing at. Run the building program to build a house.

Now that you’ve created a building, we can write a program like Listing 5-7 that checks whether the player is standing inside it.

insideHouse.py

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

buildX =
   buildY =
   buildZ =
width = 10
   height = 5
   length = 6

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

inside = buildX < x < buildX + width and

Listing 5-7: The start of the program to check whether the player is inside their house

Listing 5-7 is supposed to check that the player’s x-coordinate is within the building created by building.py, but the program isn’t finished! Your job is to make sure the program also checks the y- and z-coordinates against the coordinates of the house that you built with the building.py program.

Copy Listing 5-7 into a new file and save it as insideHouse.py. You’ll complete the program so it checks whether the player is inside the building.

To complete the program, do the following:

  1. Add the coordinates of the building (these are the coordinates you were standing at when you ran the building.py program) .

  2. Correct the width, height, and length variables if they are different from the ones used in your building.py program .

  3. Complete the comparison for the inside variable so it checks whether the player’s coordinates are inside the building. The first part, to check whether the x position is in the house, has been done for you . You need to add the comparisons for the y and z positions. The expressions are similar to the one that I’ve included for the x position (buildX < x < buildX + width).

  4. Post the value of the inside variable to the chat.

  5. When you’ve made the changes, save and run the program. You should see output similar to Figure 5-10.

    image

    Figure 5-10: I’m in my bedroom, which is indeed inside my house.

WHAT YOU LEARNED

In this chapter, you used Booleans, comparators, and logical operators to answer questions in your programs. In Chapter 6, you’ll write programs that make decisions based on the answers to these questions. You’ll check whether a condition is true or not, and you’ll tell the program to run some code if the condition is true or run different code if it’s false. In Chapter 7, your programs will keep running a piece of code as long as a condition is true and stop if the condition becomes false. This is the real power of Booleans and comparators. They help you control which code gets run in your program and exactly when the code gets run.

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

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