Raspberry PI, Python, Scratch and Minecraft

We were recently lucky enough to win 5 Raspberry PIs from the Coderdojo Foundation so figuring out what to do with them was our first challenge. In this post I will detail how I set them up so that the ninjas at the Naas-Sallins dojo could use them to improve their coding skills. They came with Raspbian installed but instructions for getting started with the PI are on the website. Knowing that the ninjas love minecraft I decided to install the special edition for the PI by following the instructions here.

Typically people use python to control the Pi edition of minecraft via its api and there is some great information on how to do that on the Stuff About Code website but after some digging about I found that it would be possible to use the Scratch extension mechanism to allow ninjas access minecraft on a remote Pi from their laptops.

The comprehensive instructions are here and you should have a read of them but in general you run a python program which talks http with scratch and translates them to instructions that the remote Pi running minecraft will understand. You then load a .s2e file which adds the minecraft blocks to scratch.

So once we got everything working with the mcpi-scratch extension it was time to see how well it works.

Using Scratch with the mcpi-scratch extension.

Using Scratch with the mcpi-scratch extension.

This screen shot shows the minecraft blocks which are found in the more blocks section and it also shows a couple of the custom blocks that are going to draw the letter they are named after in minecraft blocks.

When we run this scratch program with our mcpi-scratch helper application and extension running we get the following result.

This just gives a quick idea of what is possible, but the main advantage is that we can have multiple ninjas working on different laptops connecting to a single Pi running minecraft.

This ability to write helper apps and extensions for scratch open up a wide range of possibilities. I used the mcpi-scratch.py code as the basis for a quick test to allow scratch to tweet. I added the code from our earlier python program which uses the tweepy library.

""" messing about with Scratch2 helper app for twitter thanks to mcpi-scratch for the idea"""
import sys, traceback
import argparse, urllib
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
import tweepy
import logging

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

class GetHandler(BaseHTTPRequestHandler):

    """code to hit twitter"""
    def postToTwitter(self, params):
        tweet = urllib.unquote(params[0])
        api.update_status(status=tweet)
        return ''

    def pollEvents(self, params):
        global pollInc, pollLimit, prevPosStr, posStr
        pollInc += 1
        log.debug('poll: {} {}'.format(pollInc, prevPosStr))
        if (prevPosStr != "") and (pollInc % pollLimit != 0):
            log.debug("don't call mc")
            return prevPosStr

        posStr = ''
        prevPosStr = posStr
        return posStr

    def do_GET(self):
        global api
        cmds = {
            "poll" : self.pollEvents,
            "postToTwitter" : self.postToTwitter,
        }
        parsed_path = urlparse.urlparse(self.path)

        message_parts = []
        message_parts.append('')
        cmdpath = parsed_path[2].split('/')
        print cmdpath
        handler = cmds[cmdpath[1]]
        pollResp = handler(cmdpath[2:])
        log.debug ("pollResp: {0}".format(pollResp))
        message_parts.append(pollResp)
        message = '\r\n'.join(message_parts)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(message)
        return

parser = argparse.ArgumentParser(description='scratch_tweet is a Scratch2 extension helper app to allow Scratch programs to manipulate twitter via tweepy')

#enter the corresponding information for your Twitter application:
CONSUMER_KEY = 'sjkfhskjhfkjshfkjdsh'
CONSUMER_SECRET = 'fkslfjskljfklsjflkjsdldfkjslkfjlksjfkls'
ACCESS_KEY = 'sjdfklsjfkljsklfjlskjfklsjfklsjlfkjslkfjskljfkls'
ACCESS_SECRET = 'skfljslkfjskljfklsjflkjslkfjskljflksjflksjfklj'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

args = parser.parse_args()
log.info(args)

pollInc = 0
pollLimit = 15
prevPosStr = ""

try:
    api = tweepy.API(auth)
except:
    e = sys.exc_info()[0]
    log.exception('cannot connect to twitter')
    traceback.print_exc(file=sys.stdout)
    sys.exit(0)

from BaseHTTPServer import HTTPServer
server = HTTPServer(('localhost', 4715), GetHandler)
log.info('Starting server, use <Ctrl-C> to stop')
server.serve_forever()</pre>
<pre>

The scratch extension associated with this program is as follows this should be saved as a .s2e file

{
 "extensionName": "scratch_tweet Py",
 "extensionPort": 4715,
 "blockSpecs": [

 [" ", "post tweet %s", "postToTwitter", "Tweet"],
 ],

 }
 }

So now you run the python program, launch scratch, hold down shift and click file and then pick import experimental http extension and open the extension above. The post tweet block should now be available to use.
scratchtweet

scratchtweetxx
This just shows what is possible with the http extension in scratch.

Advertisements