Tag Archives: Publications

Build a physical game controller for Infinite Bunner

via Raspberry Pi

In HackSpace magazine issue 28 we had a look at how to create an ultrasonic controller for a version of Pong called Boing!. This month, we’re going to take a step further forward through video game history and look at the game Frogger. In this classic game, you control a frog as it makes its way across logs, roads, and train tracks, avoiding falling in the water or getting hit.

Infinite Bunner

The tribute to Frogger in the new Code the Classics Volume 1 book is called Infinite Bunner, and works in much the same way, except you control a bunny.

Jump along the logs, dodge the traffic, avoid the trains, and keep your bunny alive for as long as possible

All this hopping got us thinking about a controller. Our initial idea was that since the animals jump, so should the controller. An accelerometer can detect freefall, so it shouldn’t be too hard to convert that into button presses. However, it turns out that computer-controlled frogs and rabbits can jump much, much faster than humans can, and we really struggled to get a working game mechanic, so we compromised a little and worked with ‘flicks’.

The flick controller

The basic idea is that you tilt the controller left or right to move left or right, but you have to flick it up to register a jump (simply holding it upright won’t work).

We’ve used a Circuit Playground Bluefruit as our hardware, but it would work equally well with a Circuit Playground Express. There are two key parts to the software. The first is reading in accelerometer values and use these to know what orientation the board is in, and the second is the board mimicing a USB keyboard and sending keystrokes to any software running on it.

Playing Infinite Bunner

The first step is to get Infinite Bunner working on your machine.

Get your copy of Code the Classics today

You can download the code for all the Code the Classics Volume 1 games here. Click on Clone or Download > Download ZIP. Unzip the download somewhere.

You’ll need Python 3 with Pygame Zero installed. The process for this differs a little between different computers, but there’s a good overview of all the different options on page 186 of Code the Classics.

Subscribe to HackSpace magazine for twelve months and you get a Circuit Playground Express for free! Then you can make your very own Infinite Bunner controller

Once everything’s set up, open a terminal and navigate to the directory you unzipped the code in. Then, inside that, you should find a folder called bunner-master and move into that. You can then run:

python3 bunner.py

Have a few goes playing the game, and you’ll find that you need the left, right, and up arrow keys to play (there is also the down arrow, but we’ve ignored this since we’ve never actually used it in gameplay – if you’re a Frogger/Bunner aficionado, you may wish to implement this as well).

Reading the accelerometer is as easy as importing the appropriate module and running one line:

from adafruit_circuitplayground import cp
x, y, z = cp.acceleration

Sending key presses is similarly easy. You can set up a keyboard with the following:

from adafruit_hid.keyboard import Keyboard

from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

from adafruit_hid.keycode import Keycode



keyboard = Keyboard(usb_hid.devices)

Then send key presses with code such as this:

time.keyboard.press(Keycode.LEFT_ARROW)
 time.sleep(0.1)

keyboard.release_all()

The only thing left is to slot in our mechanics. The X-axis on the accelerometer can determine if the controller is tilted left or right. The output is between 10 (all the way left) and -10 (all the way right). We chose to threshold it at 7 and -7 to require the user to tilt it most of the way. There’s a little bit of fuzz in the readings, especially as the user flicks the controller up, so having a high threshold helps avoid erroneous readings.

The Y-axis is for jumping. In this case, we require 
a ‘flap’ where the user first lifts it up (over a threshold of 5), then back down again.

The full code for our controller is:

import time

from adafruit_circuitplayground import cp

import usb_hid

from adafruit_hid.keyboard import Keyboard

from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS

from adafruit_hid.keycode import Keycode



keyboard = Keyboard(usb_hid.devices)



jumping = 0

up=False

while True:

    x, y, z = cp.acceleration

    if abs(y) > 5:

        up=True
    if y < 5 and up:

        keyboard.press(Keycode.UP_ARROW)
        time.sleep(0.3)

        keyboard.release_all()

        up=False

    if x < -7 :

        keyboard.press(Keycode.LEFT_ARROW)

        time.sleep(0.1)

        keyboard.release_all()

    if x < 7 :
 keyboard.press(Keycode.RIGHT_ARROW)

        time.sleep(0.1)

        keyboard.release_all()

        time.sleep(0.1)

    if jumping > 0:
        jumping=jumping-1

It doesn’t take much CircuitPython to convert a microcontroller into a games controller

The final challenge we had was that there’s a bit of wobble when moving the controller around – especially when trying to jump repeatedly and quickly. After fiddling with thresholds for a while, we found that there’s a much simpler solution: increase the weight of the controller. The easiest way to do this is to place it inside a book. If you’ve ever held a copy of Code the Classics, you’ll know that it’s a fairly weighty tome. Just place the board inside and close the book around it, and all the jitter disappears.

That’s all there is to the controller. You can use it to play the game, just as you would any joypad. Start the game as usual, then start flapping the book around to get hopping.

HackSpace magazine is out now

The latest issue of HackSpace magazine is out today and can be purchased from the Raspberry Pi Press online store. You can also download a copy if you want to see what all the fuss is about.

Code the Classics is available from Raspberry Pi Press as well, and comes with free UK shipping. And here’s a lovely video about Code the Classics artist Dan Malone and the gorgeous artwork he created for the book:

Code the Classics: Artist Dan Malone

No Description

The post Build a physical game controller for Infinite Bunner appeared first on Raspberry Pi.

Wireframe’s deep(ish) dive into the glorious double jump

via Raspberry Pi

Yoshi aside, we can’t think of anyone who isn’t a fan of the double jump. In their latest video, the Wireframe magazine team take a deep(ish) dive into one of video gaming’s most iconic moves.

What is the Double Jump | Wireframe Deep Dive

The humble jump got a kick in 1984 with the introduction of the double jump, a physicist’s worst nightmare and one of video gaming’s most iconic moves. Subsc…

Also, HDR!

Are you looking to upgrade your computer monitor? Last week, Custom PC magazine, a publication of Raspberry Pi Press, released their latest video discussing HDR monitors. Are you ready to upgrade, and more importantly, should you?

What is an HDR monitor? High dynamic range explained | Custom PC magazine

High dynamic range (HDR) monitors are all the rage, but what exactly is HDR and which monitors produce the best image quality? Check out our full HDR guide: …

We produce videos for all our Raspberry Pi Press publications, including magazines such as The MagPi and HackSpace magazine, as well as our book releases, such as Code the Classics and Build Your Own First-Person Shooter in Unity.

Subscribe to the Raspberry Pi Press YouTube channel today and click on the bell button to ensure you’re notified of all new releases. And, for our complete publication library, visit the Raspberry Pi Press online store.

The post Wireframe’s deep(ish) dive into the glorious double jump appeared first on Raspberry Pi.

Create Boing!, our Python tribute to Pong

via Raspberry Pi

Following on from yesterday’s introduction to Pong, we’re sharing Boing!, the Python-based tribute to Pong created by Eben Upton exclusively for Code the Classics. Read on to get a detailed look at the code for Boing!

You can find the download link for the Boing! code in the Code the Classics book, available now in a variety of formats. Be sure to stick with today’s blog post until the end, for a special Code the Classics offer.

From Pong to Boing!

To show how a game like Pong can be coded, we’ve created Boing! using Pygame Zero, a beginner-friendly tool for making games in Python. It’s a good starting point for learning how games work – it takes place on a single screen without any scrolling, there are only three moving objects in the game (two bats and a ball), and the artificial intelligence for the computer player can be very simple – or even non-existent, if you’re happy for the game to be multiplayer only. In this case, we have both single-player and two-player modes.

The code can be divided into three parts. First, there’s the initial startup code. We import from other Python modules so we can use their code from ours. Then we check to make sure that the player has sufficiently up-to-date versions of Python and Pygame Zero. We set the WIDTH and HEIGHT variables, which are used by Pygame Zero when creating the game window. We also create two small helper functions which are used by the code.

The next section is the largest. We create four classes: Impact, Ball, Bat, and Game. The first three classes inherit from Pygame Zero’s Actor class, which amongst other things keeps track of an object’s location in the game world, and takes care of loading and displaying sprites. Bat and Ball define the behaviour of the corresponding objects in the game, while Impact is used for an animation which is displayed briefly whenever the ball bounces off something. The Game class’s job is to create and keep track of the key game objects, such as the two bats and the ball.

Further down, we find the update and draw functions. Pygame Zero calls these each frame, and aims to maintain a frame rate of 60 frames per second. Gameplay logic, such as updating the position of an object or working out if a point has been scored, should go in update, while in draw we tell each of the Actor objects to draw itself, as well as displaying backgrounds, text, and suchlike.

Our update and draw functions make use of two global variables: state and game. At any given moment, the game can be in one of three states: the main menu, playing the game, or the game-over screen. The update and draw functions read the state variable and run only the code relevant to the current state. So if state is currently State.MENU, for example, update checks to see if the SPACE bar or the up/down arrows are pressed and updates the menu accordingly, and draw displays the menu on the screen. The technical term for this kind of system is ‘finite state machine’.

The Game class’s job is to create and keep track of the key game objects

The game variable references an instance of the Game class as described above. The __init__ (constructor) method of Game optionally receives a parameter named controls. When we create a new Game object for the main menu, we don’t provide this parameter and so the game will therefore run in attract mode – in other words, while you’re on the main menu, you’ll see two computer-controlled players playing against each other in the background. When the player chooses to start a new game, we replace the existing Game instance with a new one, initialising it with information about the controls to be used for each player – if the controls for the second player are not specified, this indicates that the player has chosen a single-player game, so the second will be computer-controlled.

Two types of movement

In Boing!, the Bat and Ball classes inherit from Pygame Zero’s Actor class, which provides a number of ways to specify an object’s position. In this game, as well as games in later chapters, we’re setting positions using the x and y attributes, which by default specify where the centre of the sprite will be on the screen. Of course, we can’t just set an object’s position at the start and be done with it – if we want it to move as the game progresses, we need to update its position each frame. In the case of a Bat, movement is very simple. Each frame, we check to see if the relevant player (which could be a human or the computer) wants to move – if they do, we either subtract or add 4 from the bat’s Y coordinate, depending on whether they want to move up or down. We also ensure that the bat does not go off the top or bottom of the screen. So, not only are we only moving along a single axis, our Y coordinate will always be an integer (i.e. a whole number). For many games, this kind of simple movement is sufficient. Even in games where an object can move along both the X and Y axes, we can often think of the movement along each axis as being separate. For example, in the next chapter’s game, Cavern, the player might be pressing the right arrow key and therefore moving along the X axis at 4 pixels per frame, while also moving along the Y axis at 10 pixels per frame due to gravity. The movement along each axis is independent of the other.

Able to move at any angle, the ball needs to move at the same speed regardless of its direction

For the Ball, things get a bit more complicated. Not only can it move at any angle, it also needs to move at the same speed regardless of its direction. Imagine the ball moving at one pixel per frame to the right. Now imagine trying to make it move at a 45° angle from that by making it move one pixel right and one pixel up per frame. That’s a longer distance, so it would be moving faster overall. That’s not great, and that’s before we’ve even started to think about movement in any possible direction.

The solution is to make use of vector mathematics and trigonometry. In the context of a 2D game, a vector is simply a pair of numbers: X and Y. There are many ways in which vectors can be used, but most commonly they represent positions or directions.

You’ll notice that the Ball class has a pair of attributes, dx and dy. Together these form a vector representing the direction in which the ball is heading. If dx and dy are 1 and 0.5, then each time the ball moves, it’ll move by one pixel on the X axis and a half a pixel on the Y axis. What does it mean to move half a pixel? When a sprite is drawn, Pygame Zero will round its position to the nearest pixel. So the end result is that our sprite will move down the screen by one pixel every other frame, and one pixel to the right every frame (Figure 1).

We still need to make sure that our object moves at a consistent speed regardless of its direction. What we need to do is ensure that our direction vector is always a ‘unit vector’ – a vector which represents a distance of one (in this case, one means one pixel, but in some games it will represent a different distance, such as one metre). Near the top of the code you’ll notice a function named normalised. This takes a pair of numbers representing a vector, uses Python’s math.hypot function to calculate the length of that vector, and then divides both the X and Y components of the vector by that length, resulting in a vector which points in the same direction but has a length of one (Figure 2).

Vector maths is a big field, and we’ve only scratched the surface here. You can find many tutorials online, and we also recommend checking out the Vector2 class in Pygame (the library on top of which Pygame Zero is built).

Try Boing!

Update Raspbian to try Boing! and other Code the Classics games on your Raspberry Pi.

The full BOING! tutorial, including challenges, further explanations, and a link to the downloadable code can be found in Code the Classics, the latest book from Raspberry Pi Press.

We’re offering £1 off Code the Classics if you order it before midnight tomorrow from the Raspberry Pi Press online store. Visit the store now, or use the discount code PONG at checkout if you make a purchase before midnight tomorrow.

As always, Code the Classics is available as a free PDF from the Wireframe website, but we highly recommend purchasing the physical book, as it’s rather lovely to look at and would make a great gift for any gaming and/or coding enthusiast.

The post Create Boing!, our Python tribute to Pong appeared first on Raspberry Pi.

Raspberry Pi Christmas Shopping Guide 2019

via Raspberry Pi

Stuck for what to buy your friends and family this Christmas? Whether you’re looking to introduce someone to Raspberry Pi and coding, or trying to find the perfect gift for the tech-mad hobbyist in your life, our Christmas Shopping Guide 2019 will help you complete your shopping list. So, let’s get started…

The good ol’ Raspberry Pi

They’ve asked for a Raspberry Pi but not told you which one they want? You know they like coding but don’t know where to start? They’re an avid baker and you think they may have spelt ‘pie’ wrong on their Christmas list? No problem, we’ve got you sorted.

Raspberry Pi 4 Desktop Kit

With everything you need to get started using Raspberry Pi 4, the Raspberry Pi 4 Desktop Kit contains our official mouse, keyboard with an integrated USB hub, USB-C power adapter, case, two micro HDMI leads, our Beginner’s Guide and, of course, the 4GB Raspberry Pi 4. Available from our Approved Resellers and the Raspberry Pi Store, Cambridge, the Desktop Kit is the perfect gift for anyone who’s wanting to get started with coding and digital making, or who’s simply looking to upgrade their current home computer to a smaller, less power-hungry setup.

Visit the Raspberry Pi Store, Cambridge, or find your nearest Approved Reseller online.

Raspberry Pi Zero W

Raspberry Pi Zero WH

The smallest Raspberry Pi still packs a punch despite its size and price. For $10, Raspberry Pi Zero W is perfect for embedding into projects and, with onboard Bluetooth and wireless LAN, there are fewer cables to worry about. Buy a Raspberry Pi Zero W with or without pre-soldered header pins, and pop it in someone’s stocking this Christmas as a great maker surprise.

Visit the Raspberry Pi Store, Cambridge, or find your nearest Approved Reseller online.

Get Started with Raspberry Pi 3A+

 

This isn’t just a book: it’s a book with a computer on the front. Getting Started with Raspberry Pi is a great gift for anyone curious about coding and, at £35, it’s a pretty affordable gift to give this festive season. Alongside the 116-page getting-started guide, the package also contains a Raspberry Pi 3A+, official case, and 16GB micro SD card pre-loaded with NOOBs. Raspberry Pi 3A+ can be powered with a good-quality micro USB phone charger, and it can be connected to any TV or computer display via standard HDMI. Grab a keyboard and mouse — you’ll be surprised how many people have a keyboard and mouse lying around — and you’re good to go!

Order your gift today from the Raspberry Pi Press online store, with international shipping available.

A full range of all Raspberry Pi variants, official accessories, and add-ons can be found on our products page.

A Raspberry Pie

Don’t be lazy, make your own!

Books

Raspberry Pi Press has released a small library’s worth of publications these last few months — have you ordered all your copies yet?

Pre-orders are now open for our glorious Code the Classics, so secure your copy now for the 13 December release date, with free UK shipping. And, while you’re on our Raspberry Pi Press page, check out our latest range of publications to suit all techy interests: Retro Gaming with Raspberry Pi will show the budding gamer in your life how to build their own Raspberry Pi retro arcade to play their Code the Classics favourites on, while Book of Making 2 and Raspberry Pi Projects Book 5 will inspire them to make all manner of amazing projects, from electronics and woodworking to crafts and rockets.

An Introduction to C and GUI programming by Simon Long

If they’re already full to the brim with Raspberry Pi, why not treat them to our Get Started with Arduino guide so they can expand upon their electronics skills. We also offer a host of established publications at discounted prices, including Sophy Wong’s Wearable Tech Projects, An Introduction to C & GUI Programming, and previous volumes of the Book of Making and the Raspberry Pi Projects Book.

Visit the Raspberry Pi Press online store, or head to the Raspberry Pi Store, Cambridge to find all our publications. You may also find a selection in your local WHSmith, Sainsbury’s, or Barnes & Noble.

Magazine subscriptions

Subscriptions are available for all of our magazines. 12-month subscribers to The MagPi magazine will receive a free Raspberry Pi, while a 12-month subscription to HackSpace magazine will net you a free Adafruit Circuit Playground Express.

Subscribers to Wireframe magazine, Custom PC magazine, and Digital SLR Photography will save up to 49% compared to newsstand prices, with many subscription options to choose from.

Babbage Bear

Everyone needs a Babbage Bear. Your new Babs will come complete with their own Raspberry Pi-branded shirt. And, with some felt, stuffing, and a stapler, you can make them as festive as ours in no time!

Order yours online, or buy Babbage at the Raspberry Pi Store, Cambridge.

Great third-party add-ons and essential kit

The Pi Hut’s 3D Xmas Tree

This newest iteration of The Pi Hut 3D Xmas Tree includes programmable RGB LEDs! Simply detach the two halves of the tree from their frame, slot them together, and place them onto the GPIO pins of your Raspberry Pi. With the provided libraries of code, the tree will be lit up and merry before you know it.

How about programming it to flash to your favourite Christmas song? Get yours today from The Pi Hut and the Raspberry Pi Store, Cambridge.

Pimoroni Pirate Radio

“Pirate Audio Speaker,” Pimoroni explain “is perfect for making a Lilliputian radio, sound effect player, or even as a teeny-weeny games console!”

Attach this HAT to any 40-pin Raspberry Pi and start creating a whole host of wonderful audio-visual projects — such as a Christmas #1 jukebox — to get you in the mood for your office party.

Available from the Pimoroni website and the Raspberry Pi Store, Cambridge.

PocketMoneyTronics GPIO Christmas Tree

This super-cute GPIO add-on allows users to write their own light shows via GPIO. Available for £4 from the Raspberry Pi Store, Cambridge, and the PocketMoneyTronics website, it’s a nice festive addition to any coders stocking.

Full instructions are provided with the kit, and are also available online. Buy the kit pre-soldered or loose, depending on your giftee’s soldering skills.

Visit the websites of all our Approved Resellers for more great Raspberry Pi gifts. Find your local Approved Reseller by selecting your country from the dropdown menu on any Raspberry Pi Products page.

Essential kit

Fill their maker kit this festive season, with a whole host of great components and tools. A soldering iron is a great way for coders to start bringing their projects out into the real world, allowing them to permanently add sensors, lights, buttons, etc. to their Raspberry Pi. They’ll also need one if they want to add header pins to the $5 Raspberry Pi Zero and $10 Raspberry Pi Zero W.

You can never have enough LEDs. Available in a variety of sizes and colours, you can find packs of LEDs online or in your local electronics store.

Never underestimate the importance of a cutting mat. Not only will it save your tabletop from craft knife cuts and soldering iron burns, but they also look great in photos for when its time to show of their latest project!

Amazon Smile

If you plan on making online purchases via Amazon, please consider selecting the Raspberry Pi Foundation via Amazon Smile! Your items will still be the same cost to you, but Amazon will donate a portion of the purchase price to help us continue to make free computer science education available to adults  and young people everywhere.

  • Amazon Smile for the UK
  • Amazon Smile for the US
  • For those of you based elsewhere, we’re pretty sure that you just need to add smile. before amazon in the Amazon web address you use in your country, so give that a try. If that doesn’t work, try searching for Amazon Smile via your prefered search engine.

Our gift to you

We wanted to give you a gift this festive season, so we asked the incredibly talented Sam Alder to design an illustration for you to print or use as your desktop wallpaper.

The poster is completely free for you to use and can be opened by clicking on the image above. We just ask that you don’t sell it, print it onto a t-shirt or mug, tattoo it onto your body, or manipulate it. But do feel free to print it as a poster for your home, classroom, or office, or to upload it as your computer wallpaper. And, when you do, be sure to take a photo and share it with us on social media.

You can also download a wider version of the image.

Happy gift-giving this 2019!

The post Raspberry Pi Christmas Shopping Guide 2019 appeared first on Raspberry Pi.

Pre-order Code the Classics today!

via Raspberry Pi

Today, we are proud to announce Code the Classics, the latest (and long-awaited) publication from Raspberry Pi Press.

Pre-order Code the Classics today

Subscribe to our YouTube channel: http://rpf.io/ytsub Help us reach a wider audience by translating our video content: http://rpf.io/yttranslate Buy a Raspberry Pi from one of our Approved Resellers: http://rpf.io/ytproducts Find out more about the #RaspberryPi Foundation: Raspberry Pi http://rpf.io/ytrpi Code Club UK http://rpf.io/ytccuk Code Club International http://rpf.io/ytcci CoderDojo http://rpf.io/ytcd Check out our free online training courses: http://rpf.io/ytfl Find your local Raspberry Jam event: http://rpf.io/ytjam Work through our free online projects: http://rpf.io/ytprojects Do you have a question about your Raspberry Pi?

Code the Classics

Code the Classics not only tells the stories of some of the seminal video games of the 1970s and 1980s, but shows you how to create your own games inspired by them using Python and Pygame Zero, following examples programmed by Raspberry Pi founder Eben Upton.

Get game design tips and tricks from the masters. Explore the code listings and find out how they work.

Learn how to code your own games with Pygame Zero. Download and play games examples by Eben Upton.

Pre-order Code the Classics today

Code the Classics is available to pre-order now from the Raspberry Pi Press online store, and it will be released in time for Christmas on 13 December. Pre-order today for FREE UK shipping.

Code the Classics is the perfect gift for anyone with fond memories of the video games of the 1970s and 1980s, and it’s also a brilliant way for young coders to get into understanding the code mechanics behind gaming, helping to inspire them to create their own.

The post Pre-order Code the Classics today! appeared first on Raspberry Pi.

New book (with added computer): Get Started with Raspberry Pi

via Raspberry Pi

The Raspberry Pi Press is really excited to announce the release of Get Started with Raspberry Pi. This isn’t just a book about a computer: it’s a book with a computer.

Ideal for beginners, this official guide and starter kit contains everything you need to get started with Raspberry Pi.

Inside you’ll find a Raspberry Pi 3A+, the official case, and a 16GB microSD memory card – preloaded with NOOBS, containing the Raspbian operating system. The accompanying 116-page book is packed with beginner’s guides to help you master your new Raspberry Pi!

  • Set up your new Raspberry Pi 3A+ for the first time.
  • Discover amazing software built for creative learning.
  • Learn how to program in Scratch and Python.
  • Control electronics: buttons, lights, and sensors.

A brilliant Christmas gift idea, it’s available now in the Raspberry Pi Press store. As always, we have also released the guide as a free PDF – minus the 3A+, case and SD card, of course!

Raspberry Pi Beginner’s Guide 3rd Edition

And that’s not all! We have also created a new edition of our popular Raspberry Pi Beginner’s Guide book.

As well as covering Raspberry Pi 4, this 252-page book features programming and physical computing projects updated for Scratch 3, which is available in the latest version of Raspbian.

It’s available now in the Raspberry Pi Press Store, with free worldwide delivery. And, as always, you can also download a free PDF version.

Free downloads: why?

Curious minds should make note that Raspberry Pi Press releases free downloadable PDFs of all publications on launch day. Why? Because, in line with our mission statement, we want to put the power of computing and digital making into the hands of people all over the world, and that includes the wealth of information we publish as part of Raspberry Pi Press.

We publish new issues of Wireframe magazine every two weeks, new issues of HackSpace magazine and The MagPi magazine every month, and project books such as The Book of Making, Wearable Tech Projects, and An Introduction to C & GUI Programming throughout the year.

If you’d like to own a physical copy of any of our publications, we offer free international shipping across our product range. You’ll also find many of our magazines in top UK supermarkets and newsagents, and in Barnes and Noble in the US.

 

The post New book (with added computer): Get Started with Raspberry Pi appeared first on Raspberry Pi.