CS Project

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

1

SESSION 2024-25

COMPUTER SCIENCE PROJECT

ON

MAKING PING PONG GAME

SUBMITTED BY: Sandeep Nayak

Class: XII

Under the guidance of:

Mr. Sushant Kumar Nayak

(Lecturer In Computer Science)


2

INDEX

SR.NO. DESCRIPTION PAGE.NO


1. ACKNOWLEDGEMENT 03

2. CERTIFICATE 04

3. TABLE OF CONTENTS 05

4. OBJECTIVE 06

5. INTRODUCTION 07-12

6. SOURCE CODE 16-26

7. BIBLIOGRAPHY 35
3

ACKNOWLEDGEMENT

Firstly, I would like to thank our computer teacher Mr.


Sushant Ku. Nayak, because he always supported and
guided us while doing this project. He very well cleared all
the doubts I had regarding this project. Also, I would like
to especially thank my parents and friends who helped me
a lot to complete this project within the limited time.
The journey of making this project has been beautiful, as
well as knowledgeable for me and I have learned a lot
from it.

Once again, thanks to everyone who was involved with


this project from beginning to end.
4

CERTIFICATE

This is to certify that Sandeep Nayak student of class XII has


successfully completed Computer Project on making ping pong
game laid down in the regulation of CBSE in Jupiter Public
School.

Signature of Principal

Signature of Signature of
Internal External

Signature of Student
5

Table Of Contents

1.Objective Of The Project


2.Introduction
3.Proposed System
4.System Development Life Cycle(SDLC)
5.Modules Used And Their Purposes
6.ER Diagram
7.Source Code
8.Outputs
9.Limitations And Future Scope
6

1.OBJECTIVE OF THE PROJECT


The objective of this project is to let the students
apply the programming knowledge into a real-
world situation/problem and exposed the
students how programming skill help in
developing a good software.

Some key points are as follows:-


1.Utilising modern software tools for programming
games.

2.Write effective procedural code to solve small to


medium sized problems.

3.Demonstrate a breadth of knowledge in computer


science, as a exemplified in the area of game
development.
4.Demonstrate ability to conduct a research or
applied computer science project, requiring writing
and presentation skills which exemplify scholarly
style in computer science.
7

2.INRODUCTION

1.About Ping Pong Game:-


Ping pong game applications let you experience the thrill
of table tennis from your pc or laptop. These games offer
various features, like simple single-player mode against AI
opponents. Some even capture the realistic physics of the
sports in this game.

This is a one player game, at first the ball will go in any


direction either left or right of the screen. If the ball will
hit any of the paddles(present in both of the ends of the
screen) then the ball will change it’s direction to the
opposite side of hitting. This process will continue until
one of the paddle will miss the ball. If any of the paddle
will not able to hit the ball then at that moment the game
will be stop and the game over text will be appear for a
fraction of time.
8

2.Advantages Of Ping Pong Game:-


(i) Improves hand-eye coordination and reflexes:
The fast-paced nature of the game can help to improve
hand-eye coordination and reflexes, which can benefit
other activities as well.
(ii) Can be played competitively or for fun:
You can play against a computer opponent for a more
competitive experience, or simply play for fun and
relaxation.
(iii)Low Resource Requirements:
ping pong games don't require a lot of processing power or
graphics capabilities to run smoothly. This means they can
be played on older computers that might not be able to
handle more demanding games.

3.Rules Of The Game:-


(i) Two players control paddles on opposite sides of the screen.
(ii)A ball bounces back and forth between the paddles and the
wall.
(iii)Players use their paddles to hit the ball back to their
opponent's side.
9

4.Python Overview:-
Python is a general-purpose high-level programming
language. It is an open source language, released under a
GPL-compatible license. Python software
Foundation(PSF), a non-profit organisation, holds the
copy-rights of python. Guido Van Rossum conceived
python in the late 1980s.
It was released in 1991 at Centrum Wiskunde &
Informatica(CWI) in the Netherlands as a successor to the
ABC Language. He named this language after a popular
comedy show called “Monty Python’s Flying Circus”(and
not after python the snake). In the last few years, it’s
popularity has increased immensely. According to
stackoverflow.com’s recent survey, python is in the top
ten most popular technologies in 2018.
It also dynamically-typed because it carries out type-
checking at run time. It does so to make sure that the type
of construct matches what we expect it to be. The
distinctive feature of python is that it is an interpreted
language. The python IDLE(Integrated Development &
Learning Environment) executes instruction one line at a
time. The python programming language is one of the
richest language.
10

5.Features of python:-
(i)Easy To Use And Use:-
Python's syntax is clear and concise, resembling plain
English. This makes it easier to learn and read compared to
other languages, especially for beginners.
(ii) Extensive Standard Library:
Python comes with a rich collection of built-in modules and
functions that provide a wide range of functionalities for
common tasks. This saves you time from writing code from
scratch and lets you focus on your specific problem.
(iii) Cross-Platform Compatibility:
Python code can run on different operating systems like
Windows, macOS, and Linux without any modifications.
This makes it a versatile language for developing
applications that can be used on various platforms.
(iv) Interpreted Language:
Python is an interpreted language, meaning the code is
executed line by line at runtime. This allows for faster
development cycles as you can see the results of your code
immediately without needing to compile it first.
(v) Object-Oriented Programming:
Python supports object-oriented programming (OOP)
concepts like classes and objects, allowing you to structure
your code in a modular and reusable way.
(vi) Large Third-Party Libraries and Frameworks:
11

Python has a vast ecosystem of third-party libraries and


frameworks available for various purposes, such as data
science, web development, machine learning, and more.
These libraries extend Python's capabilities and make it
suitable for a wide range of applications.

(vii) Free and Open-Source:


Python is free to use and modify, making it accessible to
everyone. The open-source nature also fosters a large and
active community that contributes to the language's
development and provides support to users.

6.Advantages Of Python:-
(i)Extensible
(ii)Portable
(iii)Free And Open-Source
(iv)Readable
(v)Embeddable
(vi)Improved Productivity
(vii)Simple And Use
(viii)Object Oriented
(ix)Interpreted
(x)Extensive Libraries
12

7.About MySQL:-
(i)Transactions:
MySQL supports ACID transactions, ensuring data
consistency. This means database operations are atomic (all
or nothing), consistent (data adheres to rules), isolated
(transactions don't interfere with each other), and durable
(changes persist even after a system crash).
(ii)Security:
MySQL offers various security features like user accounts
with different permission levels, access control, and
encryption to safeguard sensitive data.
(iii)Performance:
MySQL is known for its efficient performance, especially
with complex queries on large datasets. It utilizes features
like indexing to optimize data retrieval.
(iv)Scalability:
MySQL can handle a wide range of workloads, from small
personal projects to massive databases for enterprise
applications. You can easily scale up by adding more
hardware or using replication techniques.
(V)versatility:
MySQL supports various data types, including numbers,
text, dates, and even multimedia files (BLOBs). This makes
it suitable for storing a broad range of information.
(vi)Active development:
MySQL is constantly being improved by a large community
of developers. This ensures regular updates, bug fixes, and
new features.
(vii)Open source ecosystem:
A vast ecosystem of open-source tools and libraries exists
around MySQL, making it easy to integrate with various
applications and development frameworks.
13

3.PROPOSED SYSTEM
The aim of our project is to make a ping pong game in python
language. This project shows that Python is simple, easy to learn
syntax, easy to use and fast to develop.
The python interpreter and the extensive standard library are
available in source or binary form without charge for all major
platforms, and can be freely distributed.
Often, programmers fall in love with python because of the
increased productivity it provides. It is an open-source, simple
and portable and a small amount of code is needed to built the
game.
One has to use the data management software. Many software
products working are now in markets, which have helped in
making the data easier and efficiently. Data management initially
had to maintain a lot of paper work has to be done but now
software product has made our work easier and faster. Now only
this software has to be loaded on the computer and work can be
done. And MySQL has helped us a lot to make and store data of
Ping Pong Game. And this prevents a lot of time and money. The
work becomes very easy with the help of MySQL

WHEN GAME OVER


REPLY GAME
ASK GAME SCORES
EVENT
USER GAME
INTERFACE DATABASE
ASK
WHEN GAMEOVER
GAME EVENT
REPLY GAME SCORES
14

4.SYSTEM DEVELOPMENT LIFE CYCLE


(SDLC)
The System Development Life Cycle as used in the construction
of the server appliance.

The system development life cycle is a project management


technique that divides complex projects into a smaller, more
easily managed segments or phases. Segmenting projects allow
managers to verify the successful completion of project phases
before allocating resources to subsequent phases. Software
development projects typically include planning, creating,
developing, testing and maintenance. However, the phases may
be divided differently depending on the organization.
15

5.MODULE USED AND THEIR PURPOSES

1.Random Module:-
This module implements pseudo-random number
generators for various distributions.
2. MySql.connector Module :-
This module enables python programs to access MySQL
databases, using an API that is compliant with the Python
Database API Specification v2.0 (PEP 249). It is written in
pure Python and does not have any dependencies except
for the Python Standard Library.
3.Pygame :-
Pygame is a free and open-source cross-platform
library for developing multimedia applications,
particularly video games, using Python. It abstracts
common functions related to graphics, sound, and
input, making game development more intuitive
4.Time:-
The time module in Python provides various time-related
functions. It’s an integral part of Python, offering
functionalities to work with dates, times, and intervals.
16

6.ER Diagram
17
18

import pygame,random,time
from pygame.locals import *
from mysql.connector import *

#DATA INPUT FOR MYSQL CONNECTION


user_name=input("Enter Your Local Machin's Username:
")
pass_word=input("Enter Your Local Machin's Password: ")
database_name=input("Enter Your Database Name: ")

#MYSQL CONNECTIVITY
connection = connect(
host="localhost",
user=user_name,
password=pass_word,
database=database_name
)
19

cursor=connection.cursor()

if connection.is_connected():
print("CONNECTION ESTABLISHED!")
cursor.execute("CREATE TABLE IF NOT EXISTS
PLAYER_HIGH_SCORES(SCORE INT,DATE DATE,TIME
TIME)")
cursor.execute("CREATE TABLE IF NOT EXISTS
AI_HIGH_SCORES(SCORE INT,DATE DATE,TIME TIME)")
cursor.execute("CREATE TABLE IF NOT EXISTS
PLAYER_SCORES(SCORE INT,DATE DATE,TIME TIME)")
cursor.execute("CREATE TABLE IF NOT EXISTS
AI_SCORES(SCORE INT,DATE DATE,TIME TIME)")

def PLAYER_HIGH_SCORES(x):
cursor.execute(f"INSERT INTO PLAYER_HIGH_SCORES
VALUES({x},CURDATE(),NOW())")
connection.commit()
def AI_HIGH_SCORES(x):
cursor.execute(f"INSERT INTO AI_HIGH_SCORES
VALUES({x},CURDATE(),NOW())")
connection.commit()
def PLAYER_SCORES(x):
20

cursor.execute(f"INSERT INTO PLAYER_SCORES


VALUES({x},CURDATE(),NOW())")
connection.commit()
def AI_SCORES(x):
cursor.execute(f"INSERT INTO AI_SCORES
VALUES({x},CURDATE(),NOW())")
connection.commit()

print("GAME IS STARTING.....")
time.sleep(5)

# INITIALISATION OF PYGAME
pygame.init()

#CONSTANTS
WIDTH = 800
HEIGHT = 600
clock = pygame.time.Clock()
player_score=0
ai_score=0

#ASSETS
bgi=pygame.image.load("Bg.jpg")
21

pygame.mixer.music.load("Bg_Music.mp3")
gmomu=pygame.mixer.Sound("GameOver_Music.wav")
text=pygame.font.Font("Phoenix Gaming.ttf",60)
text1=pygame.font.Font("Phoenix Gaming.ttf",90)
gameover_text=text1.render("GAMEOVER",True,(128,0,0)
)
icon=pygame.image.load("pongicon.png")

# SCREEN SETTING UP
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ping Pong Game")
pygame.display.set_icon(icon)

# CHARACTERISTICS OF PADDLES
player_paddle = pygame.Rect(WIDTH - 25, HEIGHT // 2 -
100 // 2, 15, 100)
opponent_paddle = pygame.Rect(10, HEIGHT // 2 - 100 //
2, 15, 100)

# CHARACTERISTICS OF BALL
22

ball = pygame.Rect(WIDTH // 2 - 10 // 2, HEIGHT // 2 - 10


// 2, 20, 20)
ball_speed_x = random.choice([-5, 5])
ball_speed_y = random.choice([-5, 5])

#DRAWING FUNCTIONS
def paddles():
pygame.draw.rect(screen, (249,243,124),
player_paddle)
pygame.draw.rect(screen, (249,243,124),
opponent_paddle)
def balldraw():
pygame.draw.ellipse(screen, (144,238,144), ball)

pygame.mixer.music.play(-1,0.0)
if connection.is_connected():
game=True
while game:
screen.blit(bgi,(0,0))

pygame.draw.line(screen,(255,255,255),(0,140),(800,140))
display_text=text.render(f"{ai_score}-
{player_score}",True,(255,128,0))
23

screen.blit(display_text,(370,80))

for event in pygame.event.get():


if event.type ==QUIT:
game=False

# GIVING MOVEMENT TO THE BALL


ball.x += ball_speed_x
ball.y += ball_speed_y

# BALL COLLISION DETECTION


if ball.top <= 140:
ball_speed_y = 5
if ball.bottom >= HEIGHT:
ball_speed_y = -5

if player_paddle.colliderect(ball):
ball_speed_x = -5
player_score+=1
if opponent_paddle.colliderect(ball):
ball_speed_x = 5
ai_score+=1
24

#PADDLES LIMITS IN THE SCREEN


if player_paddle.top<=140:
player_paddle.top=140
if player_paddle.bottom>=HEIGHT:
player_paddle.bottom=HEIGHT
if opponent_paddle.top<=140:
opponent_paddle.top=140
if opponent_paddle.bottom>=HEIGHT:
opponent_paddle.bottom=HEIGHT

#AI_HANDLING
if ball_speed_x == -5:
if opponent_paddle.centery < ball.y:
opponent_paddle.y += 5
if opponent_paddle.centery > ball.y:
opponent_paddle.y -= 5

#PLAYER CONTROL OVER THE RIGHT PADDLE


keys = pygame.key.get_pressed()
25

if keys[K_UP]:
player_paddle.y -= 5
if keys[K_DOWN]:
player_paddle.y += 5

#FUNCTION CALL
paddles()
balldraw()

#GAME OVER
if ball.left <= 0 or ball.right >= WIDTH:
screen.fill((0,0,0))
screen.blit(gameover_text,(260,270))
pygame.mixer.music.stop()

#GAMEOVER MUSIC
if ball.left <= 0 or ball.right >= WIDTH and game==True:
gmomu.play()
time.sleep(2)
gmomu.stop()
26

game=False

#DISPLAY UPDATION
pygame.display.flip()

#SETTING UP OF THE FPS


clock.tick(60)

PLAYER_SCORES(player_score)
AI_SCORES(ai_score)

cursor.execute("SELECT MAX(SCORE) FROM


AI_HIGH_SCORES")
data=cursor.fetchall()
if data==[(None,)]:
AI_HIGH_SCORES(ai_score)
elif ai_score>data[0][0]:
AI_HIGH_SCORES(ai_score)

cursor.execute("SELECT MAX(SCORE) FROM


PLAYER_HIGH_SCORES")
27

data=cursor.fetchall()
if data==[(None,)]:
PLAYER_HIGH_SCORES(player_score)
elif player_score>data[0][0]:
PLAYER_HIGH_SCORES(player_score)

cursor.close()
connection.close()

pygame.quit()
28

8.OUTPUTS
1.Ask for the username to connect to the database.
29

2.Ask for the password to connect to the database.


30

3.Ask for the database name to connect


31

4.Connection established and game starting message


32

5.Game interface:-

6.Score updation :-
33

7.Final score:-

8.Gameover screen:-
34

9.Tables created in the pingpong database:-

10.ai_high_scores Table:-

11.player_high_scores Table:-

12.player_scores Table:-

13.ai_scores Table:-
35

9.LIMITATIONS AND FUTURE SCOPE

Limitations:-
• Only one player can play at a time.
• Registration of players cannot be done.
• It does not follow the actual rules of the ping pong
game.

Future Scope:-
• The number of player can be more than one at a
time.
• Registration of the players can be done.
• It can follow the actual rules.
36

Bibliography
1.www.wikipedia.com
2.www.scribd.com
3.www.geeksforgeeks.org
4.www.google.com
5.Computer Science with Python by Sumita Arora
Class XIIth (book)

You might also like