Showing posts with label program. Show all posts
Showing posts with label program. Show all posts

Thursday, February 16, 2017

Making Games with Scratch and Sense Hat on Raspberry Pi


I'm a big fan of the Raspberry Pi Sense Hat and Scratch for doing interesting things and learning to code.
Previously I made a Sense Hat Cave Game using Python where you tilt the Sense Hat to move around as well as a Crane controller programmed in Scratch.
This time the goal was to create game that uses the Sense Hat as the display while programmed in Scratch.  The best of both world.  The goal for me was to lean to control the pixels a bit better in Scratch.

The result is Collect the Dots a simple game where you're a blue dot collecting red dots.  It's kind of like snake without the tail.



You control your dot using either the small joystick on the Sense Hat or use the keyboard on the computer.  Press Down to start the game.  You'll see in the video it tells you this on the Sense Hat, but if no Sense hat is attached and you're running on screen there is no prompt.


As can be seen in the video the on screen display mirrors on the Sense Hat dots, so either can be used.
Strangely even though the screen display is bigger I found it easier to play if I only looked at the Sense Hat display.
The game can also be played without the Sense Hat. Uploaded to Scratch website https://scratch.mit.edu/projects/144708660/

Embedded from the Scratch Website



You can download the code from GitHub

TIP: As the wonderful Cat Lamin points out in her blog post about using doing an animation on the Sense Hat using Scratch you have to run the code once to enable the sensors and capability of the Sense Hat.  So, the first time you run the program on a Raspberry Pi with a Sense Hat it may not work correctly.  Just stop it and start again and all will be perfect

A thought for an enhancement would be to control your dot by tilting the Sense Hat rather than using the joystick or keys.

Monday, January 30, 2017

Controlling screen brightness on pi-topCEED on Raspbian Jessie with guizero app and keyboard shortcut

I backed the pi-topCEED during the crowd funding campaign and have used it a lot since.

pi-topCEED

My kids also use it for homework and general Minecraft playing.
As I like to make things I have a number of microSD which means I regularly use it with Raspbian Jessie.

There are a couple of drawback to using Raspbian on the pi-topCEED.  The pi-topHUB doesn't shutdown the power completely leaving the backlight on and the Raspberry Pi in kind of a suspecd mode. The red LED is still on.  Also, there is no way to control the screen brightness.

Doing the usual Google to see if there was a way around this I came across this GitHub repository that looked like it would do the job.  https://github.com/rricharz/pi-top-install
It includes code to shutdown the pi-topHUB which also completely shuts down power to the display and to the Pi as well as provide a program called 'brightness' to control the screen brightness.

After following the instructions in the README.md I had the pi-topHUB shutting down correctly and if from the terminal I type brightness increase the screen brightness would go up and vice versa brightness decrease did what you'd expect.

All very good, but not very user friendly if you're running the GUI which is where I spend most of my time. 

With that in mind and having recently heard good thing about guizero (https://github.com/lawsie/guizero) which is based on tkinter and is said to make building GUI apps  in Python easier.

It looked to me like a simple app with 2 buttons [Darker] [Brighter] is all I needed so I read up a little on guizero.  Using the App using grid layout example (https://lawsie.github.io/guizero/app/) I soon has a small app that did exactly what I wanted.
Code available on Git Hub (https://github.com/winkleink/pi-top-brightness)

The program itself is quite short. Code below.  This makes 2 buttons.  Button1 and Button2.  When you press them they run the relevant system comment to change the brightness. 


from guizero import *
from subprocess import call

def brighter():
    call(["brightness", "increase"])

    
def darker():
    call(["brightness", "decrease"])
    
    
app = App(title="pi-top", height=50, width=145, layout="grid", bgcolor=None)

button1 = PushButton(app, brighter, text="Brighter", grid=[0,1])
button2 = PushButton(app, darker, text="Darker", grid=[0,0])
app.display()


Here is a video showing it working.


After a quick chmod +x  pi-top-brightness-gui.py the program was executable and so I could run it directly.

Then I added the program to the main menu under the System Tools section.
In the video you can see I have a pi-top icon.  This I took from their Twitter account (https://twitter.com/GetPiTop)  I expect they'll be OK with that as I'm adding even more branding to my pi-topCEED.
I explained in a recent post on backing up Minecraft Worlds how to add a program to the menu (http://www.winkleink.com/2016/07/minecraft-pi-backup-worlds-on-exit.html)

It's great to have a little gui app to change the brightness of the screen and even better to learn a new skill with guizero.

One thing I didn't mention is that when I rebooted the Raspberry Pi the first time after installing the programs the screen brightness was far lower than I wanted it be by default.

To fix this I added a single line cronjob.  Crontab with cronjobs is a way to schedule when programs run automatically with one of the options being to run at boot up. It's a simple way to get something running each time you login. It's the system used by people who lets say want to check their network connection every hour.  Just setup a cronjob to run every hour and it will take care of it for you.   I used this previously to enable the Bluetooth keyboard and trackpad or the NexDock. (http://www.winkleink.com/2016/10/nexdock-thoughts.html)

So, I used crontab to set the brightness of the screen to 8 on startup.

In the terminal type:

crontab -e

If this is your first time it asks which editor you want to use.  I do [2] for nano.
Then the crontab file is opened where you put the jobs you want to run.
There are some comments in the file to help you get started, but if you want to do serious scheduled jobs then it's worth 

Go to the bottom of the file and type

@reboot brightness 8

Then the usual nano [CTRL]-[x] to save and close.  Answering [y] to save the file with the same name

Now when I start up the pi-topCEED the default brightness is '8' which suits me.


Finally, finally, the rricharz GitHub explains how to set the keyboard shortcuts for the pi-top laptop so the brightness keys work.  All good if I had a pi-top laptop, but I have a pi-topCEED where it's bring your own keyboard and the one I'm using doesn't have any fancy keys.
So, I looked up how to add keyboard shortcuts.  Again, it ends out to be not too hard.  Just added a couple of entries into a config file.

First thing I had to do is decide what key combination I wanted to use. I settled on:
[Shift]-[Windows Key]-[Up Arrow] for brighter
[Shift]-[Windows Key]-[Down Arrow] for darker

To do this you need to edit the lxde-pi-rc.xml file.
The file is a in a hidden folder in your home folder. If using the default user pi then the following command will open it 

nano /home/pi/.config/openbox/lxde-pi-rc.xml

As the file is in the home folder it doesn't need sudo to edit it

Then scroll down to the keyboard section and add the following to the end.
Easiest way is in nano find the </keyboard> text using the command [Ctrl]-[w] to do a Where is

Make sure you use spaces for the indent and get the <keybind> to line up with the other <keybind> entries

    <keybind key="S-W-Up">
      <action name="Execute">
        <command>brightness increase</command>
      </action>
    </keybind>
    <keybind key="S-W-Down">
      <action name="Execute">
        <command>brightness decrease</command>
      </action>
    </keybind>

To finish like above use [Ctr]-[x] to save and close.

To test select [shutdown] in the drop down menu and then [logout].
No need to reboot to enable the keyboard shortcuts.
Once you log back in the lxde-pi-rc.xml setting will be re-enabled and the 2 new key bindings will be active giving you the ability to change the brightness of your pi-top/pi-topCEED using [Shift]-[Windows Key]-[Up Arrow] and [Shift]-[Windows key]-[Down Arrow]

This has been a fun little project to improve the use of the pi-topCEED.
I like the work rricharz has done getting the pi-topHUB to turn off completely and to control the brightness as well as Laura Sach has done to make guizero so easy to use.

With the help of other peoples effort I now have the pi-topCEED completely shutdown as well as the Raspberry Pi and the ability to change the screen brightness using either a little gui app or with the keyboard.  Not a bad result for a couple of hours.

If you have any questions let me know in the comments.


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:

#!/usr/bin/python

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.setBlocks(-127,-127,-127,127,127,127,blockId)

mc.postToChat("create floor")

blockId = block.DIRT.id
mc.setBlocks(-127,0,-127,127,0,127,blockId)


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

RUN:
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.