KBC Game in Python

Dec 19, 2019

KBC Game in Python

Using Pygame and Python 3 to re-create the famous Kaun Banega Crorepati quiz game.

Author

Vikram Kumar
Vikram KumarSoftware Engineer

Hello Everyone! You all must have watched or heard about the very famous Television game show called KBC(Kaun Banega Crorepati), originally Who Wants to Be a Millionaire?. I took a chance to re-create that popular game show and refresh all those good old memories which we got sitting in front of the TV Screen.

Let’s Get Started

I have used Pygame module of Python 3 to create the game. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries that are designed to be used with the Python programming language.
So, before proceeding further, make sure you have Python 3 and Pygame module installed in your system.
First, we need to define some color constant, amount list and question data set consisting of questions, options and its correct answers. You can create a custom question data set in a separate .json file or as a list of map objects in same file. I have used the latter option.

Setting Display Window

We can set our game screen display window to a fixed resolution and add title to our display window. Now we need to add some background properties to it to make it look more interactive. We can use an image as background and scale it to our desired resolution or just use color as background. I have used an image. Make sure you do all these things in the constructor of the class. Below is the code snippet for all that stuff:

    def __init__(self):
        pygame.init()
        pygame.display.set_caption('KBC Pygame')
        self.screen = pygame.display.set_mode((1366, 768), 0, 32)
        self.addBackgroudPic()
        self.font = pygame.font.SysFont('Arial', 25)
        self.bigFont = pygame.font.SysFont('Arial', 50)

    def addBackgroudPic(self):
        bg = pygame.image.load("kbc.jpg")
        bg = pygame.transform.scale(bg, (1366, 768))
        self.screen.blit(bg, (0, 0)) #To draw surface on screen at given position (x,y) 

Before Proceeding further let me tell you one thing, all the positional parameters I have used in below code is in relative to the game screen window size.So you have to adjust your positional parameters according to your window size.

Creating First Screen-Game Play Settings


First of all we have to notify users about how to play game. Pygame can detect keyboard events, so we have used onKeyPress for event handling. We can display text on Screen using the render method. We can also add font color and position to text.
Below is the code snippet for this part for better understanding:-

def gameRules(self):
        self.addBackgroudPic()
        readRules = True
        isPlay=True
        while readRules:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        readRules = False
                    if event.key == pygame.K_q:
                        pygame.quit()
                        quit()
            self.displayText("Welcome to KBC Game For Developers",
                             self.red,
                             630, 50, True
                             )
            self.displayText("Game Rules:-",
                             self.green,
                             680, 100, True)
            self.displayText("Press A/B/C/D to select corresponding options",
                             self.orange,
                             680, 150, True)
            self.displayText("Press P to play or Q to quit.",
                             self.WHITE,
                             660, 650, True)
            # if isPlay:
            #     playsound("KBCIntro.mp3")
            #     isPlay = False
            pygame.display.update()

def displayText(self, text, color, xCordinate, yCordinate=0, isBig=False):
        if isBig:
            textSurface = self.bigFont.render(text, True, color)
        else:
            textSurface = self.font.render(text, True, color)
        textRectangle = textSurface.get_rect()
        textRectangle.center = (xCordinate, yCordinate)
        self.screen.blit(textSurface, textRectangle)

One thing we need to make sure of is to call pygame.display.update() wherever required. It re-renders the screen with updated values just like setstate in React. 

Creating Game Play Screen

This is the main screen of the game where all fun stuff happens. It keeps track of the current status of the game and keeps us engaged with some interesting challenging questions.
This screen has a common component 'Rounded Rectangular Box' which is used as a basic building block for UI of this screen. You can find code for this component here
Now coming to the main UI part of this screen, first of all we have to add Price Tile which is nothing but a list of rounded rectangular boxes which contain the respective amount prize according to its level. The current level is denoted by red background color. Below is the code snippet for that:-

 def addPriceTile(self):
        yCordinate = 50
        yCordinateText = 75
        for index in range(11):
            if 10-index == self.currentQuestion:
                self.RoundedRectangle(
                    (50, yCordinate, 200, 50), self.red, 0.5)
            else:
                self.RoundedRectangle(
                    (50, yCordinate, 200, 50), self.navyBlue, 0.5)
            self.displayText(self.amount[index],
                             self.WHITE, 150, yCordinateText)
            yCordinate += 60
            yCordinateText += 60

Now we have to just add a Question Box and an Option Box. In Question Box, we have to just render a large rectangular rounded box with the question as text on that surface. For Options, we have to render four small rectangular rounded boxes with their corresponding options as text. To make it more interactive, I have added a change in background color whenever user selects any option.Below is the code snippet for this part:-

   def addQuestionBox(self):
        self.RoundedRectangle(
            (320, 450, 950, 100), self.navyBlue, 0.5)
        self.displayText(
            self.questionList[self.currentQuestion]["question"], self.WHITE, 825, 500)

    def addOptionBox(self, isCorrect=False):
        yCordinate = 560
        yCordinateText = 580
        xCordinate = 320
        xCordinateText = 450
        options = self.questionList[self.currentQuestion]["options"]
        for index in range(len(options)):
            if self.selectedAnswer == index:
                if isCorrect:
                    self.RoundedRectangle(
                        (xCordinate, yCordinate, 300, 50), self.green, 0.5)
                else:
                    self.RoundedRectangle(
                        (xCordinate, yCordinate, 300, 50), self.red, 0.5)
            else:
                self.RoundedRectangle(
                    (xCordinate, yCordinate, 300, 50), self.navyBlue, 0.5)
            self.displayText(
                options[index], self.WHITE, xCordinateText, yCordinateText)
            if(index % 2 == 0):
                xCordinate = 950
                xCordinateText = 1070
            else:
                xCordinate = 320
                yCordinate = 620
                xCordinateText = 450
                yCordinateText = 640

Now we have to just merge all sub part of this screen into one which will act as the starting point of this screen. Here is the code snippet for this one:-

    def playGame(self):
        playsound("KBCIntro.mp3")
        self.addBackgroudPic()
        self.addPriceTile()
        self.addQuestionBox()
        self.addOptionBox()
        correctAnswer = self.questionList[self.currentQuestion]["answer"]
        play = True
        proceed = True
        isPlay = True
        while play:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        # self.currentQuestion += 1
                        self.resultScreen()
                    elif (event.key in [pygame.K_a, pygame.K_b, pygame.K_c, pygame.K_d]):
                        isCorrect = self.validateAnswer(
                            correctAnswer, event.key)
                        self.addOptionBox(isCorrect=isCorrect)
                        pygame.display.update()
                        pygame.time.delay(2000)
                        if isCorrect:
                            self.currentQuestion += 1
                            self.selectedAnswer = -1
                            if self.currentQuestion > 10:
                                # Winner Screen
                                self.resultScreen()
                            else:
                                correctAnswer = self.questionList[self.currentQuestion]["answer"]
                                self.addPriceTile()
                                self.addQuestionBox()
                                self.addOptionBox()
                                pygame.display.update()
                                playsound("KbcQuestion.mp3")
                        else:
                            play = False
                            pass
                            # GameOver
                            self.resultScreen(isLost=True)
            pygame.display.update()
            if isPlay:
                playsound("KbcQuestion.mp3")
                isPlay = False


Creating Result Screen

This Screen is similar to the first screen. We have just replaced gameplay settings description text with final result description text. You can refer to the github repo for its code.

That’s all folks! This game is ready to play now. I hope you had a good time reading this. You can find the GitHub repo for the game here. You can refer to it for better understanding in case I missed out on something important. You can also add various new features to it also.

I am Vikram Kumar working as a Software Engineer Intern at GeekyAnts. Do reach out to me if you require assistance or anything else at all. I will be happy to help you.

Thank you. Bye Bye!

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Taming Elasticsearch at Scale
Oct 13, 2026

Taming Elasticsearch at Scale

Optimize Elasticsearch for millions of records with better pagination, leaner payloads, efficient filtering, faster ingestion, and frontend techniques that keep search responsive with increase in data.

Insight
Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide
Oct 13, 2026

Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide

Build a self-hosted deep linking and referral system for React Native without a third-party SDK. This guide covers Android App Links, iOS Universal Links, an S3 and CloudFront setup, and a NestJS backend that routes users to the right app store.

Insight
How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform
Oct 12, 2026

How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform

This blog explains how a real-time sports platform uses synchronous, asynchronous, and scheduled processing paths to handle rewards without slowing down the player experience.

Insight
Building an MCP-Powered QA Agent
Oct 12, 2026

Building an MCP-Powered QA Agent

Build an MCP QA agent that runs Playwright tests, validates APIs, and analyzes failures through a controlled, auditable tool layer with human approval.

Insight
From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline
Oct 9, 2026

From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline

This blog explains how an AI-assisted Playwright pipeline can analyze test failure evidence, identify probable root causes, and support human-validated debugging.

Insight
The Model Context Protocol: From First Call to Production
Oct 8, 2026

The Model Context Protocol: From First Call to Production

This blog explains how Model Context Protocol (MCP) works, from tool discovery and execution to OAuth authorization, security controls, and production deployment.

Insight
Stop Automating Everything: A Balanced Quality Engineering Approach to Testing
Oct 8, 2026

Stop Automating Everything: A Balanced Quality Engineering Approach to Testing

Balanced quality engineering places automation, API testing, exploratory work, and AI where each gives the most value, so teams ship faster without trading away user-perceived quality.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call