Tag Archives: Uncategorized

Sink every shot with this robotic backboard

via Arduino Blog

With many years of practice and discipline, you too can improve your basketball skills. Or you could just choose to play with Shane Wighton’s automated backboard that sinks nearly any shot that you take.

The setup uses a Microsoft Kinect, along with a Windows-based computer to calculate the inbound ball’s trajectory. On approach it passes data to an Arduino, which then moves the hoop into position via three large steppers and a linkage system. 

While this compensates for the “occasional” error, as shown in the excellent explainer/demo video below, you do have to actually hit the backboard for it to work!

RetroPie for Raspberry Pi 4: video game emulation on our fastest-ever device

via Raspberry Pi

For many of you out there, your first taste of Raspberry Pi is using it as a retro gaming emulator running RetroPie. Simple to install and use, RetroPie allows nostalgic gamers (and parents trying to educate their kids) the ability to play old-schoolskool classics on any monitor in their home, with cheap USB game controllers or models from modern consoles.

GuzziGuy RetroPie Table

Mid-century-ish Retro Games Table’ by Reddit user GuzziGuy

And because our community is so wonderfully inventive, Raspberry Pis running RetroPie have found themselves in homebrew gaming cabinets, old console casings, and even game cartridges themselves.

[Original Showcase Video] Pi Cart: A Raspberry Pi Retro Gaming Rig in an NES Cartridge

I put a Raspberry Pi Zero (and 2,400 vintage games) into an NES cartridge and it’s awesome. Powered by RetroPie. — See the full build video: https://www.yo…

Along came Raspberry Pi 4

When we announced Raspberry Pi 4 last year, a much faster device with more RAM than we’d previously offered, the retro gaming enthusiasts of the world quickly took to prodding and poking the current version of the RetroPie software to get it to work on our new, more powerful computer. And while some succeeded, those gamers not as savvy with manually updating the RetroPie software had to wait for a new image.

Retro Pie 4.6

And so yesterday, to much hurrah from the Raspberry Pi and retro gaming community, the RetroPie team announced the release of image version 4.6 with beta Raspberry Pi 4 support!

One of the biggest changes with the update is the move to Raspbian Buster, the latest version of our operating system, from Raspbian Stretch. And while they’re currently still advertising the Raspberry Pi 4 support as in beta, version 4.6 works extremely well on our newest model.

Update today!

Visit the RetroPie website today to download the 4.6 image, and if you have any difficulties with the software, visit the RetroPie forum to find help, support, and a community of like-minded gamers.

The post RetroPie for Raspberry Pi 4: video game emulation on our fastest-ever device appeared first on Raspberry Pi.

Make a Side Pocket-esque pool game | Wireframe #36

via Raspberry Pi

Recreate the arcade pool action of Data East’s Side Pocket. Raspberry Pi’s own Mac Bowley has the code.

In the original Side Pocket, the dotted line helped the player line up shots, while additional functions on the UI showed where and how hard you were striking the cue ball.

Created by Data East in 1986, Side Pocket was an arcade pool game that challenged players to sink all the balls on the table and achieve a minimum score to progress. As the levels went on, players faced more balls in increasingly difficult locations on the table.

Here, I’ll focus on three key aspects from Side Pocket: aiming a shot, moving the balls, and handling collisions for balls and pockets. This project is great for anyone who wants to dip their toe into 2D game physics. I’m going to use the Pygame’s built-in collision system as much as possible, to keep the code readable and short wherever I can.

Making a pool game

Before thinking about aiming and moving balls, I need a table to play on. I created both a border and a play area sprite using piskelapp.com; originally, this was one sprite, and I used a rect to represent the play area (see Figure 1). Changing to two sprites and making the play area an actor made all the collisions easier to handle and made everything much easier to place.

Figure 1: Our table with separate border. You could add some detail to your own table, or even adapt a photograph to make it look even more realistic.

For the balls, I made simple 32×32 sprites in varying colours. I need to be able to keep track of some information about each ball on the table, such as its position, a sprite, movement, and whether it’s been pocketed or not – once a ball’s pocketed, it’s removed from play. Each ball will have similar functionality as well – moving and colliding with each other. The best way to do this is with a class: a blueprint for each ball that I will make copies of when I need a new ball on the table.

class Ball:
def __init__(self, image, pos):
self.actor = Actor(image, center=pos, anchor=(“center”, “center”))
self.movement = [0, 0]
self.pocketed = False

def move(self):
self.actor.x += self.movement[0]
self.actor.y += self.movement[1]
if self.pocketed == False:
if self.actor.y < playArea.top + 16 or self.actor.y > playArea.bottom-16:
self.movement[1] = -self.movement[1]
self.actor.y = clamp(self.actor.y, playArea.top+16, playArea.bottom-16)
if self.actor.x < playArea.left+16 or self.actor.x > playArea.right-16:
self.movement[0] = -self.movement[0]
self.actor.x = clamp(self.actor.x, playArea.left+16, playArea.right-16)
else:
self.actor.x += self.movement[0]
self.actor.y += self.movement[1]
self.resistance()

def resistance(self):
# Slow the ball down
self.movement[0] *= 0.95
self.movement[1] *= 0.95

if abs(self.movement[0]) + abs(self.movement[1]) < 0.4:
self.movement = [0, 0]

The best part about using a class is that I only need to make one piece of code to move a ball, and I can reuse it for every ball on the table. I’m using an array to keep track of the ball’s movement – how much it will move each frame. I also need to make sure it bounces off the sides of the play area if it hits them. I’ll use an array to hold all the balls on the table.

To start with, I need a cue ball:

balls = []
cue_ball = Ball(“cue_ball.png”, (WIDTH//2, HEIGHT//2))
balls.append(cue_ball)

Aiming the shot

In Side Pocket, players control a dotted line that shows where the cue ball will go when they take a shot. Using the joystick or arrow buttons rotated the shot and moved the line, so players could aim to get the balls in the pockets (see Figure 2). To achieve this, we have to dive into our first bit of maths, converting a rotation in degrees to a pair of x and y movements. I decided my rotation would be at 0 degrees when pointing straight up; the player can then press the right and left arrow to increase or decrease this value.

Figure 2: The dotted line shows the trajectory of the ball. Pressing the left or right arrows rotates the aim.

Pygame Zero has some built-in attributes for checking the keyboard, which I’m taking full advantage of.

shot_rotation = 270.0 # Start pointing up table
turn_speed = 1
line = [] # To hold the points on my line
line_gap = 1/12
max_line_length = 400
def update():
global shot_rotation

## Rotate your aim
if keyboard[keys.LEFT]:
shot_rotation -= 1 * turn_speed
if keyboard[keys.RIGHT]:
shot_rotation += 1 * turn_speed

# Make the rotation wrap around
if shot_rotation > 360:
shot_rotation -= 360
if shot_rotation < 0:
shot_rotation += 360

At 0 degrees, my cue ball’s movement should be 0 in the x direction and -1 in y. When the rotation is 90 degrees, my x movement would be 1 and y would be zero; anything in between should be a fraction between the two numbers. I could use a lot of ‘if-elses’ to set this, but an easier way is to use sin and cos on my angle – I sin the rotation to get my x value and cos the rotation to get the y movement.

# The in-built functions need radian
rot_radians = shot_rotation * (math.pi/180)

x = math.sin(rot_rads)
y = -math.cos(rot_rads)
if not shot:
current_x = cue_ball.actor.x
current_y = cue_ball.actor.y
length = 0
line = []
while length < max_line_length:
hit = False
if current_y < playArea.top or current_y > playArea.bottom:
y = -y
hit = True
if current_x < playArea.left or current_x > playArea.right:
x = -x
hit = True
if hit == True:
line.append((current_x-(x*line_gap), current_y-(y*line_gap)))
length += math.sqrt(((x*line_gap)**2)+((y*line_gap)**2) )
current_x += x*line_gap
current_y += y*line_gap
line.append((current_x-(x*line_gap), current_y-(y*line_gap)))

I can then use those x and y co-ordinates to create a series of points for my aiming line.

Shooting the ball

To keep things simple, I’m only going to have a single shot speed – you could improve this design by allowing players to load up a more powerful shot over time, but I won’t do that here.

shot = False
ball_speed = 30


## Inside update
## Shoot the ball with the space bar
if keyboard[keys.SPACE] and not shot:
shot = True
cue_ball.momentum = [x*ball_speed, y*ball_speed]

When the shot variable is True, I’m going to move all the balls on my table – at the beginning, this is just the cue ball – but this code will also move the other balls as well when I add them.

# Shoot the ball and move all the balls on the table
else:
shot = False
balls_pocketed = []
collisions = []
for b in range(len(balls)):
# Move each ball
balls[b].move()
if abs(balls[b].momentum[0]) + abs(balls[b].momentum[1]) > 0:
shot = True

Each time I move the balls, I check whether they still have some movement left. I made a resistance function inside the ball class that will slow them down.

Collisions

Now for the final problem: getting the balls to collide with each other and the pockets. I need to add more balls and some pocket actors to my game in order to test the collisions.

balls.append(Ball(“ball_1.png”, (WIDTH//2 - 75, HEIGHT//2)))
balls.append(Ball(“ball_2.png”, (WIDTH//2 - 150, HEIGHT//2)))

pockets = []
pockets.append(Actor(“pocket.png”, topleft=(playArea.left, playArea.top), anchor=(“left”, “top”)))
# I create one of these actors for each pocket, they are not drawn

Each ball needs to be able to collide with the others, and when that happens, the direction and speed of the balls will change. Each ball will be responsible for changing the direction of the ball it has collided with, and I add a new function to my ball class:

def collide(self, ball):
collision_normal = [ball.actor.x - self.actor.x, ball.actor.y - self.actor.y]
ball_speed = math.sqrt(collision_normal[0]**2 + collision_normal[1]**2)
self_speed = math.sqrt(self.momentum[0]**2 + self.momentum[1]**2)
if self.momentum[0] == 0 and self.momentum[1] == 0:
ball.momentum[0] = -ball.momentum[0]
ball.momentum[1] = -ball.momentum[1]
elif ball_speed > 0:
collision_normal[0] *= 1/ball_speed
collision_normal[1] *= 1/ball_speed
ball.momentum[0] = collision_normal[0] * self_speed
ball.momentum[1] = collision_normal[1] * self_speed

When a collision happens, the other ball should move in the opposite direction to the collision. This is what allows you to line-up slices and knock balls diagonally into the pockets. Unlike the collisions with the edges, I can’t just reverse the x and y movement. I need to change its direction, and then give it a part of the current ball’s speed. Above, I’m using a normal to find the direction of the collision. You can think of this as the direction to the other ball as they collide.

Our finished pool game. See if you can expand it with extra balls and maybe a scoring system.

Handling collisions

I need to add to my update loop to detect and store the collisions to be handled after each set of movement.

# Check for collisions
for other in balls:
if other != b and b.actor.colliderect(other.actor):
collisions.append((b, other))
# Did it sink in the hole?
in_pocket = b.actor.collidelistall(pockets)
if len(in_pocket) > 0 and b.pocketed == False:
if b != cue_ball:
b.movement[0] = (pockets[in_pocket[0]].x - b.actor.x) / 20
b.movement[1] = (pockets[in_pocket[0]].y - b.actor.y) / 20
b.pocket = pockets[in_pocket[0]]
balls_pocketed.append(b)
else:
b.x = WIDTH//2
b.y = HEIGHT//2

First, I use the colliderect() function to check if any of the balls collide this frame – if they do, I add them to a list. This is so I handle all the movement first and then the collisions. Otherwise, I’m changing the momentum of balls that haven’t moved yet. I detect whether a pocket was hit as well; if so, I change the momentum so that the ball heads towards the pocket and doesn’t bounce off the walls anymore.

When all my balls have been moved, I can handle the collisions with both the other balls and the pockets:

for col in collisions:
col[0].collide(col[1])
if shot == False:
for b in balls_pocketed:
balls.remove(b)

And there you have it: the beginnings of an arcade pool game in the Side Pocket tradition. You can get the full code and assets right here.

Get your copy of Wireframe issue 36

You can read more features like this one in Wireframe issue 36, available directly from Raspberry Pi Press — we deliver worldwide. And if you’d like a handy digital version of the magazine, you can also download issue 36 for free in PDF format.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

The post Make a Side Pocket-esque pool game | Wireframe #36 appeared first on Raspberry Pi.

SD Card Speed Test

via Raspberry Pi

Since we first launched Raspberry Pi, an SD card (or microSD card) has always been a vital component. Without an SD card to store the operating system, Raspberry Pi is pretty useless*! Over the ensuing eight years, SD cards have become the default removable storage technology, used in cameras, smartphones, games consoles and all sorts of other devices. Prices have plummeted to the point where smaller size cards are practically given away for free, and at the same time storage capacity has increased to the point where you can store a terabyte on your thumbnail.

SD card speed ratings, and why they matter

However, the fact that SD cards are now so commonplace sometimes conceals the fact that not all SD cards are created equal. SD cards have a speed rating – how fast you can read or write data to the card – and as card sizes have increased, so have speed ratings. If you want to store 4K video from your digital camera, it is important not just that the card is big enough to hold it, but also that you can write it to the card fast enough to keep up with the huge amount of data coming out of the camera.

The speed of an SD card will also directly affect how fast your Raspberry Pi runs, in just the same way as the speed of a hard drive affects how fast a conventional desktop computer runs. The faster you can read data from the card, the faster your Raspberry Pi will boot, and the faster programs will load. Equally, write speed will also affect how well any programs which save large quantities of data run – so it’s important to use a good-quality card.

What speed can I expect from my SD card?

The speed rating of an SD card should be printed either on the card itself or on the packaging.

The 32GB card shown below is Class 4, denoted by the 4 inside the letter C – this indicates that it can write at 4MB/s.

The 64GB card shown below is Class 10, and so can write at 10MB/s. It also shows the logo of UHS (“ultra high speed”) Class 1, the 1 inside the letter U, which corresponds to the same speed.

More recently, speeds have started to be quoted in terms of the intended use of the card, with Class V10 denoting a card intended for video at 10MB/s, for example. But the most recent speed categorisation – and the one most relevant to use in a Raspberry Pi – is the new A (for “application”) speed class. We recommend the use of Class A1 cards (as the one above – see the A1 logo to the right of the Class 10 symbol) in Raspberry Pi – in addition to a write speed of 10MB/s, these support at least 1500 read operations and 500 write operations per second. All the official Raspberry Pi microSD cards we sell meet this specification.

A new tool for testing your SD card speed

We’ve all heard the stories of people who have bought a large capacity SD card at a too-good-to-be-true price from a dodgy eBay seller, and found that their card labelled as 64GB can only actually hold 2GB of data. But that is at least fairly easy to spot – it’s much harder to work out whether your supposedly fast SD card is actually meeting its specified speed, and unscrupulous manufacturers and sellers often mislabel low quality cards as having unachievable speeds.

Today, as the first part of a new suite of tests which will enable you to perform various diagnostics on your Raspberry Pi hardware, we are releasing a tool which allows you to test your SD card to check that it performs as it should.

To install the new tool, from a terminal do

sudo apt update
sudo apt install agnostics

(“agnostics”? In this case it’s nothing to do with religion! I’ll leave you to work out the pun…)

Once installed, you will find the new application “Raspberry Pi Diagnostics” in the main menu under “Accessories”, and if you launch it, you’ll see a screen like this:

In future, this screen will show a list of the diagnostic tests, and you will be able to select which you want to run using the checkboxes in the right-hand column. But for now, the only test available is SD Card Speed Test; just press “Run Tests” to start it.

Understanding your speed test results

One thing to note is that the write performance of SD cards declines over time. A new card is blank and data can be written to what is effectively “empty” memory, which is fast; but as a card fills up, memory needs to be erased before it can be overwritten, and so writes will become slower the more a card is used. The pass / fail criteria in this test assume a new (or at least freshly formatted) card; don’t be alarmed if the write speed test fails when run on the SD card you’ve been using for six months! If you do notice your Raspberry Pi slowing down over time, it may be worth backing up your SD card using the SD Card Copier tool and reformatting it.

The test takes a minute or so to run on a Raspberry Pi 4 (it’ll take longer on older models), and at the end you’ll see a results screen with either (hopefully) PASS or (if you are less fortunate) FAIL. To see the detailed results of the speed test, press “Show Log”, which will open the test log file in a text editor. (The log file is also written to your home directory as rpdiags.txt.)

We are testing against the A1 specification, which requires a sequential write speed of 10MB/s, 500 random write operations per second, and 1500 random read operations per second; we run the test up to three times. (Tests of this nature are liable to errors due to other background operations accessing the SD card while the test is running, which can affect the result – by running the test multiple times we try to reduce the likelihood of a single bad run resulting in a fail.)

If the test result was a pass, great! Your SD card is good enough to provide optimum performance in your Raspberry Pi. If it failed, have a look in the log file – you’ll see something like:

Raspberry Pi Diagnostics - version 0.1
Mon Feb 24 09:44:16 2020

Test : SD Card Speed Test
Run 1
prepare-file;0;0;12161;23
seq-write;0;0;4151;8
rand-4k-write;0;0;3046;761
rand-4k-read;9242;2310;0;0
Sequential write speed 4151 kb/s (target 10000) - FAIL
Note that sequential write speed declines over time as a card is used - your card may require reformatting
Random write speed 761 IOPS (target 500) - PASS
Random read speed 2310 IOPS (target 1500) - PASS
Run 2
prepare-file;0;0;8526;16
...

You can see just how your card compares to the stated targets; if it is pretty close to them, then your card is only just below specification and is probably fine to use. But if you are seeing significantly lower scores than the targets, you might want to consider getting another card.



[*] unless you’re using PXE network or USB mass storage boot modes of course.

The post SD Card Speed Test appeared first on Raspberry Pi.

Make a Spy Hunter-style scrolling road | Wireframe #31

via Raspberry Pi

Raspberry Pi’s own Mac Bowley shows you how to make the beginnings of a top-down driving game inspired by 1983’s Spy Hunter.

Spy Hunter, an arcade game from 1983

Spy Hunter was one of the very first games with both driving and shooting.

Spy Hunter

The 1983 arcade classic Spy Hunter put players at the wheel of a fictitious Interceptor vehicle and challenged them to navigate a vertically scrolling road, destroying enemy vehicles.

Here, I’ll show you how you can recreate the game’s scrolling road to use in your own driving games. The road will be created using the Rect class from Pygame, with the road built from stacked rectangles that are each two pixels high.

Making the scrolling road in Python

First, I create two lists; one to hold the pieces of road currently being drawn on screen, and another to hold a queue of pieces that will be added as the road scrolls. To create the scrolling road effect, each of the current pieces of road will need to move down the screen, while a new piece is added to the end of the list at position y = 0.

Pygame can schedule functions, which can then be called at set intervals – meaning I can scroll my road at a set frame rate. The scroll_road function will achieve this. First, I loop over each road piece, and move it down by two pixels. I then remove the first item in the queue list and append it to the end of the road. The Pygame clock is then set to call the function at intervals set by a frame_rate variable: mine is set to 1/60, meaning 60 frames per second.

Our top-down rolling road in Python

Our code snippet provides a solid basis for your own top-down driving game. All you need now are weapons. And a few other cars.

My road can either turn left or right, a random choice made whenever the queue is populated. Whichever way the road turns, it has to start from the same spot as the last piece in my queue. I can grab the last item in a list using -1 as an index and then store the x position; building from here will make sure my road is continuous. I use a buffer of 50 pixels to keep the road from moving off the edge of my screen – each time a turn is made, I check that the road doesn’t go beyond this point.

I want the turn amount to be random, so I’m also setting a minimum turn of 200 pixels. If this amount takes my car closer than the buffer, I’ll instead set the turn amount so that it takes it up to the buffer but no further. I do this for both directions, as well as setting a modifier to apply to my turn amount (-1 to turn left and 1 to turn right), which will save me duplicating my code. I also want to randomly choose how many pieces will be involved in my turn. Each piece is a step in the scroll, so the more pieces, the longer my turn will take. This will make sure I have a good mix of sharp and elongated turns in my road, keeping the player engaged.

Our rolling road Python code

Here’s Mac’s code snippet, which creates a winding road worthy of Spy Hunter in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code, go here.

Speeding up the game

To make things more exciting, the game can also be speeded up by decreasing the frame_rate variable. You could even gradually increase this over time, making the game feel more frantic the further you get.
Another improvement would be to make the turns more curvy, but make sure you’re comfortable with algebra before you do this!

Get your copy of Wireframe issue 31

You can read more features like this one in Wireframe issue 31, available now at Tesco, WHSmith, all good independent UK newsagents, and the Raspberry Pi Store, Cambridge.

Or you can buy Wireframe directly from Raspberry Pi Press — delivery is available worldwide. And if you’d like a handy digital version of the magazine, you can also download issue 31 for free in PDF format.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

The post Make a Spy Hunter-style scrolling road | Wireframe #31 appeared first on Raspberry Pi.

Vulkan is coming to Raspberry Pi: first triangle

via Raspberry Pi

Following on from our recent announcement that Raspberry Pi 4 is OpenGL ES 3.1 conformant, we have some more news to share on the graphics front. We have started work on a much requested feature: an open-source Vulkan driver!

Vulkan

Standards body Khronos describes Vulkan as “a new generation graphics and compute API that provides high-efficiency, cross-platform access to modern GPUs”. The Vulkan API has been designed to better accommodate modern GPUs and address common performance bottlenecks in OpenGL, providing graphics developers with new means to squeeze the best performance out of the hardware.

First triangle

The “first triangle” image is something of a VideoCore graphics tradition: while I arrived at Broadcom too late to witness the VideoCore III version, I still remember the first time James and Gary were able to get a flawless, single-tile, RGB triangle out of VideoCore IV in simulation. So, without further ado, here’s the VideoCore VI Vulkan version.

First triangle out of Vulkan

Before you get too excited, remember that this is just the start of the development process for Vulkan on Raspberry Pi. Igalia has only been working on this new driver for a few weeks, and we still have a very long development roadmap ahead of us before we can put an actual driver in the hands of our users. So don’t hold your breath, and instead look forward to more news from us and Igalia as they make further development progress.

The post Vulkan is coming to Raspberry Pi: first triangle appeared first on Raspberry Pi.