2
TELEPORTING WITH VARIABLES

image

Are you ready to control your Minecraft world with the power of Python? In this chapter, you’ll take a brief tour through the basics of Python. Then you’ll put your new skills to the test and create your own teleportation tour of your Minecraft world!

The concepts described in this chapter aren’t specific to Minecraft Python, so you’ll be able to use them in any Python program that you create.

WHAT IS A PROGRAM?

A program is a set of instructions that makes your computer do a specific task or tasks. Imagine a stopwatch app on a mobile phone. The stopwatch program has instructions that tell it what to do when you press start and stop. It also has instructions that display the time on the screen as it’s being counted. Some guy or gal programmed that stopwatch to work.

Millions of programs are used every day all around the world. A phone’s messaging app is a program, traffic lights are controlled by programs, and even computer games like Minecraft are programs.

In this book, you’ll learn the fundamentals of programming and how to write programs to make your ideas come to life in Minecraft.

STORING DATA WITH VARIABLES

Let’s start by learning how to store data with variables. Variables let you store data to use later in a program. Data is any information you might want to record, such as numbers, names, any kind of text, lists of items, and so on. For example, here’s a variable called pickaxes that stores the number value 12:

>>> pickaxes = 12

Variables can store numbers, words, and even complete sentences, such as “Get out of here, Creeper!” You can also change variables, which lets you do some pretty neat things in Minecraft. In fact, shortly you’ll use variables to take advantage of the power of teleportation!

To create a variable in Python, you’ll use a variable name, an equal sign (=), and a value. Let’s say you’re about to take off on a grand adventure through many Minecraft biomes; you’ll want to bring a lot of food with you. You can represent food as a variable. For example, in the following Python shell, bread is the variable name and 145 is the value:

>>> bread = 145

The variable’s name is always on the left of the equal sign, and the value you want to store is always on the right, as shown in Figure 2-1. This Python code line declares the variable bread and assigns the value 145 to it.

image

Figure 2-1: Parts of a variable declaration. You must be very hungry if you have 145 loaves of bread.

After you’ve declared a variable and assigned it a value, you can enter the name of the variable into the Python shell to check what it’s holding:

>>> bread
145

You can use almost any name for a variable, but it’s best to use a name that describes the variable’s purpose so you’ll understand what’s going on in your program. Although it’s not a rule, you should start variable names with a lowercase letter instead of a capital letter. This is a style that Python programmers follow, and it’s good practice for you to follow, too, so others can easily read your code if you ever want to share it.

NOTE

Although the value of a variable is stored, it is not saved. The value of a variable is stored in the computer’s temporary memory, meaning that when the computer is switched off or the program stops running, the value of the variable is no longer stored. Try closing IDLE and then opening it again. When you try to get the value of bread, what happens?

THE STRUCTURE OF PROGRAMMING LANGUAGES

Syntax is the set of rules that describes the grammar and punctuation of a programming language, similar to the grammar and punctuation in a human language. Once you understand Python’s syntax, you’ll be better able to write programs that a computer can follow; however, if you don’t use correct syntax, the computer won’t understand what you’re telling it to do.

Think of a single instruction in your code as a sentence. To end a sentence in English, you use a period (called a full stop in the United Kingdom). Instead of a period, Python uses a new line to indicate the end of an instruction and the start of the next. Each instruction on a new line is called a statement.

For example, say you want to keep track of how many pickaxes, iron ore blocks, and cobblestone blocks you have. In the Python shell, you’d write it like this:

>>> pickaxes = 12
>>> iron = 30
>>> cobblestone = 25

Figure 2-2 shows what this looks like in the Python shell.

image

Figure 2-2: Entering code in the Python shell

Notice that each statement is on its own line. Because of the new lines, Python will understand that you want to keep track of three different items. But if you don’t put each statement on a new line, Python gets confused and gives you a syntax error:

>>> pickaxes = 12 iron = 30 cobblestone = 25
SyntaxError: invalid syntax

A syntax error is Python’s way of telling you it doesn’t understand. Python won’t be able to follow these instructions because it doesn’t know where one statement ends and another begins.

Python also won’t know what to do if you start lines with a space:

>>>   iron = 30
SyntaxError: unexpected indent

If you look closely, you’ll see that the code has spaces at the beginning of the line. When you get an unexpected indent syntax error, like the one here, you’ll know that your line of code starts with spaces when it shouldn’t.

Python is very picky about how you write code. If you get a syntax error when entering the examples in this book, check your work carefully. Most likely, you’ll find a small mistake.

SYNTAX RULES FOR VARIABLES

You need to know a few syntax rules for naming variables so Python can understand them:

• Don’t include symbols in your variable names, except for underscores (_), or you’ll get a syntax error.

• Don’t start a variable name with a number, as in 9bread. Using numbers elsewhere in a variable name is fine, as in bread9.

• You don’t need to add spaces on either side of the equal sign: your program will run fine without them. But they do make the code easier to read, so it’s a good idea to add them.

Variables are very handy. Next, you’ll learn how to change the value of variables, and then you’ll be ready to teleport your player!

CHANGING THE VALUES OF VARIABLES

You can change the value of a variable at any time in the same way you’d declare a variable. For example, say you meet five Minecraft cats and you want to save this value as a variable. First you declare a variable, cats, and assign the value 5 to it, which would look like this in a Python shell:

>>> cats = 5
>>> cats
5

Later you meet five more cats and decide you want to update this value. What happens if you change the value of cats to 10?

>>> cats = 10
>>> cats
10

When you ask Python for the new value of cats, it’s no longer 5! Now when you use the cats variable in a program, it will use the new value of 10.

There are many types of data that you can store in variables. Data types tell the computer how to work with a particular piece of data. I’ll start by discussing one of the types you’ll use most often: integers. Later in the chapter, I’ll also introduce the floats data type.

INTEGERS

Integers are positive or negative whole numbers. Values such as 10, 32, –6, 194689, and –5 are integers, but 3.14 and 6.025 are not.

You probably use integers every day without even thinking about it, even in Minecraft! For example, you might see 12 cows on a hillside while you’re on your way to mine 5 diamonds with 2 fresh apples in your inventory. All those numbers are integers.

Let’s say you have five pigs in your Minecraft world and you want to write a program that uses the number of pigs in some way. In Python, you’d declare an integer variable to represent the number of pigs:

>>> pigs = 5

You can also store negative values in variables. For example, to say the temperature is negative five degrees, you would set a variable like so:

>>> temperature = -5

To use Python variables and integers with Minecraft, complete the first mission.

MISSION #1: TELEPORT THE PLAYER

In this mission, you’ll explore how variables work by teleporting your player to a new location using integers.

As shown in Figure 2-3, your player has a position in the Minecraft world that is represented by three coordinates: x, y, and z. The letter y represents height, and x and z represent horizontal positions on a flat plane.

image

Figure 2-3: 3D coordinates

If you’re using the Raspberry Pi version of the game, the player’s position is given by three numbers in the top-left corner of the game window, which you can see in Figure 2-4. If you’re using the desktop edition of the game, you can see the player’s coordinates by pressing F3 and finding the first line in the second block of text on the left, labeled XYZ, as shown in Figure 2-5.

Move your player around the game and watch the position numbers change; the coordinates should update in real time as the player walks. Pretty cool, right? But walking long distances takes a long time. Why spend so much time walking when you can change positions instantly using Python? Let’s look at how to do this.

image

Figure 2-4: The player’s position displayed in Minecraft: Pi Edition

image

Figure 2-5: The player’s position displayed in the desktop edition of Minecraft

Switch on your computer or Raspberry Pi and follow these steps:

  1. Open IDLE and click File New File (or New Window on some computers). You can see the empty text editor window in Figure 2-6. If you’re using a Raspberry Pi or have more than one version of Python installed on your computer, make sure you use Python 3, not Python 2.7.

    image

    Figure 2-6: A new text editor window in IDLE

  2. When the new window appears, click File Save As.

  3. Create a new folder called variables inside the Minecraft Python folder that you created in Chapter 1.

  4. Open the variables folder, name your file teleport.py, and click Save.

Now that you’re working in IDLE’s text editor, add the following two lines of code at the top of your program:

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

These lines connect your program to Minecraft; you’ll use them in every program that interacts with Minecraft. Next, create three integer variables called x, y, and z.

x = 10
y = 110
z = 12

These variables represent the position that you want to teleport your player to. For now, set these variables to 10, 110, and 12, as shown here.

Then enter the following line of code, which will transport the player:

mc.player.setTilePos(x, y, z)

The setTilePos() part of the program is a function, which is a prewritten and reusable piece of code. The setTilePos(x, y, z) function tells Minecraft to change the player’s position using the three variables you just set. The values inside the parentheses are called arguments. You passed the variables you just created to the function as arguments so the function can use the values of x, y, and z when it runs.

WARNING

If you’re using a Raspberry Pi, don’t use values larger than 127 or smaller than –127 for the x and z variables. The Minecraft Pi world is small, and numbers outside this range will crash the game.

Listing 2-1 contains the full code to teleport your player, which you can also see in Figure 2-7:

teleport.py

# Connect to Minecraft
   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()

   # Set x, y, and z variables to represent coordinates
   x = 10
   y = 110
   z = 12

   # Change the player's position
   mc.player.setTilePos(x, y, z)

Listing 2-1: The finished teleport code

To make this program easier to understand, I’ve included some comments . Comments are useful statements in code that describe what the code does but are ignored by Python. In other words, when you run the program, Python passes commented lines without doing anything. A single-line comment begins with a hash mark (#). My comments describe what each part of teleport.py does. It’s a good habit to write comments in your code so you can remember what the parts of your program do when you return to them later.

Figure 2-7 shows the completed program written in IDLE’s text editor.

image

Figure 2-7: The completed program in IDLE’s text editor

Now let’s run the program! Follow these steps:

  1. Open Minecraft by clicking the desktop icon.

  2. If you’re using a Raspberry Pi, click Start Game and Create a New World. If you’re using the desktop edition of Minecraft, open the game world using the instructions in “Running Spigot and Creating a Game” on page 7 for Windows and on page 16 for Mac.

  3. After the world has been generated, press the ESC key (or TAB if you’re using a Raspberry Pi) to release the mouse. You can now move the mouse outside of the Minecraft window or double-click the Minecraft window to reselect the game. Figure 2-8 shows the IDLE and Minecraft windows on my computer.

    image

    Figure 2-8: This is how I like to arrange my Minecraft and IDLE text editor windows.

  4. Click the IDLE text editor window that has your teleport.py program.

  5. Click Run Run Module or press F5. If you haven’t saved the program, IDLE will always ask if you want to save before running. Click OK to save the program. If you click Cancel, the program won’t run.

NOTE

When you’re running programs from IDLE on a Raspberry Pi, a dialog asking you to save your program might appear and hide itself behind the Minecraft window. If you think IDLE has frozen, it might be that the dialog is hiding. Just minimize the Minecraft window and click OK in the IDLE dialog. After clicking OK, maximize the Minecraft window.

Well done! Your program should now run, and after a few seconds, your player should be teleported to coordinates (10, 110, 12), as shown in Figure 2-9. Your world isn’t the same as mine, so you’ll see some differences when you run it on your computer.

image

Figure 2-9: I’ve teleported from my house to position (10, 110, 12), which is above a swamp. Look out below!

FLOATS

Not all numbers are whole numbers. Decimal points are used to represent values that can’t be described with whole numbers. For example, you might have half (0.5) of an apple. Numbers that use decimal points are called floating point numbers, or floats. This is another data type that Python uses. Floating point numbers are used instead of integers when you want to be more precise. Floats can also represent whole numbers (as in 3.0), but integers can’t represent numbers with decimal places.

You might have noticed that your player’s position coordinates (as shown in Figures 2-4 and 2-5) include decimals, which means they’re floats!

In Python, you declare a float variable in the same way that you declare an integer variable. For example, to set the variable x to 1.34, you’d write this:

>>> x = 1.34

To create a negative float, put a minus sign (-) before the value:

>>> x = -1.34

In the next mission, you’ll gain even more control over your teleportation powers by using floats to teleport the player to precise locations.

MISSION #2: GO EXACTLY WHERE YOU WANT

You learned how to set the player’s position using integers, but you can set the player’s position more accurately if you use floats. In this mission, we’ll revise the program from Mission #1 to teleport the player using a float value:

  1. In IDLE, open the teleport.py program (page 34) by clicking File Open and selecting the file from your variables folder.

  2. Save a copy of the program as teleportPrecise.py in your variables folder.

  3. In the teleportPrecise.py file, change the x, y, and z variables to use floats instead of integers. That is, change the values of x, y, and z from 10, 110, and 12 to 10.0, 110.0, and 12.0.

  4. Change the last line of code to mc.player.setPos(x, y, z) by removing the word Tile.

  5. Save the program.

  6. Open a Minecraft world and run the code.

The final result should look like this:

teleportPrecise.py

# Connect to Minecraft
from mcpi.minecraft import Minecraft
mc = Minecraft.create()

# Set x, y, and z variables to represent coordinates
x = 10.0
y = 110.0
z = 12.0

# Change the player's position
mc.player.setPos(x, y, z)

Notice the difference between mc.player.setPos(x, y, z), used here, and mc.player.setTilePos(x, y, z), used in Listing 2-1. The setTilePos() function uses integers to tell the game the position of the block that you want to teleport to. The setPos() function is a little different—it uses floats to tell the game the position of the block as well as the precise position on that block that you want to teleport to. Using my program, I teleported to the top of my tower, as shown in Figure 2-10.

image

Figure 2-10: I’ve teleported myself to the top of my tower, using floats to be very precise.

SLOWING DOWN TELEPORTATION USING THE TIME MODULE

Python runs your code as fast as possible. But you can slow down the action by making your programs wait a certain number of seconds before continuing.

To use time in your programs, you need the time module, which contains a set of prewritten functions relating to time. To use the time module, add the following line of code to the top of your programs:

import time

Order is very important when you’re using the time module and the sleep() function, which is part of the time module. The sleep() function will make a program wait a specified number of seconds before continuing. You must always import the time module before you use the sleep() function. If you don’t, Python won’t be able to find the sleep() function and will be so confused that it will stop your program from running. This is why it’s best to import any module you use at the top of your code. All of your import statements will be grouped together at the top of the program. For example, I usually include the lines of code to connect to Minecraft first, and then add the import time statement on the third line.

Here is an example of how to use the sleep() function:

time.sleep(5)

This line of code pauses your program for five seconds. You can use any number, including integers and floats, as the following example shows:

time.sleep(0.2)

When your program reaches this line of code, it will wait 0.2 seconds. Now that you can control the flow of time, you’re ready for the next mission!

MISSION #3: TELEPORTATION TOUR

The beauty of teleportation in Minecraft is that you can send your player anywhere. Using all the skills you’ve learned so far, you’ll send your player on an automated tour of your entire Minecraft world!

In this mission, you’ll practice changing the values of variables by modifying the code from Mission #1 (page 31) to teleport the player to several locations across the map. The player will teleport to one location, wait a few seconds, and then teleport to another location.

  1. In IDLE, open the teleport.py program (page 34) by clicking File Open and selecting the file from your variables folder.

  2. Save a copy of the program as tour.py in your variables folder.

  3. Just after the code that connects your program to Minecraft, add import time.

  4. At the end of the program, add time.sleep(10).

  5. Copy the lines with the x, y, and z variables and the setTilePos() function and paste them at the end of the program, so those lines appear twice.

  6. Change the values of both sets of x, y, and z variables to any numbers you want. You can find the coordinates for any position in your game by moving there and writing down the player’s coordinates like you did earlier in this chapter.

  7. Save the program.

  8. Open a Minecraft world and run the code.

The final result should look like this, with new coordinates filled in:

tour.py

# Connect to Minecraft
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
import time

# Set x, y, and z variables to represent coordinates
x = # Fill in
y = # Fill in
z = # Fill in

# Change the player's position
mc.player.setTilePos(x, y, z)

# Wait 10 seconds
time.sleep(10)

# Set x, y, and z variables to represent coordinates
x = # Fill in
y = # Fill in
z = # Fill in

# Change the player's position
mc.player.setTilePos(x, y, z)

The player should teleport to the first location, wait 10 seconds, and then teleport to the second location, as shown in Figure 2-11.

image

Figure 2-11: I’ve set the coordinates in my program to teleport to my house and then to teleport to the desert.

DEBUGGING

Everyone makes mistakes; often, even the best programmers don’t get their code right the first time. Writing a program that works is just one skill that a good programmer needs. Fixing programs when they don’t work is another essential skill. This process is called debugging, and each problem in a misbehaving program is called a bug. In this section, you’ll learn tips and tricks to fix all your future programs.

Bugs can completely stop a program from running, or they can make the program behave in an unexpected way. When a program doesn’t run, Python will show you an error message, such as the one in Figure 2-12.

image

Figure 2-12: Python gives me an error message because I didn’t stick to Python’s syntax.

In Figure 2-12 you can see that I’ve entered some code in the Python shell, and it has returned an error message. A lot of information is displayed in the error message, but based on the last line (NameError: name 'x' is not defined) I can tell that something is wrong with my x variable. Specifically, the x variable has not been defined. To fix this, I need to add an extra line of code that defines the x variable, like so:

>>> x = 10

This line will fix the error message, but it doesn’t mean all errors will be fixed.

Bugs that allow the program to run but cause it to behave strangely won’t show an error message, but you’ll know something is wrong when your program produces an unexpected result. For example, if you forget to write a line of code in your teleportation programs, such as setTilePos(), the program will run without any errors, but the player won’t change position. That’s not a very useful teleportation program!

WARNING

Typos are among the most common causes of bugs. Spelling something in a way the computer doesn’t expect can stop your program from running. Be careful, and make sure your spelling and capitalization are correct!

MISSION #4: FIX THE BUGGY TELEPORTATION

In this mission, you’ll debug two programs. The first program, Listing 2-2, is similar to teleport.py (page 34), but this version has five mistakes. Open a new file in the IDLE text editor, copy Listing 2-2 into it, and save it as teleportBug1.py.

teleportBug1.py

from mcpi.minceraft inport Minecraft
# mc = Minecraft.create()

x = 10
  y = 11
z = 12

Listing 2-2: A broken version of the teleport program

To debug this program, complete the following steps:

  1. Run teleportBug1.py.

  2. When you get an error message, read the last line for a hint about what’s wrong.

  3. Correct the bug and run the code again.

  4. Keep correcting the bugs until the program teleports the player to a new location.

HINT

Don’t forget to double-check that you’re actually calling the setTilePos() function!

Let’s try debugging another program. The version of teleport.py in Listing 2-3 runs, but for some reason, the player doesn’t teleport to the specified position. Copy Listing 2-3 into an IDLE file and save it as teleportBug2.py.

teleportBug2.py

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

x = 10
y = 110
z = -12

mc.player.setPos(x, z, y)

Listing 2-3: The teleport program with bugs

Unlike with teleportBug1.py, you won’t get any error messages when you run the program. To fix this program, you’ll need to read the code until you find the mistake. The program should teleport the player to position (10, 110, –12). Run the program and check the coordinates that the player has teleported to. This might help you debug the program and identify the problem with it.

When you’ve squashed all the bugs in these two programs, add a comment to each to explain what the problems were. Jotting down problems you encounter in debugging can help you remember to watch out for similar bugs in the future.

WHAT YOU LEARNED

Congratulations! You’ve written your first Python programs to control a Minecraft player through the power of variables and functions. You explored two data types (integers and floats), controlled time, and debugged broken programs. You also learned two useful functions specific to the Minecraft Python API: setPos() and setTilePos().

In Chapter 3, you’ll master the art of speed building in Minecraft, using mathematical operations and functions that set blocks!

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

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