Tuesday, February 26, 2013

Raspberry Pi Minecraft and Python - create lots of blank worlds to mess about in.

I've been playing with Python and Minecraft on the Raspberry Pi.  Using the API included you can write Python scripts to build in Minecraft.
I like to work with a blank world rather than an existing landscape because the landscape may not work or if I make a mistake it can be hard to undo.

So, I wanted to quickly create a bunch of disposable worlds that I can run my very rough scripts in to see where I need to tweak them.

NOTE: for some reason some flowers and things are left behind. It might be an attribute thing...

Code Below:


import sys
import mcpi.minecraft as minecraft
import mcpi.block as block

mc = minecraft.Minecraft.create()

mc.postToChat("Clearing ALL")

blockId = block.AIR.id

mc.postToChat("create floor")

blockId = block.DIRT.id

There are no indents so should just work if cut and pasted to a text file and saved.  I used clearall.py

Start Minecraft
Create a World

python clearall.py

The whole world is made of AIR with a 'ground' of DIRT is added at Y=0.
This will take a while to run so be patient.

Now you have one blank world.

But that would be slow to do that every time you need a blank world.

Well with a bit of jiggery pokery you don't have to.
The method I used is probably a bit manual but it is faster than coding for new worlds every time.
Maybe somebody brighter than me can automate it.

Step 1. Make sure you can see hidden folders when browsing on your Raspberry Pi.
The got to ~/pi (if your username is pi)
Open .minecraft/games/com.mojang/minecraftWorlds
This is the directory where your saved Worlds are stored.
One per folder. For me the blank world I created was called world

Create a bunch of new directories. I used world-blank1, world-blank2 etc....
Make as many as you want.

Go into the original world directory and copy all the files.
Then paste those files into each of your world-blank directories.
Now you have replicated the blank world you created with the above script too all of these world maps.

If you go back into Minecraft they will be there. Only problem is they will all have the same name. Not ideal when you want to know which ones you have broken and which are still clean.

This is where it gets a bit more low level but still quite simple.

Installed ghex a gui based hex editor with sudo apt-get install ghex

Then for each folder open level.dat using ghex and find where it says world
Modify the text to a different name making sure to keep it the same size.  Maybe B0001.
Save the updated level.dat.
Do this for each of your new directories making sure to use a different name (B0002,B0003,...) .

If you run minecraft you will get a list of Worlds all with different names.  For me the order was still a bit mixed up but I can live with that.

Finally, rather than having to do this every time I created a new directory under com.mojang called backup-blank and copied all my newly made blank world into that directory.

Now I can mess about with the blank worlds. Building all kinds of strange shapes not caring about  it being perfect as I can just delete that world and replace it with a new clean one by just copying the saved worlds in backup-blank  back into the minecraftWorlds directory and start again.

Note: For me I have 20(ish) blank worlds created as I mess up a fair bit and this usually allows me to do one good session without having to copy across or create a new blank world.

Happy Coding.

Friday, February 22, 2013

Surrey and Hampshire Hackspace evening - 21st February

Last night was another great evening at the Hackspace with more new people coming along which is fantastic.

During the week a kind person contacted the hackspace and offered to donate some test equipment and books.  One of the members offered to go to Croyden and collect the stuff.
some of the donated books and kit
What a great donation. It included many electronics books. Some were of great interest from a nostalgia standpoint but will be great for introducing new concepts to members starting out.The book on the 741 op-amp is a great little read and introduces the fundamentals of analogue signals and circuits in a nice easy but practical way.  Amongst all the books were an lcd projector and an oscilloscope. Both in perfect working order and will be a great addition to the resources the hackspace has for meet-ups and building circuits.

With new blood came new and interesting possibilities. There were great discussions about pic programming in assembly, control circuitry for race cars, home heating automation with a Raspberry Pi at the heart of it amongst other tops.

A real interesting topic was a satellite developed in Surrey that is controlled using a mobile phone.
More details on the University of Surrey website
Below is video showing what is in the satellite, what it does and how it's all put together.

So, the hackspace is going from strength to strength with more people taking part.

Here's looking forward to the next meet-up and some more interesting discussions and demos.

A selection of pictures from the evening. (sorry for the poor quality - mobile phone pics)

Tuesday, February 19, 2013

Raspberry Pi + GPIO + Scratch + Remote Control Car

At the beginning of 2013 I started a Code Club at my local primary school and the kids love making and playing the games.  Due to the way the club is set up in the school there is expected to be a few classes after the official Code Club sessions are completed so I've been trying to come up with some ideas of things I could bring in to the class to show the kids that Scratch can do more than make a cat move around the screen.

Then on my regular trawl of the web I found this fantastic code http://cymplecy.wordpress.com/2012/08/26/scratch-controlling-the-gpio-on-a-raspberrypi/ for controlling the GPIO pins on the Raspberry Pi using Scratch.

With an old cheap remote control car in a drawer I had the makings of a fun project for me that (hopefully) will be of interest to the kids.

 Having read that the Raspberry Pi GPIO pins are not protected, so one silly mistake on my part could cause the death of my Raspberry Pi I dusted off my old electronics knowledge and put together a small transistor based driver circuit for the 4 pins used.

one circuit per pin

I originally wired this up on a protoboard and it worked, except for when it failed. Did I mention the remote control car was cheap. Well, the aerial was just a bit of wire and with all the other wires I added to the circuit there was regular interference that caused the remote to activate the wrong signal making it unreliable. Knowing the circuit was good the logical thing to do was to put the circuit on a proper board. Rather than going all the way to etching my own circuit board I made it up on a stripboard

again, 1 circuit per pin. white blobs under resistors are cuts in the tracks

After a false start (details of things I almost did wrong) I got the 4 circuits soldered up and tested.  Worked first time.

Not the prettiest soldering but after doing near no soldering for over 20 years I was happy with the result.

Now I the circuit soldered up and it worked. With a bit of coding in Scratch I could program the remote control car for a sequence of actions like
Forward 2 second
Left 0.5 seconds.
Reverse Right 2 seconds

As you'd expect from a simple remote control car the was no way to give very accurate instruction. The motor was either on or off, no variable speed or feedback.  Even with these limitations it felt great when I clicked on the code in Scratch and car actually did what I expected it to do.

the vehicle of my success!!!

And finally he is a short video of the car in action.

This is why I love the Raspberry Pi and the fun of hacking.  With a little bit of effort you can have a lot of fun. Now I have a remote control car that I can control with drag and drop commands in Scratch on a £30 computer.

Sunday, February 17, 2013

Quiz Master Raspberry Pi version now working

I copied the Windows code on to my Raspberry Pi last night and it worked perfecty if run from IDLE. But, if I ran it from either a terminal window or double clicked on the icon it failed.

There were 2 problems.

First was that IDLE on Windows put a ^M at the end of every line so the shebang statement on the first line was failing.
To fix this I copied it all into vi and saved it out. This stripped put all the ^M things.  I must admit I didn't expect this from IDLE.
Then after some more searching  and trial and error I eventually figured out that the directory for the program is not set to where the program is run from so when I try to open the players.txt file it fails and dumps me out.

Using os.getcwd() I can find out which folder the program was run from and set it to the path for players.txt and the sound files.

I revised the code and attached a new pack to the forum that now works on the Raspberry Pi.

Make sure to chmod +the .py to make it executable.

Friday, February 15, 2013

Quiz Master Lockout follow up

27-DEC-2019 Updated to change link to code from Dropbox to Git Hub. 

Following yesterdays post about the Quiz Master code I have been doing a bit of tweaking and enhancing. GitHub link to ZIP file

Enhancements in this version.
1. Number of players, their names and sound played when they press their button is taken from a text file (example included)
2. Quiz master can go into lockout mode at any time by pressing return. An X appears top right to show in lockout mode
3. Text at the top of the screen is now taken from the text file - so it can be personalised
4. Now runs full screen ( ran in a window to take the screen shot below)

screen shot

This version is reading keyboard presses. You can buy a USB keyboard on ebay for about £5 and with the aid of some buttons and soldering you can attach the buttons to the keys as defined in your file. Still leaving you with the full keyboard. As mentioned before I see this as the easier option than looking to use GPIO inputs when run from a Raspberry Pi.
These buttons from ebay look perfect.

So, for about £40 (+ cost of connecting wires and housing) you would have a quiz master set up.

NOTE: I would never describe myself as a Python programmer. The code is done in the true hacker sense in that I figured it out as I went along. It all works with the testing I have done but be aware your mileage may be different.

Thursday, February 14, 2013

Quiz button lockout system using Python & Pygame

I read the following post on the Raspberry Pi forum where somebody was looking for a quiz button system for 10 buttons where only the first button pressed was registered.

I posted a replay saying this should be possible with Python as it has an event queue so you should be able to find out which button was pressed first. I also mentioned that starting with a cheap USB gamepad would give the 10 buttons with little wiring effort and no need to do anything with the GPIO.

After posting instead of feeling like I helped somebody I mainly felt I had given them homework.
So, I decided to see if with the help of Google I could actually do the code.

Following a bit of tinkering and searching and getting spacing wrong and forgetting the colons at the end of lines I put together something quite rough that does the job.

I posted this back to the forum, but also the code is below.

The code is for four (4) buttons using the arrow keys on the keyboard.
It waits for a keys to be pressed.
Checks if it is one of the 'button' keys and registers the first button by changing the colour of that players on screen button to red.
It then waits until the 'Return' key is pressed and resets the buttons to black.

This provides the lockout system required and only registers the first button pressed.

#! /usr/bin/python
# Import a library of functions called 'pygame'
import pygame

# Initialize the game engine

# Define the colors we will use in RGB format
black = [ 0, 0, 0]
white = [255,255,255]
red = [255, 0, 0]

# Set the height and width of the screen
# Fill the screen White
# Put something in the application Bar
pygame.display.set_caption("Testing key presses")

# Set the font for the text. Windows computer so usd Ariel
myfont = pygame.font.SysFont("Ariel", 30)

# Created Variable for the text on the screen
label = myfont.render("Quiz Buttons!", 1, black)
player1 = myfont.render("Player 1", 1, black)
player2 = myfont.render("Player 2", 1, black)
player3 = myfont.render("Player 3", 1, black)
player4 = myfont.render("Player 4", 1, black)

# Draw the 4 empty rectangles for the players
pygame.draw.rect(screen, black, (20,200,150,150), 0)
pygame.draw.rect(screen, black, (210,200,150,150), 0)
pygame.draw.rect(screen, black, (400,200,150,150), 0)
pygame.draw.rect(screen, black, (590,200,150,150), 0)

# put the text on the screen
screen.blit(label, (10, 10))
screen.blit(player1, (20, 150))
screen.blit(player2, (210, 150))
screen.blit(player3, (400, 150))
screen.blit(player4, (590, 150))

# show the whole thing

done=False # used to allow exit when you click close on the window
first = 0 # used to signify the first key pressed and stops other being used
waitReset = 0 # Reset section for the while loop

while done==False: # keep going unless I exit application

    # Stay in the loop until one of the 'button' keys is pressed
    while first==0 and done==False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            # User pressed down on a key and it is not the first one
            if event.type == pygame.KEYDOWN and first==0:

                # Figure out which arrow key
                # Check of LEFT arrow key and that it was the first key pressed
                if event.key == pygame.K_LEFT and first==0:
                    print("left key pressed.") # Print to console
                    pygame.draw.rect(screen, red, (20,200,150,150), 0) # colour rectangle red
                    first=1 # set first to 1 so no other key presses will count
                if event.key == pygame.K_RIGHT and first==0:
                    print("right key pressed.")
                    pygame.draw.rect(screen, red, (210,200,150,150), 0)
                if event.key == pygame.K_UP and first==0:
                    print("up key pressed.")
                    pygame.draw.rect(screen, red, (400,200,150,150), 0)
                if event.key == pygame.K_DOWN and first==0:
                    print("down key pressed.")
                    pygame.draw.rect(screen, red, (590,200,150,150), 0)
                # a 'button' was pressed and shown on screen
                # now got to the reset code

    # loop waiting until the 4 'button' are reset
    while waitReset==0 and done == False:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:

                # User pressed down on a key
                if event.type == pygame.KEYDOWN:
                # Pressed Return Key which does a reset
                    if event.key == pygame.K_RETURN:
                        # Draw the 4 empty rectangles for the players
                        pygame.draw.rect(screen, black, (20,200,150,150), 0)
                        pygame.draw.rect(screen, black, (210,200,150,150), 0)
                        pygame.draw.rect(screen, black, (400,200,150,150), 0)
                        pygame.draw.rect(screen, black, (590,200,150,150), 0)   
# Quit in a clean way when done=True
pygame.quit ()

Next I will expand this to add the score and also run it full screen. 
Possibly even have sounds when the buttons are pressed.

Friday, February 8, 2013

Surrey & Hampshire Hackspace evening 7th February 2013

Last night was the second Surrey & Hampshire Hackspace session I have attended at GamesGalaxy in Farnborugh.  Last time I had planned to solder up my Raspberry Pi interface for a remote control car but got sucked into the excellent Eagle tutorial by Bob, so this week I was determined to get it done.

Ohms Law
Bob and Doug
While I was quietly getting on with stuff Bob for his second tutorial gave an introduction to Ohms Law.

Alan busy soldering
What he's soldering
Alan was soldering up an SMD board. A lot more complex and precise than my efforts. Not sure the circuits purpose but as you can see from the pictures Alan had 2 soldering irons at his disposal.

circuit on proto-board. too many wires
For the remote control project I needed to move the components from a proto-board that due to the number of wires hanging off it causing too much interference and stopping the remote from working reliably.  I wanted to build it on a stripboard to get rid of all the wires and also as a small, simple introduction to using stripboard as this was my first time using stripboard.

When I arrived I realised I had left my computer at home and in it’s case were my notes. Nothing too detailed but not a great start.  I also left my soldering iron at home so a quick trip to Maplin around the corner sorted that out.

figuring out the circuit
So began the task of taking a simple circuit with 4 components and figuring out how to do it on stripboard. It’s amazing how something that makes perfect sense on a proto-board suddenly appears more complex than it needed to be.

After a bit of head scratch I figured out the layout and it only used 5 strips.  one for 0V, one for 3V (from remote) and 3 for the transistor and the 3 resistors.  Hopefully a nice neat circuit. 

I then turned the board over to start placing components and thankfully Doug pointed out that I needed to mirror the circuit compared to put the components in on the strip side.  I expect this saved me a lot of troubleshooting later on.

first one soldered
top side components
I soldered in the first circuit after figuring out the mirrored circuit and where I needed to cut the tracks to make it work.
(sorry for the poor picture quality)

Really happy about getting it done and was then about to solder in the second circuit when Robin popped over so I explained the layout and again noted a mistake. I was missing a location where I could take the output to the remote. If you look at the hand drawn circuit above there is no output at the transistor.  Whoops, another mistake averted.  I had to move the transistor forward one hole to create the point where the remote wire would attach.  If you look at the 1st solder side picture above and the final one below with the 4 circuits in place you will see the one on the left has moved to the edge with no spare holes left. Lucky I had the space to move it.

Also, on the first one I thought I’d be clever and use the legs of the resistors to do the bridging by just bending over the pins and soldering them. It worked perfectly, but looked a bit of a mess so I decided for the other three I would use jumper wires on the top of the board. That is why there are no jumper wires on the first circuit but the other three all have small jumper wires.

All 4 solder in - see the one on the left has moved...

component side up. 3 on the right have  jumper wires
Here is the final layout for 1 of the circuits as a schematic diagram and also on the strip board. I put the jumper links on the strip side for illustration purposed but you can see for 3 of the 4 circuits above the jumpers are on the top.

white under resistors are cuts in the strip
So, that was it all wired up.  I then added the wires to connect to the remote control and the wires to connect to the GPIO pins on the Raspberry Pi through the Adafruit PiCobbler.
After hooking it all up and attaching a screen and keyboard I loaded GPIOScratch, Opened my test code and it worked.  Sending commands from Scratch on the Raspberry Pi made the car drive.
All the problems I had with interference due to the tangle of wires have been fixed and I now have a reliable circuit that I can possibly bring into the CodeClub I run to show the kids that Scratch is not just for making a cat run around the screen.

In my joy it slipped my mind to photograph the finished circuit all wired up to the remote and the Raspberry Pi. So, for the next post I will do some more pictures, a video and show the Scratch Code.

It was an excellent evening at the Surrey & Hampshire Hackspace and next get together is the 21st of February. If this type of thing interest you then visit the website and join the mailing list. Or even better come along on the night. For more going on you can follow on Google+.

Roll on the 21st and some more computing and electronics fun.