8
FUNCTIONS GIVE YOU SUPERPOWERS

image

Functions are reusable blocks of code that perform specific tasks. Say you want to write code that builds a tree in Minecraft. You could rewrite the tree-building code every time you need to use it in your program (or copy and paste it); however, this would be inefficient, especially if you wanted to change it.

Instead of copying and pasting, you could write the tree-building code as a function. Recall that we used some functions in earlier chapters: str(), input(), and int(). They’re all functions that are built into Python. You’ve even been using Minecraft functions, such as the getBlocks() and setPos() functions, which come with the Minecraft Python API. In this chapter, you’ll create your own functions.

You create and use functions for the following reasons:

Reusability Functions save time. Because you don’t have to rewrite the same code over and over again, writing a program is faster and easier.

Debugging By containing tasks in groups of code, it is easier to identify where a problem originates and make changes to fix the problem.

Modularity You can develop different functions to use in the same program independently of one another. This makes it easier to share code with other people and reuse functions in other programs.

Scalability Using functions makes it easier to increase the size of a program and the amount of data it processes.

DEFINING YOUR OWN FUNCTIONS

Let’s look at how you can use functions in your code. In the following example, I make a function called greeting() that simply prints two lines:

def greeting():
    print("Hello")
    print("Nice to meet you")

The def keyword, which is an abbreviation for define, tells Python you’re writing a function. Anytime you want to write a function, you must first write def followed by the function’s name. In this example, greeting is the name of the function. Don’t forget to add the parentheses and the colon at the end of the first line. The lines that follow the colon are the body of the function, which is the code that will run when the function is called.

NOTE

Keep indentation consistent in your code. Always indent the body of the function by using four spaces.

A function can contain as many statements as you want. It can also include if statements, loops, variables, conditions, math operators, and so on. When you reach the end of the function code, stop indenting lines so Python knows which statements belong to the function and which statements belong to other parts of your code.

You can create as many functions as you want in a program, as long as they have different names.

CALLING A FUNCTION

To use, or call, a function, you write the name of the function with any arguments it might require in parentheses. If your function doesn’t take any arguments, just write the function’s name and a set of empty parentheses.

To call the greeting() function defined earlier, you would use the following code:

greeting()

You can call the function as many times as you want. Let’s call the greeting() function three times:

greeting()
greeting()
greeting()

When you run the program, it should produce the output of the function three times, like so:

Hello
Nice to meet you
Hello
Nice to meet you
Hello
Nice to meet you

You must call the function in the body of your code, or the function will not do anything. This is a common mistake. If you run a program that defines some functions and your code doesn’t do anything, it might be because you forgot to call the functions you created.

You can also call functions from within another function that you’ve created. These include built-in Python functions as well as those you’ve created. You’ll see this in action in just a moment.

FUNCTIONS TAKE ARGUMENTS

The parentheses in a function contain its arguments, which are values the function uses. The values are used for specific variables inside the function when it runs. Not every function needs arguments. For example, the greeting() function doesn’t take arguments.

But let’s say I want to display a greeting to someone using their name. I’ll write this as a function so I can reuse the code to greet different people:

def fancyGreeting(personName):
    print("Hello, " + personName)

fancyGreeting("Mario")
fancyGreeting("Steve")

In this example, function is called twice using different arguments, "Mario" and "Steve". When you run the program, the output looks like this:

Hello, Mario
Hello, Steve

If you forget to include an argument when you call a function that needs one, you will get an error. Also, if a function needs multiple arguments and you forget to include even one of them, you will get an error. For example, let’s try calling the fancyGreeting() function with no arguments, like this:

fancyGreeting()

The following error message is displayed:

   Traceback (most recent call last):
     File "<pyshell#2>", line 1, in <module>
       fancyGreeting()
TypeError: fancyGreeting() takes exactly 1 argument (0 given)

This is a useful error message because the last line explains what is wrong with the code . The fancyGreeting() function takes one argument, but because it was given no argument, that caused the error.

You can create a function that takes several arguments. For example, the following program contains a function that says hello to someone, waits a number of seconds, and then says goodbye. The function uses an argument for the person’s name and the number of seconds the program will wait:

   import time

def helloAndGoodbye(personName, secsToWait):
       print("Hello, " + personName)
       time.sleep(secsToWait)
       print("Goodbye, " + personName)

helloAndGoodbye("Mario", 10)
   helloAndGoodbye("Steve", 23)

Each argument is separated by a comma when the function is defined . Then, when the functions are called, the arguments are passed in the same order in which they were defined .

NOTE

You might encounter the terms argument and parameter used almost interchangeably. The parameters of a function define the types of arguments it accepts or requires, and the arguments are the values that you pass to the function when you call it. For simplicity, we’ll just use the term argument in this book.

MISSION #41: BUILD A FOREST

Your mission is to create a forest of trees in Minecraft. Because a forest is just a bunch of trees, we’ll create the forest by making a function that builds one tree and then call that function many times to create a forest.

Listing 8-1 is the basic code you’ll be using.

forest.py

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

def growTree(x, y, z):
       # Creates a tree at the coordinates given
       # Write your code to make a tree here

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

growTree(x + 1, y, z)

Listing 8-1: The structure of a program that uses functions to create a forest of trees

The growTree() function created in this code takes arguments for the coordinates where the tree will be built. Your task is to write code in the body of the function that creates a tree at the given coordinates. You’ll use the setBlock() and setBlocks() functions to do this.

Copy Listing 8-1 into a new file in IDLE and save it as forest.py in a new folder called functions.

When you’ve created something that resembles a tree and it appears onscreen, try writing more calls to the function using different arguments so trees appear at different locations. The first one has been done for you . Try creating at least nine trees in front of the player each time you run your program. Figure 8-1 shows the trees that my program created.

image

Figure 8-1: I’ve just grown a beautiful row of trees.

REFACTORING A PROGRAM

Quite often you’ll write a program that uses the same block of code several times. Making changes to the program will become tedious when you want to change the same code in different places. You might have done this in programs you’ve written in the past, but there’s a much better way.

You can restructure your programs to use functions. To do this, move the code that is repeated several times into a single function that you can then use as many times as you want in the rest of the code. Because you’ll only need to make changes in one place instead of several, you’ll save space and the program will be easier to maintain. The process of restructuring your code in this way is called refactoring.

For example, the following code asks three people their names and then prints a greeting to each of them:

name1 = input("Hello, what is your name?")
print("Pleased to meet you, " + name1)
name2 = input("Hello, what is your name?")
print("Pleased to meet you, " + name2)
name3 = input("Hello, what is your name?")
print("Pleased to meet you, " + name3)

The code here repeats the same two statements three times. What if you wanted to change the question or the greeting? It’s not much of a problem changing the code for 3 people, but what if you were writing code for 100 people?

The alternative is to write the code as a function and call it three times. Here is the code after refactoring it:

def helloFriend():
    name = input("Hello, what is your name?")
    print("Pleased to meet you, " + name)

helloFriend()
helloFriend()
helloFriend()

Now when the program runs, it will ask for input and then output a string, and it will do both tasks three times. Here are the input and output:

Hello, what is your name? Craig
Pleased to meet you, Craig
Hello, what is your name?
Still Craig
Pleased to meet you, Still Craig
Hello, what is your name?
Craig again
Pleased to meet you, Craig again

The second version of the code has the same outcome as the first version, but as you can see, it’s much easier to read and much easier to change.

MISSION #42: REFACTOR AWAY

Sometimes you’ll write a program only to realize afterward that you should have used functions (I do this all the time). Refactoring code to include functions is a very important skill.

In this mission, you’ll practice refactoring a program to use a function instead of repeating the same statements several times.

Listing 8-2 places a melon block underneath the player every 10 seconds. We’ll rewrite the code to use a function. Currently, the program places three blocks by using the same line of code three times. Figure 8-2 shows the result of the program.

melonFunction.py

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

import time

pos = mc.player.getPos()
x = pos.x
y = pos.y
z = pos.z
mc.setBlock(x, y - 1, z, 103)
time.sleep(10)

pos = mc.player.getPos()
x = pos.x
y = pos.y - 1
z = pos.z
mc.setBlock(x, y, z, 103)
time.sleep(10)

pos = mc.player.getPos()
x = pos.x
y = pos.y - 1
z = pos.z
mc.setBlock(x, y, z, 103)
time.sleep(10)

Listing 8-2: Some code that needs refactoring

This code isn’t very pretty, is it? Several lines are repeated, which is always a sign that the code needs refactoring with the help of a function definition.

HINT

Identify which parts of the code repeat to get an idea of what your function should do.

image

Figure 8-2: Three delicious melons under the ground

Change the code so it places six blocks in total by calling your function six times. Create a new file and save it as melonFunction.py in the functions folder. Copy Listing 8-2 into your file and refactor the code to use a function. Call the new function makeMelon().

COMMENTING WITH DOCSTRINGS

Using comments in Python code is a way to explain what code does. When Python runs a program, it ignores everything in a comment, so comments don’t affect how the code runs. The main purpose of comments is to explain what your code is supposed to do to others who might look at or use your code. Comments are also useful reminders for yourself in the future.

Because functions are supposed to be reusable, it makes sense to explain their purpose. To write explanations for our functions, we’ll use long explanations called docstrings. A docstring is a multiline comment that you place at the start of a function to explain its use.

The duplicateWord() function in the following example has a docstring that explains its task:

   def duplicateString(stringToDbl):
     """ Prints a string twice on the same line.
       stringToDbl argument should be a string """
       print(stringToDbl * 2)

The docstring should be on the first line of a function . The docstring begins and ends with a set of three quotation marks (""") and can be written across as many lines as necessary.

LINE BREAKS IN ARGUMENTS

To make long lists of arguments easier for programmers to read, Python allows you to place arguments across several lines. For example, the function call in this program has its arguments split across several lines to increase readability:

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

pos = mc.player.getPos()
width = 10
height = 12
length = 13
block = 103
mc.setBlocks(pos.x, pos.y, pos.z,
             pos.x + width, pos.y + height, pos.z + length, block)

Line breaks in arguments are particularly useful when you want to use math operators on arguments, when you are using long variable names as arguments, or when you have several arguments to provide to a function.

FUNCTION RETURN VALUES

There are two types of functions: those that return a value and those that don’t. So far, you’ve created functions that don’t return a value. Let’s look at those that do return a value.

Returning a value from a function is very useful, because it allows a function to work with data and then return a value to the main body of the program. For example, imagine you sell cookies. To calculate the price you have to sell each cookie at to make enough profit, you add two gold coins to the amount you paid to make the cookie and then multiply the sum by 10. By using a function that returns a value, you can write this calculation and reuse it in Python.

When making your own functions, you can use the return keyword to return a value from the function. For example, here is the code to calculate your selling price for a cookie:

def calculateCookiePrice(cost):
    price = cost + 2
    price = price * 10
    return price

To return a value, you just write return followed by the value you want, which in this case is price. To use a function that returns a value, you call it in a place that would expect a value. For example, to set the priceOfCookie variable, call the calculateCookiePrice() function and enter a cost, such as 6:

priceOfCookie = calculateCookiePrice(6)  # Value will be 80

You can use functions that return values to set the values of variables, and you can use them anywhere that you are expected to put a value, even as an argument for another function.

Functions that do not return a value cannot be used to set the values of variables. Let’s take a quick look at the difference.

Because the following function returns a value, it can be used anywhere a value can be used, such as to set a variable or even as an argument in another function call:

def numberOfChickens():
    return 5

coop = numberOfChickens()
print(numberOfChickens())

Run this code to see its output. You can treat the result from the function like a value and even do math with it. Here I add 4 to the returned value and store it in a variable called extraChickens:

extraChickens = 4 + numberOfChickens()  # Value of 9

However, the following function doesn’t have a return statement, which means you can’t use it in place of a value. All you can do is call the function:

def chickenNoise():
    print("Cluck")

chickenNoise()

Writing this code in the text editor and running it prints "Cluck", although it can’t be used in other statements because it doesn’t return a value to the program. For example, I could try to concatenate the function with a string, like so:

multipleNoises = chickenNoise() + ", Bork"

If I ran this program, I would get the following error message:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    multipleNoises = chickenNoise + ", Bork"
TypeError: unsupported operand type(s) for +: 'function' and 'str'

This error means you can’t combine this function with a string, because the function doesn’t return a value.

However, if I change the code to return a value instead of just printing it:

def chickenNoise():
    return "Cluck"

multipleNoises = chickenNoise() + ", Bork"
print(multipleNoises)

the file would run and display the following output:

Cluck, Bork

Keep this difference in mind. Remember to include a return statement when you need it and exclude it when your function doesn’t need to return a value. The more experienced you become with functions, the easier it will be to decide whether you want your function to return a value.

MISSION #43: BLOCK ID REMINDER

Because Minecraft has so many blocks, it’s difficult to remember all the block IDs. I always remember the melon (103) and air (0) values but forget others, so I keep having to build houses out of melons!

To make remembering easier, I want you to create a program for me that returns the values of different blocks. Your program should have many functions that help me remember block IDs. The name of each function should be the same as the name of the block whose value it returns. For example, Listing 8-3 has a function called melon() that returns the value of the melon block (103).

blockIds.py

def melon():
    """ Returns the value of the melon block """
    return 103

Listing 8-3: The start of the program that will help me remember block IDs

Create a new file in IDLE and save it as blockIds.py in the functions folder. Copy Listing 8-3 into the file and add functions to it that return the values of the following blocks (see “Block ID Cheat Sheet” on page 283):

• Water

• Wool

• Lava

• TNT

• Flower

• Diamond block

After you’ve added your functions, test them by calling the functions to create blocks. Because your new functions return a block’s value, you can use them to set the value of a variable to pass into the setBlock() function. The following code will help you get started:

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

# Functions go here

block = melon()
pos = mc.player.getTilePos()
mc.setBlock(pos.x, pos.y, pos.z, block)

Figure 8-3 shows the result of the completed program with a test for the melon() function. Notice that the placement of any block is hardcoded into this program; it will always place a block at your current location.

image

Figure 8-3: Now I don’t have to remember the block types, all thanks to this handy function.

HINT

To place a diamond block, TNT, or any other kind of block, you’ll first need to define the function that returns the value of the block you want. Then you’ll need to call that function in your code, just like I called the melon() function in this example.

USING IF STATEMENTS AND WHILE LOOPS IN FUNCTIONS

In Chapters 6 and 7, you learned about putting if statements inside of other if statements and while loops inside of other while loops. You learned that you can even put if statements within while loops and vice versa! In this section, you’ll learn how to put if statements and loops inside functions. This makes your functions very flexible, because you can use them to make decisions and repeat code.

IF STATEMENTS

When you’re writing an if statement within a function, the syntax is identical to that of a regular if statement. You just need to remember to indent the if statement by an extra four spaces at the start of every line so Python knows it’s part of the function.

The following code takes a number written as a string and returns the number as an integer. For example, the argument "four" returns the value 4:

def wordToNumber(numToConvert):
    """ Converts a number written as a word to an integer """
    if numToConvert == "one":
        numAsInt = 1
    elif numToConvert == "two":
        numAsInt = 2
    elif numToConvert == "three":
        numAsInt = 3
    elif numToConvert == "four":
        numAsInt = 4
    elif numToConver == "five":
        numAsInt = 5

    return numAsInt

Let’s look at another example. The following function checks whether you’ve met a person before and uses an appropriate greeting depending on the result:

def chooseGreeting(metBefore):
       """ Chooses a greeting depending on whether you've met someone before.
       metBefore argument should be a Boolean value """
       if metBefore:
         print("Nice to see you again")
       else:
         print("Nice to meet you")

   chooseGreeting(True)
   chooseGreeting(False)

The chooseGreeting() function takes one Boolean argument, called metBefore . The if statement inside the function then prints output based on the value of the argument. If the value is True, the output will be "Nice to see you again" , and if it is False , the output will be "Nice to meet you".

MISSION #44: WOOL COLOR HELPER

You’ve used the setBlock() and setBlocks() methods with arguments to set block coordinates and block type, but these methods also have an optional extra argument that will set the block state.

Each block in Minecraft has 16 states, 0 to 15. Wool, for example, has a different color for every state. TNT (block ID 46) won’t explode when you smash the block in its default state (state 0), but it is explosive when you smash it in block state 1. Although every block has 16 states, not all of them have different behaviors.

To set a block’s state, you provide the setblock() or setblocks() function with an extra argument. The following code creates a pink block of wool:

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

block = 35
state = 6
# Creates a single block of pink wool
mc.setBlock(10, 3, -4, block, state)

# Creates a cuboid of pink wool
mc.setBlocks(11, 3, -4, 20, 6, -8, block, state)

Wool (block ID 35) has many uses in Minecraft due to its different colors, but it’s difficult to remember the different block states. Fortunately, you don’t need to memorize the different block states when you can use a program to remind you.

Let’s make a program that contains the wool block’s states. The program will contain a function with an argument that takes the color you want written as a string. The function then returns the block state for the wool color as an integer. The function will contain the bulk of the code for the program. However, you’ll add a couple of code lines to take input from a user and place the block in the game, and you’ll use your fancy new function to set the color.

First, you’ll need to find out the block states for the different colors of wool. You can find them in the “Block ID Cheat Sheet” on page 283. Here’s some code to get you started (pink is block state 6):

woolColors.py

   def getWoolState(color):
       """ Takes a color as a string and returns the wool block state for
       that color """
     if color == "pink":
           blockState = 6
       elif # Add elif statements for the other colors
       # Return the blockState here

colorString = input("Enter a block color: ")
   state = getWoolState(colorString)

pos = mc.player.getTilePos()
   mc.setBlock(pos.x, pos,y, pos.z, 35, state)

At the moment, the program has just the beginnings of the getWoolState() function. It only has an if statement for the color pink . Also included is code at the end of the program to take user input for the block color and code to place the wool block at the player’s position .

Add to the getWoolState() function using elif statements for other wool colors and their corresponding block states. The program should take an argument for the color of the block and return the integer value of the block state. For example, providing the argument "pink" will return the value 6. You’ll also need to add a return statement to the program. Use the comments to guide you.

Save the file as woolColors.py in the functions folder.

If you want to make the program more user friendly, you can post a message to chat if the argument is not a valid color. Figure 8-4 shows the input in the Python shell and the wool block being placed in the game.

image

Figure 8-4: Now I can create a wool block in any color by entering the name of the color I want.

WHILE LOOPS

Just like if statements, loops can be written inside functions. The syntax for a loop inside a function is the same as that for a regular loop. You just need to remember that the loop should be indented by an extra four spaces on each line to indicate that it belongs to the function.

In the following example, the while loop within the function will print the toPrint argument. The number of times the loop repeats is determined by the repeats argument.

def printMultiple(toPrint, repeats):
    """ Prints a string a number of times determined by the repeats variable """
    count = 0
    while count < repeats:
        print(toPrint)
        count += 1

You can also use return statements and while loops in the same function. In most cases, you’ll want the return statement to be outside the loop. (If you use the return statement inside a loop, it will break the loop and end the function.) Let’s look at an example:

   def doubleUntilHundred(numberToDbl):
       """ Doubles a number until it is greater than 100. Returns the number of
       times the number was doubled """
       count = 0
       while numToDbl < 100:
           numberToDbl = numberToDbl * 2
           count += 1
     return count

   print(doubleUntilHundred(2))

This program doubles a number until it is greater than 100. It then returns the number of times the loop repeated .

You can also put function calls within loops, as you did in previous chapters.

MISSION #45: BLOCKS, EVERYWHERE

By using loops inside functions, you can use an argument to determine the number of times a loop repeats. By using the setBlock() function, you can also determine the type of block to be placed within the loop.

WARNING

The program in this mission could be destructive, so you might want to try it in a new world to preserve your precious creations.

In this mission, you’ll create a function that places blocks randomly around the map. The number of blocks it places and the block type it places are determined by function arguments.

Listing 8-4 generates a melon at a random location on the map.

blocksEverywhere.py

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

   def randomBlockLocations(blockType, repeats):
     count = 0
     # Add the loop here
       x = random.randint(-127, 127)
       z = random.randint(-127, 127)
     y = mc.getHeight(x, z)
       mc.setBlock(x, y, z, blockType)
       count += 1

Listing 8-4: When called, this function will place a block randomly in the game.

Copy Listing 8-4 into a new file in IDLE and save it as blocksEverywhere.py in the functions folder. At , add a while loop inside the function so the code repeats. The count variable makes it easier for you to tell how many times the loop has repeated. Compare the repeats argument to the count variable in the loop’s condition to set how many times the loop should repeat. Indent all the lines inside the function after so they are also inside the loop. The getHeight() function ensures that the block is placed above the ground .

Finally, add three function calls to create blocks. The first function should create 10 blocks, the second one should create 37 blocks, and the third should create 102 blocks. Choose any block types that you want.

Save the program and run it. The program should create blocks randomly around the map. Figure 8-5 shows an example.

image

Figure 8-5: You can see some of the blocks that the program has placed randomly. I created a new world to demonstrate this program so it didn’t damage any of my buildings.

GLOBAL AND LOCAL VARIABLES

When you’re defining functions, you have a new challenge to deal with, namely the scope of a variable. The scope of a variable describes how your program can access its data. The best way to learn about scope is to see it in action, so let’s look at some code. Let’s say you’re using the following code, which increases the number of eggs you have for a party:

eggs = 12

   def increaseEggs():
     eggs += 1
       print(eggs)

   increaseEggs()

Two variables are named eggs, one outside the function and another inside the function . Nothing looks terribly wrong, but Python will throw an error. Here’s part of the error message:

UnboundLocalError: local variable 'eggs' referenced before assignment

The problem is that the eggs variable is defined outside the function, but when you try to add to it inside the function, Python can’t see the variable. To Python, the variable inside the function is totally different from the one outside the function, even though they have the same name. Python does this on purpose to stop variables inside different functions from accidentally sharing the same names and causing unexpected bugs.

In Python code, you have two ways to approach the variables in a file: you can either make a variable global, which means it affects an entire program or file, or make a variable local, which means it can be seen only by the code in a particular function or loop. In other words, you can use the same variable inside and outside a function, or you can make two different variables that affect different parts of the code.

A global variable will be treated as the same variable inside and outside a function. Any changes to the variable inside the function will affect the variable that was defined outside the function and vice versa. To make a global variable, use the global keyword :

   eggs = 12

   def increaseEggs():
     global eggs
       eggs += 1
       print(eggs)

   increaseEggs()

In this example, the value of eggs will be 13 when it is printed.

You can treat the variable as a local variable instead to produce a different effect. In this case, the variables inside and outside the function will be treated as different variables. Changes to the variable inside the function will not affect the variable outside the function and vice versa. So you could change the code to make the variable a local variable , like this:

   eggs = 12

   def increaseEggs():
     eggs = 0
       eggs += 1
     print(eggs)

   increaseEggs()
print(eggs)

When the value of eggs in the function is printed , it will be 1 because the value of the eggs variable outside the function does not affect the local variable inside the function. The value of eggs inside the increaseEggs() function is 1, and the global eggs variable still has the value of 12 .

MISSION #46: A MOVING BLOCK

A while ago, I thought it would be cool to make a block move around the Minecraft world by itself. Every second it would move forward. If it hit a wall, a tree, or something tall, it would turn and make its way in a different direction. If it fell in a hole, however, it would get stuck and wouldn’t be able to escape.

Listing 8-5 is the start of a program to make a magical block that moves on its own.

movingBlock.py

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

   import time


   def calculateMove():
       """ Changes the x and z variables for a block. If the block
       in front of the block is less than 2 blocks higher, it will move
       forward; otherwise it will try to move left, then backward,
       then finally right. """
     # Create global variables here

       currentHeight = mc.getHeight(x, z) - 1

       forwardHeight = mc.getHeight(x + 1, z)
       rightHeight = mc.getHeight(x, z + 1)
       backwardHeight = mc.getHeight(x - 1, z)
       leftHeight = mc.getHeight(x, z - 1)

       if forwardHeight - currentHeight < 3:
           x += 1
       elif rightHeight - currentHeight < 3:
           z += 1
       elif leftHeight - currentHeight < 3:
           z -= 1
       elif backwardHeight - currentHeight < 3:
           x -= 1

       y = mc.getHeight(x, z)


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

   while True:
       # Calculate block movement
       calculateMove()

       # Place block
       mc.setBlock(x, y, z, 103)

       # Wait
       time.sleep(1)

       # Remove the block
       mc.setBlock(x, y, z, 0)

Listing 8-5: Unfortunately, this code won’t work until global variables are added.

But this code won’t run yet because the variables in the calculateMove() function aren’t global.

Your mission is to finish the code in Listing 8-5. Copy it into IDLE and save it as movingBlock.py in the functions folder. Add code to the start of the function to make the x, y, and z variables global. The global definitions should be placed at .

After you’ve declared some global variables, run the program. Your block should move around. Figure 8-6 shows the block move up to a wall and then start to move around it.

image

Figure 8-6: It was fun watching the melon move forward and then try to move around the wall.

WHAT YOU LEARNED

Hooray! In this chapter, you learned how to create and call functions. With return statements you can make functions return values, and you can write loops and if statements inside functions. In Chapter 9, you’ll learn about lists, which allow you to store several pieces of data in a single variable.

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

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