Warm-up (optional)
This year builds on your previous experience coding in Minecraft. To get back into the swing of it, open a Minecraft world and press C on your keyboard, then choose any tutorial.
Not sure where to start? Try one of these.
Block code is the main path
Throughout this unit, sample code is given as block code. You will also see optional Python panels marked in grey. Those are extensions: open them if you want to, skip them if you would rather concentrate on getting your build working.
A new word: encapsulation
Today introduces a new coding term. We are not going near the full object-oriented meaning; at this stage all you need to know is that encapsulation is a way of grouping your program into sections.
First, a memory check
You have used all three of these in previous years. Can you say what each one refers to?
- Conditional statement
- Iteration
- Variable
Technically, encapsulation means the grouping of data (attributes and stored values) and methods (functions, or code that does something) into single units, sometimes called a class, while restricting direct access to some of the components.
Got that? Do not stress if you did not. The part to focus on is methods and functions.
Methods and functions let you create segments of code that each handle one specific task. The difference is only in naming: method is the term used in object-oriented coding, which we are not doing, and function is the more general term, which is what we will be creating.
You have almost built functions before
Last year you wrote code that was very close to a function without calling it one. Does this look familiar?
Now look at what happens when we split it up. There are two clear chunks of code, or more accurately two functions, each handling one specific task. They sit in the program doing nothing at all until they are called into action by a function call.
Building it this way might look like extra work. The payoff is that you can now spawn chickens or bees with individual chat commands and create both creatures at once, just by adding a call to each function.
Questions on the code above
- How many chickens will be spawned when the program first runs?
- How could we modify it to produce 500 chickens? Hint: there are at least three different ways.
How to create a function
Four steps, in order.
Task: fill in the empty functions
Here is another example, but this time the main body of each function has been left out. Mimic this code, then add the instructions needed inside each one to:
- Place an individual block when the user types
blockin the chat window. - Place a stack of 3 blocks when the user types
stack. Complete this as three separate block-place commands, keeping the X and Z coordinates the same and increasing Y by 1 each time.
Optional The same starting point in Python
Why this is optional.
The risk: Python is typed out by hand, so the syntax and the indenting have to be exactly right. One missing colon, one bracket in the wrong place, or one line indented incorrectly and the program will not run at all. Block code cannot go wrong in those ways.
The reward: if you work through these panels, you will finish the unit with real Python skills to build on, which is exactly what you need if you are thinking about taking Digital Technologies in Year 10.
Any line beginning with # is a comment: Python ignores it. Remove the comment lines and replace them with real commands.
def place_a_block(): # command — any line with a # is treated as a comment, not actual code # command — remove these lines and replace them with actual commands def build_a_stack(): # command # command player.on_chat("block", place_a_block) player.on_chat("stack", build_a_stack)
The def instruction is short for "define a function".
What is actually happening
This code works by breaking the program into segments called functions. A function only ever runs when another section of code makes a function call. Here the user starts it by typing a trigger word into the chat window, so we can say the program is listening for that word. Until either word is typed, nothing inside place_a_block or build_a_stack executes at all.
Think of it as the instructions stored in your brain for how to throw a ball. The instructions are already there; you only access them when you actually want to throw. You can make the same call every single time without having to work out how to control each individual muscle again, and again, and again.
Parameters: sending a value into a function
So far each function does exactly the same thing every time. A parameter changes that: it lets the user hand a value to the function as they call it, and the function uses that value to decide what to do.
build_a_custom_stack, takes a number and uses it inside the loop.num. It should only be created when you first build the function and select a number parameter.Notice the extra variable in build_a_custom_stack. When the user types custom 5, the value 5 is stored in the height variable and passed into the function as part of the function call. That value then decides how many times the loop repeats. The higher the number typed into chat, the more times the loop runs. Handy.
Try each of these in the chat window
You should not need to move your player between commands, though you may need to look around to find where the blocks have been placed.
| Type this | What should happen |
|---|---|
block | One block is placed. |
stack | A fixed stack is built. |
custom | An error, because you have not supplied an argument. "Argument" is another word for the value you pass in as a parameter. |
custom 5 | A stack five blocks high. |
custom 20 | A stack twenty blocks high, from the same function. |
Optional The three functions in Python
Copy this into a new Python program inside Minecraft. Be careful with the indenting after pasting: everything must line up exactly as shown.
def place_a_block(): # This is a function that only places one block blocks.place(DIAMOND_BLOCK, pos(3, 2, 3)) def build_a_stack(): # Another function that runs when a function call is made for i in range(4): blocks.place(REDSTONE_ORE, pos(5, i, 1)) def build_a_custom_stack(height): # This function also takes a number, called a parameter, # and uses it within the code inside the function for i in range(height): blocks.place(GREEN_CONCRETE, pos(1, i, 5)) player.on_chat("block", place_a_block) player.on_chat("stack", build_a_stack) player.on_chat("custom", build_a_custom_stack)
Reminder: indenting is not decoration in Python. It is how the language knows which lines belong inside the function and inside the loop.
Finally, try adding this code.
Run it, then type chunk 3 5 and chunk 20 4 into the chat window. What does this code do?
Chat command simulator
Type a command the way you would in Minecraft chat, or use the buttons. Watch which function is called, what the parameters become, and what gets built. Commands available: block, stack, custom <height>, chunk <height> <width>.
Task: build your own program
Using the code samples above, create your own program built from functions and function calls. Pick one option. This runs for the rest of this lesson, homework, and next lesson.
Option 1
Instant zooThe user types zoo in chat, which triggers function calls to:
- populate_wings — 5 bees, 5 chickens, 2 parrots
- populate_land — 1 cow, 1 sheep, 1 pig
- populate_finns — 1 dolphin, 2 pufferfish
- populate_finns must also call a fourth function, create_water, to make an area of water before the fish are spawned
Option 2
Hollow glass cube- Dimensions come from the user, e.g.
cube 10 20 - One function builds the outside
- A second function places a cube of air inside it, hollowing the cube out but leaving the walls intact
- Two functions in total, each with one job
Note: Minecraft already has a built-in command that builds a hollow cube in one step (the hollow option on fill). Do not use it for this task. You must build the cube and hollow it out yourself with your two functions. Using the built-in hollow command will result in a lower assessment.
Option 3
Pyramid- Each layer is smaller than the layer below it
- The height comes from the user, e.g.
pyramid 10 - Think carefully about the logic: how does each layer know how big to be?
- Bonus points if each layer is built from alternating materials
Submission
Upload a Word document containing screenshots of your code plus several images of what your code builds. You must also show your teacher the code working.
Rubric
Developing
Code that builds- LowEvidence of some code to build or spawn, but no evidence of successful or suitable functions
- HighCode has been copied in from the samples shown above
Consolidating
Working functions- LowSome of the zoo functions have been successfully created
- MidAll four distinct zoo functions created and triggered in the correct logical order by typing
zoo, or the glass cube partially completed with some issues placing blocks inside the loops - HighThe zoo has cages or tanks included, or the hollow glass cube works, or the pyramid builds at a set size without handling a parameter
Extending
Parameters driving the build- LowThe pyramid is complete in one material, sized by a value typed in by the user
- HighEach layer of the pyramid uses a different material
Relative and global coordinates
Until now, your Minecraft coding has mostly used the XYZ system that is relative to the player, not the global system. In relative terms, 0, 0, 0 means the block at your player's feet, not some central point far away in the world.
This is exactly why the chickens in Chicken Rain always spawn directly over your head, even if you walk sideways after starting the program. The tilde symbol, ~, is what marks a coordinate as local and relative rather than global.
~, so all of it is measured from wherever the player happens to be standing.Turn your coordinates on
To see your global coordinates in game: Settings → World Settings, then scroll down to Show Coordinates and turn it on. You cannot debug a position problem you cannot see.
Local versus global
Look at the code below. What is different between the location coordinates, and what would we have to do to make sure we can actually see the bees being spawned?
Relative versus global lab
Press Run program, then walk your player around. Each pulsing block is one frame of the animation. With relative coordinates every frame lands somewhere new and the animation smears across the world. Switch to geo-locked and every frame redraws in exactly the same place, no matter where you wander. That is the whole point of the next task.
Move the player, then run the program again.
The glitch this causes
An animation built from relative coordinates redraws itself around wherever you are standing at that moment. Take three steps to the left mid-animation and the whole thing tears itself apart, because each new frame is measured from a different origin. Geo-locking fixes the origin once, at the start, so every later frame lands in the same place no matter where you wander.
Task: geo-lock your coordinates
To create geo-locked coordinates we need a little coding magic. Copy the sample below carefully into a new code file. You do not need to include the comments. You can alter the starting coordinate values, but do not put them too far away from yourself.
This lets you create an animation in a particular location that begins relative to your player, but, far more importantly, lets you move around afterwards without your animation glitching.
Find a good spot
Stand on a flat piece of land with a decent amount of space around you. A flat world is ideal.
Copy the code exactly
Recreate the sample below in a new file. The first command inside on start is the one that captures your player's current position into variables.
Run it and check the falling sand
Execute the program and confirm the falling sand animation works. Then walk away and watch that it keeps animating in the original spot.
Be mindful of using location coordinates with the word WORLD on them for all block placement commands. The default is relative to the player, and we only want to set a relative location in the very first command inside the "on start" section.
Optional How geo-locking looks in Python
Same trade-off as before.
The risk: this is more typing than the block version, and a single mistyped variable name will send your build somewhere unexpected or stop it running.
The reward: storing a position in variables and reusing it is a pattern you will meet constantly in Year 10 and beyond.
The idea is the same in either language: read the player's position once, store the three numbers, then use those stored numbers as the origin for everything you build afterwards.
# Capture the player's position ONCE, at the start originX = player.position().get_value(Axis.X) originY = player.position().get_value(Axis.Y) originZ = player.position().get_value(Axis.Z) def build_here(): # Every placement is measured from the stored origin, # not from wherever the player is standing now blocks.place(SAND, world(originX + 2, originY + 6, originZ + 2)) player.on_chat("build", build_here)
Compare this with the block version above. world() is doing the same job as the WORLD-marked coordinates in the blocks: it says "these numbers are absolute, not relative to me".
Geo-locked animation
Copy the following code into the file you created last lesson, the one that geo-locked a relative coordinate system. If you missed that lesson, the code you need is in Lesson 2.
Notice that every placement command is relative to the X, Y and Z variables you defined earlier, using the world coordinate data type. That is what stops the animation from chasing you around the map.
How an animation works here
There is no animation tool in Minecraft. You create the illusion the same way you would on a flip-book: place blocks, pause, remove them, place the next arrangement, pause, and repeat. A ghost that appears and disappears is a set of blocks placed and then replaced with air. Anything that seems to move is really being deleted from one position and drawn in the next.
Assessment task: the Haunted Carnival
Create a Haunted Carnival. The entire carnival must be generated with code, and the keyword to build it is spooky. When that word is typed into the chat window, the carnival is created.
Suggestions to include
| Feature | Notes |
|---|---|
| Buildings and a fence | Simple structures are fine. Use the fill with command rather than hundreds of single block placements. |
| Ghost or monster | A simple animation of something appearing, then disappearing. |
| Carnival name | Written in large letters, flashing different colours. The built-in Billboard tutorial can help with this. |
| Minecart ride | A short one is plenty. |
| Dripping lava | Falling endlessly from an invisible source, as an animation. |
| Spinning ride | A ferris wheel or gravitron. This one is difficult. |
Build conditions
Develop all of this on a flat world, at the height of the player. Keep most structures simple. The point of this task is the quality of your code, not the number of blocks in it.
Submission
A PowerPoint containing screenshot evidence of your code, in either block or Python form, plus your Python code as text, converted if necessary and pasted into a text box directly from Minecraft.
Note that even if you build entirely in blocks, Minecraft can convert your work to Python for you, so this part of the submission does not require you to write Python by hand.
Carnival planner
Tick features as you get them working. Each one maps to a level in the rubric below, so this doubles as a progress check.
0 of 11 complete
Rubric
Developing
It builds- Simple block-house structures and a fence
- Typing
spookyexecutes the functions that create the carnival - No evidence of using geo-locked relative coordinates
Consolidating
It animates- LowEvidence of objects appearing and disappearing, using the relative-to-global code, with effective use of functions in the parameters and structure of the code
- LowIf the geo-locking is too difficult to understand, a Consolidating High result from the functions task may help you reach this level. Submit that same code for this assessment
- MidFlashing carnival name
- HighMinecart ride
Extending
It spins- Low–HighA spinning object or ride. Hint: this is easier with some additional maths functions, so researching that could help
- ExtraCan you make smoke appear when the carnival is first created? Hint: hay plus a campfire. Smoke passes through one block, so the campfire itself can be hidden from view