4
CHATTING WITH STRINGS

image

In Chapters 2 and 3, you worked with integers and floats, which are both number types. In this chapter, you’ll use another data type called strings. You can use strings to work with letters and symbols as well as numbers.

Strings help you display data to people using your programs—an important part of programming. Using strings, you can to tell Python to output data to the screen, which displays and communicates information to the user.

With Minecraft you can use strings in various places, such as posting messages to the chat, which is a way of communicating with other players when you are in multiplayer mode. Although posting messages is a standard feature in other versions of Minecraft, it is a hidden feature in the Raspberry Pi version. But you can access this feature through the power of programming. You’ll be able to share secret information with your friends and brag about your treasures!

You’ll also learn about functions in this chapter. If you are eagle-eyed, you’ll notice that you’ve seen some functions already. setPos(), setTilePos(), setBlock(), setBlocks(), getPos(), and getTilePos() are all functions—reusable blocks of code that make it easier for you to complete tasks. Pretty cool, huh?

In this chapter’s missions, you’ll build on the knowledge you’ve learned so far. You’ll print messages to the Minecraft chat using strings and practice inputting data to create objects in your Minecraft world.

WHAT ARE STRINGS?

A string data type includes any amount of text, from a single letter or symbol—like "a" or "&"—to a large block of text. Each letter, number, or symbol in a string is called a character. When you want to include letters, symbols, words, sentences, or a combination of these things in your program, you use strings.

With the string data type, you can store letters, numbers, and symbols. All strings are enclosed in quotation marks. For example, this is a string:

"Look out! There's a zombie behind you!"

The following is also a string:

'Welcome to my secret base!'

Did you catch the slight difference in the way these examples are written? When writing a string, you can use either single or double quotation marks: ' or ". Be careful not to mix quotation marks! If you start a string with a single quote, you must end it with a single quote. If you start with a double quote, end with a double quote. There is a good reason for including both of these options in the Python programming language; for example, if you want to use an apostrophe in your string, you can safely include it if you enclose your string in double quotes.

THE PRINT() FUNCTION

Displaying text and other information to the user is important for user interaction; otherwise, the user won’t know what’s going on in your programs. The information you display to the user is called output. To output data to the user’s screen, you use the print() function.

To output a message, pass a string to the print() function as an argument:

>>> print("String")

This tells Python that you want to display the word String to the user. So to print chocolate to the Python shell, you write:

>>> print("chocolate")

And that output would be:

chocolate

You can also use print() to print the values of variables. For example, if you have a variable called name that stores a name as a string, and you want to display it to the screen, you can do this:

>>> name = "Steve the Miner"

After you store the string "Steve the Miner" in name, you can simply write print(name) to display this output:

>>> print(name)
Steve the Miner

Now that you know the basics of strings, complete the mission to say hello to your Minecraft world!

MISSION #11: HELLO, MINECRAFT WORLD

If you want to chat with other players in Minecraft Pi, the Minecraft Python API lets you send messages to the chat using the postToChat() function. The postToChat() function takes a string as an argument and posts that string to the Minecraft chat window. For example, Listing 4-1 posts "Hello, Minecraft World" to the chat.

message.py

from mcpi.minecraft import Minecraft
mc = Minecraft.create()
mc.postToChat("Hello, Minecraft World")

Listing 4-1: Use Python to send a greeting over Minecraft chat.

Recall that an argument is information that you pass to a function when you call the function. The function needs this information in order to do its job. For example, in the previous chapter, we needed to pass numbers to our functions to define what we wanted them to do. In this case, postToChat() needs a string, such as "Hello, Minecraft World".

The postToChat() function is similar to the print() function. Both can show strings on the screen, and both can take a variable that stores a string as an argument. The difference is that the print() function outputs strings to the Python shell while postToChat() displays the output in the Minecraft chat.

Copy the code from Listing 4-1 and save it as message.py in a new folder called strings. When you run the program, you should see the message posted to chat, as shown in Figure 4-1.

image

Figure 4-1: My message was posted in the chat.

Try passing a different string to postToChat() to make it display a different chat message.

THE INPUT() FUNCTION

So far, all of your variables have been set in your programs, or hardcoded. To change the value of a variable, you’d have to edit the program. It would be handy to be able to change these variables while the program is running or accept user input from the player.

One way of adding this kind of interactivity to your program is by using the input() function. It prints a string to the console (to tell the user what kind of information they should enter) and then waits for the user to type a response. Try entering this code into the Python shell to see what happens:

>>> input("What is your name? ")

You’ll see the string that you passed to input(), and you’ll be able to type in a response.

What is your name?

When you enter a response, you should see something like this:

What is your name? Craig
'Craig'

Neat! But if you want to use this input somewhere in your program, you’ll have to save it to a variable. Unlike the Python shell, programs created in the text editor do not automatically output the results of statements. For example:

>>> name = input("What is your name? ")
What is your name? Craig

Notice how this time after you type in your name and press ENTER, the program doesn’t automatically display your input. To see the saved input, just pass the variable name as an argument to the print() function:

>>> print(name)
Craig

Awesome! Now you’ve stored your input in a variable and printed the variable’s value. This is very handy because it lets you get input from the user to use anywhere in your program. Let’s use this technique to write chat messages to the Minecraft chat!

MISSION #12: WRITE YOUR OWN CHAT MESSAGE

Let’s make the chat more interactive! You can use the Python shell to write a message in Minecraft chat, as you did in Mission #11. In this mission, we’ll write a slightly different program that saves the string you want to post to the chat in a variable named message.

Listing 4-2 will get you started. Copy it into a new file in IDLE and save it as messageInput.py in your strings folder.

messageInput.py

   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()
message = "This is the default message."
mc.postToChat(message)

Listing 4-2: How to output strings to Minecraft’s chat

The program stores the message you want to output to chat in the variable message . In this case, the variable is a string that says "This is the default message." Then the program passes message to the postToChat() function , which outputs the string to the Minecraft chat.

In this program, the string is hardcoded, meaning it will be the same every time the program runs. But with a single change, you can make it print whatever the user writes! In other words, you can write your own custom messages every time you run the program. You’ll create your very own chat program.

To make the program accept input, replace the string "This is the default message." with the input() function. Give the input() function an argument, such as "Enter your message: ". Remember to put this string inside the input() function’s parentheses! After you’ve made the changes to the program, run it. You should see a prompt in the Python shell displaying "Enter your message: ". Enter your message and press ENTER. The message displays in the shell and in the Minecraft chat, as shown in Figure 4-2.

image

Figure 4-2: When I enter a message in the IDLE shell, it’s posted to Minecraft’s chat.

Now your program lets you write a message to display to chat, instead of you having to write the message in your program. See how much easier it is to chat using input?

JOINING STRINGS

Often, you’ll need to print a combination of strings. This is called joining, or concatenating, strings, and Python makes it easy.

In Chapter 3 we used the addition operator (+) to add numbers, but you can also use it to concatenate strings. For example:

firstName = "Charles"
lastName = "Christopher"
print(firstName + lastName)

The output of print() will be "CharlesChristopher". If you want a space character between the values, you can add a space by using the addition operator like this:

print(firstName + " " + lastName)

Python often provides multiple ways to achieve the same result. In this case, you could use a comma to create the space instead:

print(firstName, lastName)

Both of these statements will output "Charles Christopher". You can concatenate hardcoded strings with variables that happen to be strings too. Just write the value like you would write any other string:

print("His name is " + firstName + " " + lastName)

This will output "His name is Charles Christopher".

Putting together blocks of text is useful, but sometimes you’ll want to join strings to another data type, like an integer. Python will not let you concatenate a string with an integer; in this case, you need to tell Python to first convert the integer to a string. Let’s try it.

CONVERTING NUMBERS TO STRINGS

Converting one variable type to another is handy. For example, imagine you store the number of golden apples you have, which is an integer, in a variable called myGoldenApples. You want to brag to your friends about how many golden apples you have, because they’re rare and you like to brag. You could print a message like "My not-so-secret golden apple stash: ", followed by the value stored in myGoldenApples. But before you can include the value of myGoldenApples in the printed message, you have to tell Python to change the integer in myGoldenApples to a string.

The str() function converts non-string data types, like integers and floats, into strings. To convert to a string, put the value you want to convert inside the parentheses of the str() function.

Let’s go back to your golden apple stash. Say you’ve set myGoldenApples to 2, and you want Python to treat that 2 as a string instead of an integer. Here’s how you’d print your message:

print("My not-so-secret golden apple stash: " + str(myGoldenApples))

This statement outputs the string "My not-so-secret golden apple stash: 2".

You can convert floats to strings as well. Say you ate half a golden apple, and now myGoldenApples stores 1.5 apples. str(myGoldenApples) works the same on the 1.5 as it did on the 2. It converts 1.5 to a string so you can include it in your message.

After you’ve converted numbers to strings, you can concatenate them however you like. Let’s have some fun turning numbers into strings and concatenating them!

CONCATENATING INTEGERS AND FLOATS

If you want to concatenate two pieces of data, they must be strings. But the plus sign is used for both addition and concatenation, so if you’re concatenating integers, floats, and other numbers, Python will try to add them instead. You must change number values to strings in order to join them using concatenation.

To join two numbers instead of adding them, just use the str() method:

print(str(19) + str(84))

Because you told Python to treat the numbers 19 and 84 as strings and concatenate them, this statement outputs 1984 instead of 103, the sum of 19 and 84.

You can use concatenation as many times as you want within a statement. For example:

print("The year is " + str(19) + str(84))

This line of code outputs The year is 1984.

Now that you have a bit of practice using concatenation, let’s put your new skills to the test in the next mission!

MISSION #13: ADD USERNAMES TO CHAT

When you’re playing a game with more than two people, it can be confusing to figure out who is writing a message in Minecraft chat. The obvious solution is to include the user’s name at the start of their message. In this mission, you’ll modify the program from Mission #12 to include a username for all messages sent to chat.

Open messageInput.py in IDLE and save it as a new file called userChat.py in the strings folder. Then add code to take in the user’s name as input before taking in their message. The message posted to chat should be in the following format: "Anna: I need TNT." You’ll need to use concatenation to accomplish this mission.

In the program, find this line of code:

message = input("Enter your message: ")

On the line above it, you need to add another variable called username and set its value to input("Please enter a username: "). After you’ve added the username variable, find this line:

mc.postToChat(message)

Using concatenation, join the username and message strings inside the postToChat() function. Add ": " between the two strings so the output has a colon and a space between the username variable and the message variable. Figure 4-3 shows what the output of the finished program should look like.

image

Figure 4-3: Now when I post to chat using my program, it displays my username.

Save your updated program and run it. In the Python shell you will be asked to enter a username. Type your name and press ENTER. Then you’ll be prompted to write a message, so do that as well. Your username and message should be displayed in Minecraft chat.

CONVERTING STRINGS TO INTEGERS WITH INT()

Like the str() function, which converts non-string data types into strings, the int() function converts non-integer data types into integers.

The int() function is useful when used with the input() function. The input() function returns the user input as a string, but you’ll often want to use this input in math operations. To do that, you’ll first have to convert the input to an integer type using int().

Here’s how it works. Suppose we have already assigned an integer value to a variable called cansOfTunaPerCat, and we want a program that tells us how much tuna gets eaten, depending on the number of cats the user has. Here’s an example of a program we could write:

cansOfTunaPerCat = 4
cats = input("How many cats do you have? ")
cats = int(cats)
dailyTunaEaten = cats * cansOfTunaPerCat

You can do the same thing in a single line by putting one function inside the other:

cats = int(input("How many cats do you have? "))
dailyTunaEaten = cats * cansOfTunaPerCat

Now that you know how to convert input into an integer, you can use it to input block types into Minecraft programs.

MISSION #14: CREATE A BLOCK WITH INPUT

There are tons of block types in Minecraft. Although you can choose lots of blocks in creative mode, many others cannot be used. However, the Python API for Minecraft gives you access to all of the block types and lets you set them using the setBlocks() function.

You’ve used the setBlocks() function before, but you had to hardcode the block type into your program. This means you couldn’t change it while your program was running. Now you can use the input() function. By writing a program that accepts input, every time you run the program you can choose the type of block you want to create. You could create a wool block the first time you run the program, then create iron ore the second time.

In this mission, you’ll write a program that lets your user decide which kind of block they want to set. Copy Listing 4-3 into a new file and save it as blockInput.py in your strings folder.

blockInput.py

   from mcpi.minecraft import Minecraft
   mc = Minecraft.create()
blockType = # Add input() function here
   pos = mc.player.getTilePos()
   x = pos.x
   y = pos.y
   z = pos.z
   mc.setBlock(x, y, z, blockType)

Listing 4-3: Code to set a block at the player’s position

This program sets a block at the player’s current position. Change it so the blockType variable is set using the input() function . I suggest including a question or other text prompt so the user knows to type a block number, not some other kind of input. If you don’t include a prompt, IDLE will just wait on a blank line until the user enters something, and you want to make it clear that the program needs a number from the user.

Recall that input() returns your input as a string, and in order for it to input the value as an integer, you need to use the int() function. The expression to collect input for the block type should look like this:

blockType = int(input("Enter a block type: "))

Save your modified program, run it, and enter any block number you like. Figure 4-4 shows the result of the program.

image

Figure 4-4: I can now create whichever block I want!

BOUNCE BACK FROM ERRORS

Python uses exception handling to make sure your program can recover from errors and continue running when they occur. For example, exception handling is one way to manage incorrect user input.

Say your program requested an integer, but the user entered a string. Normally, the program would display an error message, which is also called throwing an exception, and then stop running.

With exception handling, you can manage that error yourself: you can keep the program running smoothly, display a useful error message to the user—such as "Please enter a number instead"—and give them a chance to fix their problem without restarting the program.

A try-except statement is one tool you can use to handle errors. It is particularly good for providing useful feedback to the user when they enter incorrect input, and it can prevent your program from stopping when an error occurs.

The statement is made up of two parts: the try and the except. The first part, try, is the code you want to run if no errors occur. This code might take input or print a string. The except part of the statement will run only if an error occurs in the try part.

Imagine a bit of code that asks you how many pairs of sunglasses you own (I own three pairs):

   try:
     noOfSunglasses = int(input("How many sunglasses do you own? "))
   except:
     print("Invalid input: please enter a number")

This program requires a number. If you enter letters or symbols, it will print "Invalid input: please enter a number". The error occurs because the int() function can only convert strings that contain only integers . If you enter a number, the code will work, but if you enter something that isn’t a number, like many sunglasses, this input will cause an error in the int() function.

By the way, did you notice anything different about this bit of code? It is our first time using a statement that calls for indentation, which is when you type several spaces before typing any text. I’ll discuss indentation more when I cover if statements in Chapter 6 and for loops in Chapters 7 and 9. For now, just make sure you type your code exactly as it appears in this book.

Usually when an error occurs, Python shows a message that is difficult to understand and doesn’t clearly tell the user how to fix the problem. But with try-except, you can stop Python’s error messages from being displayed to the user when they enter the wrong type of data; instead, you can give the user simple, helpful instructions on what to do. Sometimes the user will just press ENTER instead of entering input. Normally, this creates an error, but with the code inside the try-except statement , the string "Invalid input: please enter a number" will be printed instead .

You can put almost any code inside a try-except statement, even other try-except statements. Try it out in the next mission!

MISSION #15: ONLY NUMBERS ALLOWED

Remember the program you wrote in Mission #14? When you entered an integer value, the program worked exactly as it was supposed to and created a block. But if you entered a string, the program would stop working and show an error, as shown in Figure 4-5.

image

Figure 4-5: cake is not a number, so the program did not create a block.

This error message makes sense when you’re used to Python. But what if someone who had never used Python before tried to enter a string instead of an integer? They’d get an error message they wouldn’t understand. Your mission is to use error handling to write a message that’s easy to understand.

Open the program blockInput.py that you created in Mission #14. Save the program as blockInputFix.py in the strings folder.

You’ll change the program so it uses a try-except statement when it asks for a block number. Find the last line of code in the program. It should look like this:

mc.setBlock(x, y, z, blockType)

Add a try statement on the line above this one and add four spaces at the start of the line before the mc.setBlock() function. Next, on the line above setBlock(), add this code to get an input from the user: blockType = int(input("Enter a block type: ")).

Then, on the line just after the setBlock() function, write an except statement. Inside the except statement add a line of code that posts a message to the Minecraft chat to say that the block type must be a number; for example, "You didn't enter a number! Enter a number next time.". Here’s what the changed code should look like (notice the four spaces, or indentation, at the start of lines and ):

   try:
     blockType = int(input("Enter a block type: "))
       mc.setBlock(x, y, z, blockType)
   except:
     mc.postToChat("You did not enter a number! Enter a number next time.")

The int() function expects to convert the input entered by the user into an integer . Because we’ve added the try-except statement to the program, if the user enters input that contains something that isn’t a number (such as letters or symbols), an error will occur. Instead of displaying the normal Python error message, the program will output a string to the chat asking the user to enter only a number . You might want to change the chat message so it’s a bit more polite!

When you’re finished entering a friendlier error message, save the blockInputFix.py file, and run it to admire your handiwork. The result should look something like Figure 4-6.

image

Figure 4-6: The error message shown in the chat is much easier to understand.

MISSION #16: SPRINT RECORD

This chapter’s final mission combines everything you’ve learned about variables (Chapter 2) and math operators (Chapter 3) with posting messages to the chat. Your task is to create a record keeper: the program will work out how far the player travels in 10 seconds and display the results in the chat.

Remember that you can use the following code to make your programs wait, or sleep, a certain number of seconds:

import time     # Place this somewhere near the top of your program
time.sleep(30)  # Makes the program wait 30 seconds

Use this sleep() example and type in the following code to get started with this new program:

sprint.py

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

pos1 = mc.player.getTilePos()
   x1 = pos1.x
   y1 = pos1.y
   z1 = pos1.z

   time.sleep(10)

pos2 = mc.player.getTilePos()
   x2 = pos2.x
   y2 = pos2.y
   z2 = pos2.z

   # Compare the difference between the starting position and ending position
xDistance = x2 – x1
   yDistance =
   zDistance =

   # Post the results to the chat
mc.postToChat("")

Let’s break down this code. The program gets the player’s starting position , waits 10 seconds, and then gets the player’s finishing position at . To finish the program, you need to work out the difference between the starting and finishing positions. To do this, set the values of the yDistance and zDistance variables, which start at . To help you out, I’ve included the value of the xDistance variable, which should be x2 – x1. The values of the yDistance and zDistance variables should be similar to this, but use different variables instead of x1 and x2.

On the last line, output the results to the Minecraft chat . The results should be in the following format: "The player has moved x: 10, y: 6, and z: -3". Use strings, concatenation, and the values of xDistance, yDistance, and zDistance variables to do this.

Save this program in the strings folder as sprint.py and run it. Figure 4-7 shows the result of the program.

image

Figure 4-7: The distance I traveled is displayed when the program finishes.

If you have the program running but you’re finding it difficult to switch between the command line and Minecraft fast enough, try adding a three-second countdown before step 2. Post this countdown to the chat.

WHAT YOU LEARNED

Congratulations! You’ve learned a lot in this chapter. You created strings, displayed strings using print statements, and joined them using concatenation. You wrote programs that accept user input, changed the data types of values, and handled exceptions. Along the way, you applied your Python knowledge to make your Minecraft chat more lively.

In Chapter 5, you’ll learn how to control the flow of the program and tell your programs how to make decisions.

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

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