Hack the chat
Python Minecraft - Lesson 1
Objectives
- To set up a Raspberry Pi computer with some assistance
- To begin to use a text based programming language
- To compare text and block based programming languages
- To use logical reasoning to debug errors in a program
Lesson Resources
Lesson 1 - Hack the chat
Lesson 2 - Debugging challenges
Lesson 3 - Using 3D coordinates
Lesson 4 - Setting Blocks
Lesson 5 - Setting Block Challenges
Lesson 6 - Going loopy
Introduction
We want to help you develop an understanding of a written programming language using an environment you know and love… Minecraft!
While not essential, we find the lessons work best in longer sessions due to the time needed for setting up and packing away the equipment. So, for example, you might teach it in three full afternoons rather than six individual lessons.
The Raspberry Pi is a stripped back computer, and Minecraft Pi is a stripped back version of the original game. You can only enter creative mode, but this is not a bad thing. Minecraft Pi has been designed to allow us to edit/create/hack the Minecraft world using a variety of coding languages. This unit focuses on a coding language called Python.
Using Python, we will be able to control the Minecraft world by writing code and running it. Things that take a long time, or are impossible in other versions of Minecraft, can be done very quickly using the examples provided in this unit.
We have found inspiration in a number of places to support this. Craig Richardson’s Code Academy book “Python Programming: Minecraft Pi” and Code Academy is an excellent detailed resource. We have also found articles from Magazines such as Raspberry Pi geek, The Mag-Pi and “Raspberry Pi Projects For Kids”, really helpful. We have also used a number of fantastic websites , all of which have helped us understand the capabilities of Minecraft Pi. Our hope for this unit is for it to be used in the classroom. As such we have also used the work of Mark Clarkson and his brilliant “Introduction to Python” to help secure a sound programming pedagogy.
We hope that we have produced an easy to follow guide that develops an understanding of a range of Computer Science concepts using fun activities.
Setting up the computer
Before we can do any coding the Raspberry Pi computer needs setting up. It’s great if the students can do this themselves (with some guidance) to give them a better idea of the parts of a computer and the Raspberry Pi’s various sockets. If they have completed our previous Raspberry Pi unit, they should have done this before and have some familiarity with the parts of the computer. But briefly recap these to begin with.
(please note there are different models of the Raspberry Pi available. We’ve included the two most commonly used models in school here):
- USB Sockets (2 on the model B, 4 on the model B+) - Ask What goes in a USB socket? - Keyboards, mice, game pads, phone chargers, printers, scanners, cameras, storage devices ... the list goes on. They are useful as USBs allow both data and electricity to travel through them.
- Ethernet socket - Wired network cables go here for networking and internet access
- Audio/Sound out - Like any 3.5mm headphone or speaker jack
- HDMI - A video output for you to connect your Pi to a screen. Many students are familiar with these from their own TVs and games consoles at home.
- Micro USB - Like many phone and device chargers these days, this provides power. You can get Micro USB cables that have a regular plug on the end, the cable in the box for this has a normal USB plug at the other end and can be plugged into the USB socket on a PC (that is turned on) to get its power for the Pi that way.
- SD/Micro SD card slot - This is the Pi’s hard drive. It contains the entire operating system, files and software programs for the Pi, as a result it’s pretty essential and the Pi won't work without it!
- GPIO Pins - GPIO stands for General Purpose Input Output. These are pins to which we can connect wires, that in turn can connect to other things such as LEDs and motors.
First connect a keyboard and mouse to available USB sockets on the Raspberry Pi. Ensure the SD card or micro SD is also correctly inserted into the Raspberry Pi.
Next, the kit comes with a HDMI to DVI cable, this is used to connect the Raspberry Pi directly to your monitor if it has a DVI connection available. Not all monitors will have a DVI input, Some older monitors will only have VGA inputs which are not compatible with the Pi. DVI to VGA converters do not usually work either as they do not successfully convert the digital video signal (DVI) to an analog signal (VGA).
If your monitors have HDMI (but no DVI) inputs then it is possible to connect your Pi with these instead, but you will need to purchase HDMI to HDMI cables for each Pi.
Possible monitor input connections
If you do have a DVI input, connect the cable from the HDMI port on the Pi to the monitor and then connect the power cable from the micro USB end on the Pi to any available USB socket on a nearby computer (USB wall plug adapters, like most phone chargers, will also work fine if they have a 5v output, if you don’t have other computers available). Turn on the connected computer or wall socket and the Pi should begin to boot up. Wait for all the white text to stop loading on the screen until login info is requested and then follow the instructions below.
Logging in
There are three steps to logging in (this can also be found on p.6 of their BuildIT book)
- Login = root (and press ENTER)
- Password = password (and press ENTER) - Note it won’t show on the screen as you type it, wait for a bit more text to load and then...
- Type startx (and press ENTER)
You’ll then see a white screen showing the BuildIT logo:
If the students make any mistakes don’t worry, it’ll just ask them to try again from the Login step.
Arranging your windows
In order to get started there are a couple of fundamentals you need to be aware of. Firstly we are going to work with multiple windows open on our screen. The screen on your monitor will look a little like the image below. Once you are confident in your abilities, you can rearrange it any way you like, but this is the way we like to organise our screen:
Our preferred desktop layout for coding with Python and Minecraft Pi edition.
The 3 windows we need to open are as follows:
1) Minecraft
If we are going to be playing around with Minecraft worlds, we need to see them right? So the first window we need open is a Minecraft world. This will allow us to see the effect our programs have.
Go to the bottom of the screen and select the Minecraft icon.
Double click on the minecraft-pi icon
Select “execute” to open the program.
Start the game.
Then create a new world.
You can press the ESCAPE key to pause and leave the Minecraft window at any time or press the TAB key to just release the mouse cursor from Minecraft so you can click on other windows on your desktop.
2) Python Shell
The Python shell is the first window we see when we open up the Python programming environment (IDLE). This window will tell you if there are any bugs in your code (it’s really useful).
Click the monitor icon in the top left of the screen,
Hover over “Programming”,
Select “IDLE”
3) A New Python Program Window
IDLE stands for Integrated Development and Learning Environment. This is where we will create, edit, save and run our python files.
From the Python shell, select “File” , then select “New Window”
We will need to reposition and resize our screens so they match the layout below, so spend a little bit of time adjusting your screen. Each window can be resized from the corners and moved from the top middle of its title bar. It should look a bit like this when you’re all set up:
Our preferred desktop layout for hacking Minecraft Pi edition.
IMPORTANT - When you have created a new file in IDLE you MUST save it to the “mcpi” folder. If you don’t, the program can’t access the correct files to hack Minecraft and it won’t work!
In the new ‘Untitled’ file you have created click ‘File’ > ‘Save as’
Browse for the MCPI folder, open it and save your file in that location with your name(s) or something else appropriate.
Once your file has been saved, you need to execute the files using the “Run” command in Python, but remember to save your work first!!!
Image 6: Running your Python file.
When you “Run” your file it will connect to your current Minecraft game, run the python code and do what you have told it to. But remember, if your program is written incorrectly, the computer will execute what it says regardless, so be sure to check your code.
If you get an error message at any point in the Python Shell, this is good! It helps you debug your program, so read it and use it!
Getting moving
So now we know how to set up our screens, let’s have a look at the Minecraft world we are going to edit and how to get around it.
If you’re not familiar with playing the game yourself knowing the controls helps, so here they are; a combination of mouse and keyboard inputs:
Give the students a few minutes to have a look around the world that has been created and to get used to the controls.
Challenge 1 - Having a Chat
Let’s get coding!!! We’re going to start our coding adventure by hacking the chat pane.
Remember to set your screen up as we described on Page 3, with the Minecraft window, Python Shell and New Window open
Type the following code on lines 1 to 6 into your new window:
Once typed you need to save your file to the “mcpi” folder. You do this by going to “File”, “Save As”, then finding the “mcpi” folder and giving it a filename ending in .py - your name will do fine.
Now your program is saved you need to RUN it. So go to Run > Run Module from the menu and wait for something to happen in the Minecraft window.
You should see something like this:
Let’s consider what has actually happened here and learn a bit about how computers and computer programs work...
When we create a program in Python or any other text based programming language, the program always has 2 parts:
- Setup - This sets out all of the things required to get the program to work.
- Loop - The Loop tells everything what to do
LOOP - Loops are essential in programming. They allow you to repeat sequences of code so you don’t have to write the same thing again and again. There are a couple of different types of loop, and we will look at these in more detail later.
In order to cement this idea, let’s think of ourselves as artists, and our programs as works of art we are creating.
Before an artist can begin creating a work of art they need to get “Set Up”. This will include ensuring they have pencils, paints, paintbrushes, sharpener etc. Maybe a pot of water, a canvas or paper, something to draw, or even sketchbooks to use as references. Only once all of this preparation or “Setup” has been done will the artist actually begin to draw and create their work of art.
Programming is exactly the same. Before the program runs we need to do the setup. This could be to bring in additional libraries (like an artist’s reference material), declare variables (setting the paints on your palette), or a variety of other things. Once this setup has been done, the rest of the program can use this information to create a work of art or program.
In our first hack, the first 3 lines are the setup. They access a series of Libraries and create a pipeline that connects our Python editor to Minecraft, and allows us to edit the Minecraft world.
We use Libraries to allow the programs to access complex information (like how to deal with time!!). Think of this as an artist referencing their sketchbooks to understand the best way to draw a horse.
This setup is where textual languages (like Python) differ from graphical languages (like Scratch), as graphical languages do the all of the setup for you
Our first hack sent a chat message to the Minecraft console using the following command:
mc.postToChat
This is really similar to giving a ‘print’ command in Python or a ‘Say’ block in Scratch.
We also use the “time.sleep(x)” command. This command tells the program to “sleep” or “wait” for a specified amount of time. (seconds)
Again, if we compare this to Scratch, it’s just the same as a ‘Wait’ block:
Time to tinker
Ask the students to try combining the 2 commands from this example to make something super groovy happen. Can you make Minecraft say your names, ask a question or tell a knock knock joke?
Have a look at this example, the sleeps give you a chance to respond to the computer as it tells the joke:
Challenge 2: Random Messages in the Chat Pane!
Well Done! You can now send messages to the chat pane, but what if we could send random messages to the player. In order to do this we would need a collection of comments for our program to pick out at random.
We can do this in Python using a data structure called an ARRAY or LIST (we will look at this structure in more detail later.
Let’s take a look at how an array can be used in a program.
The SETUP is now 4 lines long. We are now accessing a new library called random.
This allows the computer to generate random numbers (we use this to find the location of the data in our list)
The LIST is called ‘chat’ and contains three sentences that the computer will pick from. Each one needs to be written inside inverted commas, and the whole collection must be inside the square brackets [ ].
We also have a VARIABLE called “picker”. This VARIABLE uses the ‘random’ library to choose a random number between 0 and 2 (computers start counting from 0 so this gives us a range of 3)
- If it picks a 0 it will display the first sentence ( “Are you lost?”)
- If it picks a 1 it will display the second sentence ( “Your Mummy can’t help you here!")
- If it picks a 2 it will display the third sentence ( “We hope you are well"”)
When you run this code you should start to see something like this:
Let’s consider what you might be seeing and why, for example:
- The computer chooses a random integer in line 8.
- The random integer chosen is 1
- The computer looks at the “Chat” list and chooses the variable at position 1.
- The variable at position 1 is the string “Are you lost?”
- The computer sends the string “Are you lost” to the chat pane.
- The text is displayed.
- The computer waits 5 seconds.
- The computer chooses another random integer in line 8.
- The random integer chosen is 1 AGAIN!
- The computer looks at the “Chat” list and chooses the variable at position 1 AGAIN
- The variable at position 1 is the string “Are you lost?”...AGAIN
- The computer sends the string “Are you lost” to the chat pane...AGAIN
- The text is displayed. AGAIN
- The computer waits 5 seconds.
- The computer chooses another random integer in line 8.
- The random integer chosen is 2
- The computer looks at the “Chat” list and chooses the variable at position 2.
- The variable at position 1 is the string “Your mummy can’t help you here”
- The computer sends the string “Your mummy can’t help you here” to the chat pane.
- The text is displayed.
- The computer waits 5 seconds.
The computer will run through this process until you halt the program, because we have asked it to loop through the process FOREVER!!!
The forever loop is created by the code:
while True:
A while loop is ideal if you don’t know how many times you need to repeat the code. Our example above will run until we terminate the program.
Anything inside that loop needs to be indented below it. Python should automatically do this for you as you hit enter after the colon. If for any reason it doesn’t, use the Tab key to move each line across.
If you want to halt a program, you can click in the python shell and use the keyboard shortcut ctrl + c. This terminates your program.
Did you know... ?
VARIABLE - A variable is a place in the computer’s memory where we can store a single piece of data. Variables are associated with a name. We can read, change, and set the value of variables using their names.
You will recognise the mc.postToChat instruction, but in this example we tell the computer to go to the ‘chat’ list, and select the list item that matches the random number generated by ‘picker’
mc.postToChat (chat[picker])
Ask the students to add another 3 statements to the list and tweak your code to get it working. Remember if you are increasing the amount of sentences in your list, you will also need to increase the range of random integers (numbers) to choose from the whole list and include your new sentences! (line 8 of the code).
Plenary
Recap what we have covered so far in this lesson.
- Which parts of our code are the ‘set up’?
- Why do we need them?
- What are your first impressions of using a text based coding language?
- What’s different to block based languages like Scratch?
The lack of the visual library definitely makes it harder as you have to remember the code you’ll need (if you don’t have any reference or guides). It’s easier to make mistakes as well as the syntax that’s required needs to be so precise.
Be sure to leave time to disconnect the Raspberry Pi, monitor, mouse and keyboard and put them back into any PCs they were borrowed from.