Monday, 24 July 2017

BitIO Blog 2: Extending the Accelerometer demo: Walking Rainbow Blocks



This takes the basic 'tilt_mc.py' demo from David Whales BitIO master available here:
https://github.com/whaleygeek/bitio

In the first blog the demo moves the character around the screen according to the direction you tilt the Micro:bit. The code below extends this to:

1. Use a list to randomly select a wool block.
2. Drop this block underneath the player the end result is a colourful mess. :) (See below)

The code will need to be saved in the 'src' folder to work.



Below is the code, you can download it here:
https://github.com/ncscomputing/HpAnthologyV2/raw/master/Walking%20tilt.py



Code:

#Original written by David Whale located here as part of his BITIO library
#https://github.com/whaleygeek/bitio/blob/master/src/tilt_mc.py
#adapted by @ncscomputing 19/07/17


import mcpi.minecraft as minecraft
import mcpi.block as block
import microbit
import time
import random




mc = minecraft.Minecraft.create()

blocksList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

while True:
    pos = mc.player.getTilePos()
    x = microbit.accelerometer.get_x()/300 # -ve=left/+ve=right
    y = microbit.accelerometer.get_y()/300 # -ve=forward/+ve=backward

    pos.x += x # east/west
    pos.z += y # north/south

    mc.player.setTilePos(pos.x, pos.y, pos.z)
    mc.setBlock(pos.x, pos.y-1, pos.z,35,random.choice(blocksList))
 


   # time.sleep(0.5)


Enjoy :)

You can now download a pdf version of these tutorials as part of the updated #hackpack resource booklet here:
https://github.com/ncscomputing/HpAnthologyV2/raw/master/Hackpack%20Anthology%20V2%200.3.pdf

2 comments: