Hardware Reference
In-Depth Information
2. Now you need to import a new module that allows you to insert time delays. You
do this because if you don't slow down the loop, you will be bombarded with a
flood of messages on the chat and won't be able to see what you are doing. Add
the following bold line to your existing program:
import mcpi.minecraft as minecraft
import time
3. Next, modify the main part of your program by adding the lines that are marked
in bold in the following, noting that you have to indent the lines beneath while
True to tell Python which instructions it needs to repeat. See the Digging into
the Code section to understand why this indent is needed:
while True:
time.sleep(1)
pos = mc.player.getTilePos()
mc.postToChat("x="+str(pos.x) +" y="+str(pos.y) +
" z="+str(pos.z))
4. Choose File Save from the editor menu to save your changes.
5. Now you can run your program by choosing Run Run Module from the editor
menu. Have a walk around the Minecraft world and notice that, once every sec-
ond, you will see the coordinates of your player posted to the chat.
DIGGING INTO THE CODE
Indentation is extremely important in all programming languages, as it shows
how the program is structured and which groups of statements belong with
other statements. Indentation is even more important in the Python program-
ming language, because it is used by Python to understand the meaning of your
program (unlike other languages such as C that use { } braces to group state-
ments together). Indentation is important when you use while loops and other
statements, as it shows which of these belong to the loop and will therefore be
repeated over and over again. In your game loop, all the program statements
underneath while True: are indented, because they belong to the loop and
will be repeated each time round the loop.
In this example, you can see that the “hello” is printed once but the word “tick”
is then printed once every second. time.sleep() and print() belong to the
loop because they are indented:
print("hello")
while True: # this is the start of the loop
time.sleep(1)
print("tick")
 
Search WWH ::




Custom Search