Minecraft Mashups part three

By Russell Barnes. Posted

Use Minecraft with a Sense HAT and music-making software Sonic Pi in our final mashups

Finish off mashing up Minecraft with part three of our guide, following up on natural disasters and libraries in part one and Node-RED in part two.

The full article can be found in The MagPi 41

Walking with Steve

One of the cool things about the console edition of Minecraft is that you can use a controller instead of a keyboard. The Pi edition might sometimes seem a little basic, but you can make your game more like the console edition by deploying your Sense HAT as a tiltable controller instead of using a keyboard. If you don’t know which way to tilt it, the arrows appearing on the LED matrix will help you.

 Walking Steve with a Sense HAT

The first thing you need to do is to install all the necessary modules. An obvious one is the Sense HAT library: if you have Raspbian Jessie, this comes bundled with it; if not, you can install it by typing:

sudo pip install sense_hat

You'll also need another Python module, which in turn requires the Xlib library:

sudo apt-get install python-xlib
sudo pip install pyautogui

Using the pyautogui functions, you can simulate keys as if they were actually pressed. This is how you make Steve walk around his blocky world.

Instead of pressing keys, we'll use the Sense HAT’s accelerometer to find out which direction the HAT is being tilted. Each time we measure, we get values representing the acceleration intensity of the x, y, and z axes (in Gs). These are sometimes called roll, pitch, and yaw, like on an aeroplane or a spaceship. We only need the x and y axes, as the z axis is rotation and we’re not using that.

How to use it

Download or type up the code from the listing (right) into IDLE, then press F5 to run it. Make sure Minecraft is running and you’ve entered a world when you run it, otherwise lots of errors will appear! If you tilt the Sense HAT forward, the pyautogui module will trigger a W key and move Steve forward; make sure your mouse is clicked in the Minecraft window when this happens, otherwise it will just generate a ‘w’ in the Python shell. The same thing happens when you tilt it backwards, but it will generate an S. If you tilt it to the side, it will generate a D or an A, depending on which direction you’ve tilted. You still need to use the mouse to look around, and the E key to open your inventory. So, the idea is for you to get all the items you need in your hotbar, then hold the mouse in one hand and the Sense HAT in the other.

 None shall pass!

Using Minecraft

When the program is running, you’ll only be able to walk (or fly) around using the keys when the Sense HAT is in the level position (all the LEDs will be red). Even then, you’ll only move if you tap the key repeatedly instead of holding it down. So you’re better off sticking to the Sense HAT!

Once you have written and understood this program, you could try to improve it by making the Sense HAT’s joystick open your inventory or something awesome like that.

Code listing

You can download WalkingWithSteve.py from GitHub, or copy it in from below:

import pyautogui as pag
import time
from sense_hat import SenseHat
sh = SenseHat()

def unpress():# unpresses all the keys
    for key in ['s','w','a','d']:
        pag.keyUp(key)

def move(direction):# presses the correct key
    unpress()
    pag.keyDown(direction)

def displayArrow(c,rot):# the arrow
    arrow = [
    e,e,e,c,c,e,e,e,
    e,e,c,c,c,c,e,e,
    e,c,c,c,c,c,c,e,
    c,c,e,c,c,e,c,c,
    c,e,e,c,c,e,e,c,
    e,e,e,c,c,e,e,e,
    e,e,e,c,c,e,e,e,
    e,e,e,c,c,e,e,e]
    sh.set_rotation(rot)
    sh.set_pixels(arrow)
    
r = [255,0,0]# define the colours
e = [0,0,0]
g = [0,255,0]
b = [0,0,255]
stop = [# the stop sign
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r,
r,r,r,r,r,r,r,r]

mot = 'SSSS'
while True:# main loop
    x, y, z = sh.get_accelerometer_raw().values()
    x = round(x, 0)
    y = round(y, 0)
    if x  == -1  and abs(y) == 0 and mot != 'rrrr': 
        displayArrow(b,0)
        move('d')# right
        mot = 'rrrr'
    elif  x == 1  and abs(y) == 0 and mot != 'llll': 
        displayArrow(b,180)
        move('a')# left
        mot = 'llll'
    elif y == -1  and mot != 'wwww': 
        displayArrow(g,270)
        move('w')# fwd
        mot = 'wwww'
    elif y == 1  and mot != 'bbbb':
        displayArrow(g,90)
        move('s')# back
        mot = 'bbbb'
    elif abs(x) == 0 and abs(y) == 0:
        unpress()# stop
        sh.set_pixels(stop)
        mot = 'SSSS'

Become A Minecraft VJ

Everyone has built amazing structures, designed cunning traps, and even created elaborate cart tracks in Minecraft. How many of you have performed with Minecraft? We bet you didn’t know that you could use Minecraft to create amazing visuals, just like a professional VJ.

As well as coding with Python, you can also program Minecraft with an app called Sonic Pi, which makes the coding not only easy but also incredibly fun. In this article, we’ll be showing you some of the tips and tricks that we’ve used to create performances in nightclubs and music venues around the world.

 Become a VJ with Sonic Pi and Minecraft

Enter a new world in Minecraft and open Sonic Pi. When we’re using Minecraft to create visuals, we try to think about what will both look interesting and also be easy to generate from code. One nice trick is to create a sandstorm by dropping sand blocks from the sky. For that, all we need are a few basic fns (Sonic Pi functions):

sleep - for inserting a delay between actions
mclocation - to find our current location
mc
setblock - to place sand blocks at a specific location
rrand - to allow us to generate random values within a range
live
loop - to allow us to continually make it rain sand

Let’s make it rain a little first, before unleashing the full power of the storm. Grab your current location and use it to create a few sand blocks up in the sky nearby:

x, y, z = mc_location
mc_set_block :sand, x, y + 20, z + 5
sleep 2
mc_set_block :sand, x, y + 20, z + 6
sleep 2
mc_set_block :sand, x, y + 20, z + 7
sleep 2
mc_set_block :sand, x, y + 20, z + 8

When you press Run, you might have to look around a little, as the blocks may start falling down behind you depending on which direction you’re currently facing. Don’t worry: if you missed them, just press Run again for another batch of sand rain - just make sure you’re looking the right way!

Let’s quickly review what’s going on here. On the first line, we grabbed Steve’s location as coordinates with the fn mclocation and placed them into the vars x, y, and z. Then, on the next lines, we used the mcset_block fn to place some sand at the same coordinates as Steve, but with some modifications. We chose the same x coordinate, a y coordinate 20 blocks higher, and then successively larger z coordinates so the sand dropped in a line away from Steve.

Why don’t you take that code and start playing around with it yourself? Try adding more lines, changing the sleep times, try mixing :sand
with :gravel, and choose different coordinates. Just experiment and have fun!

Live loops unleashed

OK, it’s time to get the storm raging by unleashing the full power of the live_loop, Sonic Pi’s magical ability, which unleashes the full power of live-coding: changing code on the fly while it’s running!

live_loop :sand_storm do
  x, y, z = mc_location
  xd = rrand(-10, 10)
  zd = rrand(-10, 10)
  co = rrand(70, 130)
  synth :cnoise, attack: 0, release: 0.125, cutoff: co
  mc_set_block :sand, x + xd, y+20, z+zd
  sleep 0.125
end

What fun! We’re looping round pretty quickly (eight times a second), and during each loop we’re finding Steve’s location like before but then generating three random values:

xd - the difference for x, which will be between -10 and 10
zd - the difference for z, also between -10 and 10
co - a cutoff value for the low pass filter, between 70 and 130

We then use those random values in the fns synth and mcsetblock
, giving us sand falling in random locations around Steve, along with a percussive rain-like sound from the :cnoise synth.

For those of you new to live loops, this is where the fun really starts with Sonic Pi. While the code is running and the sand is pouring down, try changing one of the values, perhaps the sleep time to 0.25 or the :sand block type to :gravel. Now press the Run button again. Hey presto! Things have changed without the code even stopping. This is your gateway to performing like a real VJ. Keep practising and changing things around. How different can you make the visuals without stopping the code?

Epic block patterns

Finally, another great way of creating interesting visuals is to generate huge patterned walls to fly towards and get close to. For this effect, we’ll need to move from placing the blocks randomly to placing them in an ordered manner. We can do this by nesting two sets of iteration; press the Help button and navigate to section 5.2 of the tutorial, ‘Iteration and Loops’, for more background on iteration. The funny |xd| after the do means that xd will be set for each value of the iteration. So, the first time it will be 0, then 1, then 2 and so on. By nesting two lots of iteration together like this, we can generate all the coordinates for a square. We can then randomly choose block types from a ring of blocks for an interesting effect:

x, y, z = mc_location
bs = (ring :gold, :diamond, :glass)
10.times do |xd|
  10.times do |yd|
    mc_set_block bs.choose, x + xd, y + yd, z
  end
end

Pretty neat. Whilst we’re having fun here, try changing bs.choose to bs.tick to move from a random pattern to a more regular one. Try changing the block types – the more adventurous of you might want to try sticking this within a live_loop so that the patterns keep changing automatically.

Now, for the VJ finale. Change the two 10.times to 100.times and press Run. Kaboom!… A gigantic wall of randomly placed bricks. Imagine how long it would take you to build that manually with your mouse! Double-tap SPACE to enter fly-mode and start swooping by for some great visual effects. Don’t stop here, though – use your imagination to conjure up some cool ideas and then use the coding power of Sonic Pi to make it real. When you’ve practised enough, dim the lights and put on a VJ show for your friends!

From The MagPi store

Subscribe

Subscribe to the newsletter

Get every issue delivered directly to your inbox and keep up to date with the latest news, offers, events, and more.