Raspberry Pi Game Show

Updated 15 September 2022

Introduction

I made this project because I had been given a Raspberry Pi 4 for Christmas and was hoping to make a fun project with it. I wanted to make something which wasn’t just copying a tutorial and was actually my own. I also hoped to learn to use the GPIO pins and incorporate them into it.

I decided to make a Quiz Show. As I didn’t have a big budget, I thought that maybe I could make the contestant's buzzers myself.

the gameshow being played with different colour buttonsthe gameshow being played with different colour buttons

Table of Contents

What You’ll Need

Make the Buttons

First, you need to put your Paper Clay into your rounded moulds. Open the pot and make sure that you knead the clay well first. When you put it into the mould ensure that there are no air bubbles. A good way to do this is by putting it into the centre and gently spreading it outwards. Now, carefully smooth the top. (This will become the bottom when you assemble it.) Repeat this step, so that you have 3 buttons. These will take a few days to dry. When it has dried, use a blunt knife, or something else thin to gently peel it away from the edges. Once you’ve peeled it from the edge, gently pull it out. If the rounded side (which is the top) is still wet then leave it a few hours to finish drying.

 

Now, we’re going to prepare the other parts of the buttons. Get your rigid sheet and cut 3 pieces from it that are larger than the paper clay buttons. Now cut 6 pieces from your thick cardboard that are about the same length as the pieces you just cut. The width should be ~12mm. Also, cut 3 more pieces of thick cardboard. These should also have a width of ~12mm, but the length should be a bit less than half the diameter of your buttons.

 

Next, we will construct the buttons. Please refer to the diagram below for the building steps:

 

All materials laid out for making buttonsAll materials laid out for making buttons

Gather all your materials.

 

Create matching holes on your board and add a spring to each leg.

 

Inserting two paper fastenersInserting two paper fasteners

Insert two paper fasteners into your board.

 

 

Adding glue to each skewer leg to hold them in placeAdding glue to each skewer leg to hold them in place

Use a touch of glue to hold each leg in place.

 

the skewer cut into 4 equal lengthsthe skewer cut into 4 equal lengths

Cut your skewer into four.

 

Attaching foil to cardboardAttaching foil to cardboard

Glue the foil to the small cardboard block.

 

 

Splaying the paper fasteners so that they staySplaying the paper fasteners so that they stay

Flatten the paper fasteners. Ensure they don’t touch each other.

 

Final assembly clay is mounted to sign board assemblyFinal assembly clay is mounted to sign board assembly

Assemble and test your button!

 

Skewers inserted into paper claySkewers inserted into paper clay

Gently insert the skewers vertically.

 

Attaching foil to underside of button assemblyAttaching foil to underside of button assembly

Glue the foiled block to the button.

 

 

Gluing cardboard blocks onto bottom of sign boardGluing cardboard blocks onto bottom of sign board

Glue the two cardboard blocks onto the back of the board.

 

The Code

Now we’re going to start coding. If you want to just download it all, you can skip to the Quick Version at the bottom of the page.

 

First we will install some python packages we will need. Open up the terminal on your Raspberry Pi and type in

pip3 install pyside2 keyboard pyqt5 vlc quantumrandom gtts

This might take a couple of minutes.

 

Click here to download “Main Quiz.py” to a directory for this project. This will be the file that you run. Now, we can unpack the code in here.

We start by importing a few modules that we will use later in our code.

from PySide2 import QtWidgets
from PySide2.QtCore import *
from os import system
from ColourSet import setG, setR, setY, setW
from Ui_MainWindow import Ui_MainWindow
from Ui_ScoreWindow import Ui_ScoreWindow
from Ui_WinnerWindow import Ui_MainWindow as Ui_WinnerWindow
import Qs
import keyboard
from time import sleep
from threading import Thread
import gpiozero
import Player1
import Player2
import Player3
import gtts
import os
import sys
import filler

Don’t worry that there are some modules in here that you don’t have yet. We will create these later.

 

Next, we set some variables.

status = 0
index = 0
Player1.name = "Player1"
Player1.score = 0
Player1.button = gpiozero.Button(2)

 

The status variable holds a number which defines what is currently happening. E.g. 1 is for when a question has been shown and the program is waiting for contestants to answer. The index variable contains a number defining the index of the next question to be shown. The next lines of code define a few variables for Player1. We repeat this code for the other 2 players. Change the name variable to the name of the first player and then repeat for players 2 and 3.

 

After that, we create some audio files.

try:
    tts = gtts.gTTS(Player1.name)
    tts.save("Data/Player1.mp3")
    tts = gtts.gTTS(Player2.name)
    tts.save("Data/Player2.mp3")
    tts = gtts.gTTS(Player3.name)
    tts.save("Data/Player3.mp3")
except:
    print("There is no internet. The gTTS engine will not work.\nThe files from last time this program was run will be used.")

Here, we are using a text-to-speech engine to convert the players’ names to audio files. We use the try and except structure because our text-to-speech engine requires internet, and if there isn’t internet it will stop the program.

 

Next, we define some variables relating to the question bank.

Questions = Qs.Questions
As = Qs.As
Bs = Qs.Bs
Cs = Qs.Cs
Ds = Qs.Ds
Answers = Qs.Answers 

 

We set 6 variables to the quiz questions, options and answers. We use these variables later in our code.

Now, we are going to define our first function.

def quizManager():
    Thread(target = updater).start()
    Thread(target = keyCheck).start()
    Thread(target = buzzCheck).start()
    Thread(target = winCheck).start()

 

This function calls “Thread” a few times. Thread allows us to run multiple pieces of code simultaneously. We create a few different threads which run various other functions.

Next we define a function that is called when we want to progress to the next question.

def next():

 

Within this function, we set everything to have a white background and show the next question and options.

This next function shows the answer, and whether the player was correct.

def showAnswer():

 

There’s quite a lot happening in this function, so we’ll only look at the key parts. We check whether the answer that the contestant gave is correct. We play an audio track - we’ll look at this later - and we change the colour of the correct answer and the answer that the player chose.

This function checks to see if any of the contestants have pressed their “buzzers”.

def buzzCheck():

 

We first check to see if the code is waiting for someone to press their buzzer. If someone has pressed their buzzer, we then play their name and a buzz sound effect, and change the status to show that they have “buzzed”.

After that, we have a function to detect key presses. 

def keyCheck():

 

The “Quizmaster” uses a keyboard to interact with the python script. Depending on what key they press, different things will happen. First the code checks the status, and then depending on what that is, it checks whether various keys have been pressed. It then calls one of several functions which progress the quiz.

Now, we have a function that is called when a player answers the question.

def answered():
    global answer, status
    if answer == "a":
        setY(MainUi.Option_A)
        status = 3
    elif answer == "b":
        setY(MainUi.Option_B)
        status = 3
    elif answer == "c":
        setY(MainUi.Option_C)
        status = 3
    elif answer == "d":
        setY(MainUi.Option_D)
        status = 3

 

When it is called, it sets the background colour of the option that the player chose to yellow. (We will define setY later.) It also changes the status variable to show that the player has answered.

This final function runs in the background, and checks to see if anyone has won.

def winCheck():

 

If any of the player’s scores have reached 100, it sets a variable to show that they’ve won. It then displays a window that says that they’ve won, and plays an audio track.

At the bottom is a little bit of code that displays the main question window, and the score window. It also starts a few background processes running.

Now, download the “ColourSet.py” file into the same folder as “MainQuiz.py”.

This function changes the background colour of the item it receives.

def setG(item):
    item.setStyleSheet(u"background-color: rgb(0, 170, 0);")

 

When we call this function, we have to put an object from our GUI into the brackets. E.g. setG(MainUi.Question)

It will then change the background colour of that item to green. We then repeat this function for red, yellow, and white.

Create 4 empty files called “Player1.py”, “Player2.py”, “Player3.py”, and “Filler.py” in your main directory for this project. While these files are empty, they are still very important for the overall program.

Download the file “resource_rc.py” to your main project directory. It contains a lot of lines, because it is all of the data that specifies an image used in the GUI.

Create a file called “AllQs.py” in your main project directory. This will contain all of the questions.

I’ve put 100 questions in, but you probably don’t need quite that many. Fill it up with your questions in this format:

AllQs = [[Question 1, Choice A, Choice B, Choice C, Choice D, Answer],
[Question 2, Choice A, Choice B, Choice C, Choice D, Answer]]

 

Start by setting the variable to a list, each question should then be another list within that list. Make sure that at the start and end of the main list you use double square brackets. Here are my first few questions:

AllQs = [["Which planet is the hottest?","A: Venus","B: Saturn","C: Mercury","D: Mars","A"],

["Fe is the chemical symbol for what?","A: Zinc","B: Hydrogen","C: Fluorine","D: Iron","D"],

["What does the 'U' stand for in 'UFO'?","A: Unidentified","B: Under","C: United","D: Unique","A"]]

 

If you don’t want to make your own questions, you can download “AllQs.py” here.

Now, download “GetQ.py” to your main project directory.

First, we import a few modules.

import random
import quantumrandom as qrng
from NoInternet import noInternet
from AllQs import AllQs

 

We use the two random modules to get a random question. The NoInternet module we will create in a minute, and displays a message if there is no internet connection.

We now define some variables.

GetQ = AllQs

notprinted = True

 

GetQ is used so that we only see each question once during each quiz, and the second is to make sure that the user only sees the no internet message once.

This function will get a random question from the bank of questions.

def getQ():

 

First we try to use a true-random number generator to pick an index for a question. We round the number to an integer value. This module only works on the internet, and will return an error if there isn’t a connection. To fix this, we use a try and except structure. If there isn’t internet, the program will display the no internet message. Then, it will use an alternative pseudo-random number generator to select a question index. The selected question is then removed from a copy of the main question list, to prevent it from being shown again during the quiz. Finally, the question is passed back to the script which called getQ.

Next, download “Qs.py” to the project folder. This function shuffles the questions, so that they are ready to be displayed.

We define a few variables first.

Questions = []
As = []
Bs = []
Cs = []
Ds = []
Answers = []

 

These will hold the respective parts of the questions drawn from the bank.

This function gets random questions and sorts the parts.

for i in range(100):
    tempQ = getQ()
    Questions.append(tempQ[0])
    As.append(tempQ[1])
    Bs.append(tempQ[2])
    Cs.append(tempQ[3])
    Ds.append(tempQ[4])
    Answers.append(tempQ[5])

 

First of all, change 100 to the number of questions that are in your question bank. The script fetches a random question, and appends each of its parts (Question, Option A etc.) to their respective lists. It repeats this for every other question.

Download “NoInternet.py” to your project directory. This file simply displays a message to say that there is no internet connection when it gets called.

Download “Ui_MainWindow.py”, “Ui_ScoreWindow.py”, and “Ui_WinnerWindow.py” to your project directory. These are the three graphical user interfaces for this project.

“Ui_MainWindow.py” displays the questions, “Ui_ScoreWindow.py” displays the scores, and “Ui_WinnerWindow.py” shows when someone wins.

The code defines how the GUIs should look. I used a software package to create the GUIs. If you want to create your own, then there are various packages that will help you do so.

Finally, download our last file: “Audio.py”. This controls the audio for the project.

 

I’m not sure why, but the audio wouldn’t play in the main script, so I found a workaround to allow us to play it in a different script.

while True:
    with open("Data/Audio.txt", "r+") as file:

 

Within our while True loop, we use a with statement. This means that we define a variable only within that piece of code. When we open a file in python, it needs to be closed again or excess memory will be taken up and any content written to it can be lost. Our with statement means that the file will automatically be closed, and then opened again when the loop next runs. If you would like to learn more about python and files, I suggest that you have a look at the Python documentation.

 

Here, we are reading the data from the file and dumping it into a variable.

text = file.read()

 

First, we check if the text from our file is set to Wrong. If so, the audio file is played. The text file is reset to blank to prevent the audio track being played when we don’t want it. We wait for the audio to be finished, and then stop it, to clear up some memory. This is repeated for all other sound effects.

if text == "Wrong":
        media = vlc.MediaPlayer("Data/Wrong.wav")
       media.play()
       file.write(" ")
       sleep(0.1)
       while media.is_playing() == 1:
              sleep(0.1)
       media.stop()

 

My quiz could be adapted to have more players, but the GUI and code would need to be tweaked to include more.

The Quick Version

Head down to the attachments section to find all of the files you need for this project in a .zip file. Unzip the file, and you should have everything you need.

In a terminal window, run this command:

pip3 install pyside2 keyboard pyqt5 vlc quantumrandom gtts

 

Head down to the attachments section to find all of the files you need for this project in a .zip file. Unzip the file, and you should have everything you need.

In a terminal window, run this command:

pip3 install pyside2 keyboard pyqt5 vlc quantumrandom gtts

Set-Up

To set up your quiz, you need to connect the buttons to your Raspberry Pi as shown in the picture below.

Raspberry Pi button connection diagramRaspberry Pi button connection diagram

 

Now, you need to open a python editor of your choice with ‘sudo’ (admin) privileges. If you want to use my preferred python editor mu, open a terminal window and type in:

sudo mu-editor

Next, you need to launch a python editor of your choice (this can be the same editor as before), without sudo privileges. Open and run “Audio.py” in this window.

In your ‘sudo’ window, open and run “Main Quiz.py”. To control the quiz, there are some keyboard controls.

 

Gameshow starting screenGameshow starting screen

First, the Quizmaster needs to press the right arrow key to show the first question.

 

A player selects an answer on screen, their column side of the screen lights upA player selects an answer on screen, their column side of the screen lights up

When that player answers, the Quizmaster types in the player’s answer (A, B, C, or D).

 

The screen turns green if the correct answer is selected points increaseThe screen turns green if the correct answer is selected points increase

After that, the Quizmaster then presses the right arrow to show the next question.

 

After the quizmaster starts the gameAfter the quizmaster starts the game

Next, when a player thinks they know the answer, they press their buzzer.

 

Quizmaster before showing the correct answerQuizmaster before showing the correct answer

When the Quizmaster is ready, they press the spacebar to show the correct answer.

 

Two players having fun with the gameshowTwo players having fun with the gameshow

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.