Python Pinball Game Project with Source Code

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Have you ever played the pinball game? Isn’t it a challenging and occupying one! Wouldn’t it be more fascinating to build such a game on your own? Yes! In this project, we will be developing the Pinball game using simple modules in Python.

What is Pinball?

A pinball game is a game in which we use a paddle to hit the bouncing ball. The score increases every time we hit the ball. And the game ends once we miss the hit.

Pinball Game using Python

We will be using the turtle and the random modules to build the project. The turtle module helps to build the game window and the components and controls the game. We use the random module to give a random position for the ball to start the game.

Download Python Pinball Project

Please download the source code for the python pinball game using the link: Pinball Game Project Code

Project Prerequisites

It is required to have prior knowledge of Python and the turtle module to build the project. You can download the turtle and the random module using the below commands.

pip install random2
pip install turtle

Project Structure

The following steps will be followed to develop python pinball game.

1. Importing the required modules

2. Create a screen for game

3. Create the paddle

4. Create the ball

5. Create the scoreboard

6. Write function to move the paddle

7. The main game loop

1. Importing the required modules

# Importing the turtle and random library
import turtle
from random import randint

Code explanation:

a.  In this step we import the turtle and the random modules.

b.  randint in the random module helps in getting a random integer in the given range.

2. Create a screen for game

# Creating the screen with name and size
screen = turtle.Screen()
screen.title("DataFlair Pinball game")
screen.setup(width=1000 , height=600)

Code explanation:

In this step, we create the Screen() object with title and size

3. Create the paddle

# Creating the paddle
paddle = turtle.Turtle()
#Setting its speed as zero, it moves only when key is pressed
paddle.speed(0) 
#Setting shape, color, and size
paddle.shape("square")
paddle.color("blue")
paddle.shapesize(stretch_wid=2, stretch_len=6) 
paddle.penup()
#The paddle is left-centered initially 
paddle.goto(-400,-250)

Code explanation:

Now, we create a square paddle that moves only when the keyboard is pressed.
Initially, it stays in the leftmost positions and moves in the respective direction when the player presses left/right keyboard buttons.

4. Create the ball

# Creating the ball of circle shape
ball = turtle.Turtle()
#Setting the speed of ball to 0, it moves based on the dx and dy values
ball.speed(0)
#Setting shape, color, and size
ball.shape("circle")
ball.color("red")
ball.penup()
#Ball starts from the random position from the top of the screen
x=randint(-400,400)
ball.goto(x, 260)
#Setting dx and dy that decide the speed of the ball
ball.dx = 2
ball.dy = -2

Code explanation:

a.  Next, we create the ball with a circle shape.

b.  It starts from the top of the screen from a random position along the horizontal axis.

c.  The variables dx and dy decide the speed of the ball, whose position gets updated by these values every time.

5. Create the scoreboard

score=0

# Displaying the score
scoreBoard = turtle.Turtle()
scoreBoard.speed(0)
scoreBoard.penup()
#Hiding the turtle to show text
scoreBoard.hideturtle()
#Locating the score board on top of the screen
scoreBoard.goto(0, 260)
#Showing the score
scoreBoard.write("Score : 0 ", align="center", font=("Courier", 20, "bold"))

Code explanation:

a.  Now we create the scoreboard with the score updating every time paddle hits the ball.

b.  This is located on top of the screen.

6. Write a function to move the paddle

# Functions to move the paddle left and right
def movePadRight():
    x = paddle.xcor() #Getting the current x-coordinated of the paddle
    x += 15 
    paddle.setx(x) #Updating the x-coordinated of the paddle

# Function to move the left paddle down
def movePadLeft():
    x = paddle.xcor() #Getting the current x-coordinated of the paddle
    x -= 15 
    paddle.setx(x) #Updating the x-coordinated of the paddle

#Mapping the functions to the keyboard buttons
screen.listen()
screen.onkeypress(movePadRight, "Right")
screen.onkeypress(movePadLeft, "Left")

Code explanation:

a.  Then we create the two functions movePadRight() and movePadLeft() that move the paddle to left and right respectively by 15 units every time the user presses the right/left key.
b.  The method onkeypress() maps the function to the respective keyboard buttons.
c.  And the listen() function makes sure the keyboard inputs are considered.

7. The main game loop

while True:
    #Updating the screen everytime with the new changes
    screen.update()
    
    ball.setx(ball.xcor()+ball.dx)
    ball.sety(ball.ycor()+ball.dy)

    # Checking if ball hits the left, right, and top walls of the screen  
    if ball.xcor() > 480:
        ball.setx(480)
        ball.dx *= -1 #Bouncing the ball 
 
    if ball.xcor() < -480:
        ball.setx(-480)
        ball.dx *= -1#Bouncing the ball 
    
    if ball.ycor() >280:
        ball.setx(280)
        ball.dy *= -1#Bouncing the ball 
    
    #Checking if the ball hits bottom and ending the game
    if ball.ycor() < -260:
        scoreBoard.clear()
        scoreBoard1 = turtle.Turtle()
        scoreBoard1.speed(0)
        scoreBoard1.penup()
        #Hiding the turtle to show text
        scoreBoard1.hideturtle()
        #Locating the score board on top of the screen
        scoreBoard1.goto(0, 0)
        scoreBoard1.color('black')
        #Showing the score
        scoreBoard1.write("Score : {} ".format(score),    align="center", font=("Courier", 30, "bold"))
       break
    
    #Checking if paddle hits the ball, updating score, increasing speed and bouncing the ball
    if (paddle.ycor() + 30 > ball.ycor() > paddle.ycor() - 30 and 
       paddle.xcor() + 50 > ball.xcor() > paddle.xcor() - 50 ):

        #Increasing score of left player and updating score board
        score += 1 
        scoreBoard.clear()
        scoreBoard.write("Score: {}".format(score), align="center", font=("Courier", 20, "bold"))
        
        #Increasing speed of the ball with the limit 7
        if(ball.dy>0 and ball.dy<5): #If dy is positive increasing dy
            ball.dy+=0.5
        elif(ball.dy<0 and ball.dy>-5): #else if dy is negative decreasing dy
            ball.dy-=0.5
            
        if(ball.dx>0 and ball.dx<5):#If dx is positive increasing dx
            ball.dx+=0.5
        elif(ball.dx<0 and ball.dx>-5): #else if dx is negative decreasing dx
            ball.dx-=0.5
        
        #Changing the direction of ball towards the right player
        ball.dy *=-1 
while (True):
    screen.update()

Code explanation:

a.  We run the whole game in an infinite while loop.

b.  In this we first update the screen and set the ball coordinates

c.  Then we check if the ball hits the right, left or top edges of the screen and we bounce by reversing the sign of the dx or dy

d.  After this, we check if the ball hits the bottom edge of the screen, that is, the paddle missed the hit. If this condition is true, we stop the game and show the score.

e.  If not, we check if the paddle hits the screen, and we update the score on the scoreboard and bounce the ball.

Output of Python Pinball Game

python pinball game output

Conclusion

Congratulations! You have successfully built the python pinball game. Hope you enjoyed building with DataFlair.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

1 Response

  1. Joseph says:

    My game doesn’t catch the ball. It keeps giving me lots of errors and I don’t even know where to begin to fix them. The ball goes right through the paddle and my score doesn’t even get to 1 and the game doesn’t reset either.

Leave a Reply

Your email address will not be published. Required fields are marked *