Hardware Reference
In-Depth Information
1. Start a new file with File New File and then save it as tipChat.py .
2. Import the necessary modules:
import mcpi.minecraft as minecraft
import time
import random
3. Connect to the Minecraft game:
mc = minecraft.Minecraft.create()
4. Set a constant for the filename, so that you can easily change it to read a differ-
ent file later:
FILENAME = "tips.txt"
5. Open the file in read mode (see the following Digging into the Code for a fuller
explanation of this line):
f = open(FILENAME, "r")
6. Read all the lines of the file into a list called tips . Remember that you have already
used lists in Adventure 4 (magic bridge builder) and Adventure 5 (electronics):
tips = f.readlines()
7. Close the file when you have finished with it. It is good practice to always close a
file when you have finished with it, because when the file is open it cannot be
used by other programs, such as the editor you used to enter the text into the file
in the first place:
f.close()
8. Now write a game loop that waits a random length of time between three and
seven seconds:
while True:
time.sleep(random.randint(3,7))
9. Now tell the program to choose a random message from the tips list and dis-
play it on the chat. You need to use the strip() function, in order to strip out
unwanted newline characters. You'll be looking at newline characters later on, so
don't worry too much about understanding this for now.
msg = random.choice(tips)
mc.postToChat(msg.strip())
Save and run your program. What happens? As you walk around the Minecraft world
and play your game, every so often a tip pops up on the chat, just like in Figure 6-1.
Note how the Minecraft chat builds up messages on the screen, and gradually they will
disappear over time.
 
Search WWH ::




Custom Search