0% found this document useful (0 votes)
18 views

cs project

Uploaded by

snitheesh.2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

cs project

Uploaded by

snitheesh.2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

PONG GAME

COMPUTER SCIENCE PROJECT


SUBMITTED BY

NITHEESH.S , CLASS XI
SRIMATHI SUNDARAVALLI MEMORIAL SCHOOL
CHENNAI
S.NO CONTENT PAGE.NO

1 OVERVIEW OF PYTHON

2 ABSTRACT

3 REQUIREMENTS

4 MODULES

5 BUILT IN

6 SOURCE CODE

7 OUTPUT

8 CONCLUSION

9 FUTURE OUTLOOK

10 REFERENCES
OVERVIEW OF PYTHON
Python is a versatile, high-level programming language that is
widely used across various fields due to its simplicity, readability,
and extensive library support. Created by Guido van Rossum and
first released in 1991, Python is designed to be easy to learn and
use, making it an excellent choice for both beginners and
experienced programmers. Below is an overview of its key features,
uses, and strengths
1.KEY FEATURES
Simple Syntax: Python’s syntax is clean and readable, which enhances
developer productivity. Unlike other languages, Python doesn’t use braces to
define code blocks; instead, it relies on indentation, making the code visually
structured.
Interpreted Language: Python code is executed line by line by an interpreter.
This makes debugging easier and allows for rapid development since there is
no need to compile the code.
Dynamic Typing: In Python, variable types are determined at runtime,
meaning you don't have to explicitly declare the type of a variable. This
flexibility makes it easier to write code quickly.
Object-Oriented: Python supports object-oriented programming (OOP)
principles, such as classes, inheritance, and polymorphism, making it suitable
for both small scripts and large software projects.
Cross-Platform: Python can run on multiple platforms, including Windows,
macOS, and Linux. The same Python code can be executed on different
systems with minimal or no modification.
Extensive Standard Library: Python comes with a comprehensive standard
library that provides modules for tasks such as file handling, regular
expressions, networking, and more, which significantly reduces development
time.
Community and Ecosystem: Python has an active, large community that
contributes to a rich ecosystem of third-party libraries and frameworks. The
Python Package Index (PyPI) contains thousands of packages for various use
cases, including web development, data analysis, machine learning, and more.
STRENGTHS OF PYTHON

Ease of Learning: Python is well-known for being beginner-friendly. Its simple


syntax makes it easier for newcomers to understand and write code compared
to other languages.

Rapid Development: Python allows for quick prototyping and iteration. Its
dynamic typing and extensive libraries help developers build applications
faster.

Extensive Library Support: Python has a vast collection of modules and


packages that allow you to implement functionality without reinventing the
wheel. This makes Python ideal for various domains, from web development to
data science.

Readable Code: Python emphasizes readability, which not only reduces the
chances of bugs but also makes it easier for teams to collaborate on large
projects.

Large Community and Support: The Python community is one of the largest in
the programming world. This means abundant resources, tutorials,
documentation, and forums are available to help with any programming
challenges.

CONCLUSION

Python’s simplicity, versatility, and broad ecosystem make it an excellent


choice for a wide range of applications, from web development and data science
to automation and machine learning. Despite some performance limitations,
Python’s strengths in ease of use, readability, and rich community support
have solidified its place as one of the most popular and widely adopted
programming languages in the world today.
REQUIREMENTS

DEVICE SPECIFICATIONS:

Processor :11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz 2.42 GHz


Installed RAM : 8.00 GB (7.80 GB usable)
Device ID : 12CAC963-645F-4755-B836-ACF44570F5D8
Product ID : 00356-02793-51989-AAOEM
System type : 64-bit operating system, x64-based processor

WINDOWS SPECIFICATION:

Edition : Windows 11 Home


Version : 23H2
OS build : 22631.4602
Experience Windows Feature Experience Pack : 1000.22700.1055.0
MODULES USED
1. sys:

Use: Used for interacting with the Python runtime environment. It's
primarily used in this program to handle system-specific parameters, like
the sys.exit() method for quitting the program and sys.executable to call
the Python executable for installing missing modules.

2. subprocess:

Use: Used to run system commands, specifically for installing required


Python modules if they are missing. The subprocess.check_call function
is used to run the command to install modules via pip.

3. importlib.util:

Use: Used to check whether a specific module (in this case pygame) is
available before importing it. It allows checking the presence of modules
dynamically to prevent errors.

4. math:

Use: Provides mathematical functions. In this program, it is used to


calculate the positions of the gear teeth in the draw_settings_icon
function for drawing the settings icon (the gear icon) using trigonometric
functions (e.g., math.radians, math.cos, and math.sin).

5. pygame:

Use: The main library used to create the graphical user interface and
handle game mechanics. It provides functions for handling graphics (e.g.,
drawing shapes), event handling (e.g., keyboard inputs), and game
management (e.g., setting up the game screen, managing game loops,
and controlling frame rate).

6. time:

Use: Provides time-related functions. It is used here for:


i. Delays: Using time.sleep() to introduce delays (e.g., pausing
the game for 1 second after a point is scored).
ii. Timing: pygame.time.get_ticks() to track time passed since
the game started, specifically used to increment game speed
periodically and handle power-up duration.

BUILT IN FUNCTIONS USED


importlib.util.find_spec

• Checks if a module is installed. If the module is not installed, it returns


None. It's used to check whether a required module (pygame) is available
before attempting to import it.

subprocess.check_call(args)

• Runs the command passed as a list (args) and waits for it to complete. In
this case, it’s used to install missing modules by running pip install
<module>.

sys.exit([status])

• Exits the program. status can be passed to indicate the exit status (non-
zero values typically indicate errors).

pygame.init()

• Initializes all imported Pygame modules. It must be called before using


any other Pygame functions.

pygame.display.set_mode((width, height), flags=0, depth=0, display=0,


vsync=False)

• Creates a window with the specified dimensions (width and height). In


your program, it's used to create a fullscreen window with
pygame.FULLSCREEN.

pygame.display.set_caption(title)

• Sets the window title. In your program, it sets the title to "Pong Game".

pygame.mouse.set_visible(value)

• Sets whether the mouse cursor is visible or not. In the program, the
cursor visibility is controlled based on the game state.

pygame.time.Clock()
• Creates a clock object to control the frame rate of the game (60 FPS in
this case).

pygame.font.Font(name, size)

• Creates a font object to render text. It’s used throughout the program to
render text like scores, titles, and messages.

pygame.event.get()

• Returns a list of all the events that have occurred. It is used to process
events like quitting the game or keypresses.

pygame.key.get_pressed()

• Returns a list of boolean values representing the state of each key


(whether it's pressed or not).

pygame.draw.rect(surface, color, rect)

• Draws a rectangle on the given surface (screen). It’s used to draw


paddles, buttons, and other objects.

pygame.draw.ellipse(surface, color, rect)

• Draws an ellipse on the surface. It’s used for drawing the ball in the
game.

pygame.draw.aaline(surface, color, start_pos, end_pos)

• Draws an anti-aliased line between two points on the surface. In this


case, it’s used for drawing the center line.

pygame.mouse.get_pos()

• Returns the current mouse cursor position.

pygame.time.get_ticks()

• Returns the number of milliseconds since Pygame was initialized. This is


used to manage timed events like increasing the speed of the ball or
handling the power-up timer.
SOURCE CODE

import pygame import sys import time

pygame.init()

WIDTH, HEIGHT = 800, 600

BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0)

PADDLE_WIDTH, PADDLE_HEIGHT = 10, 100 PADDLE_SPEED = 5


AI_SPEED_INCREMENT = 0.5 # Speed increment for AI

BALL_SIZE = 15 BALL_SPEED_X, BALL_SPEED_Y = 4, 4

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) WIDTH,


HEIGHT = screen.get_width(), screen.get_height()
pygame.display.set_caption("Pong Game")

BUTTON_WIDTH = 200 BUTTON_HEIGHT = 50 BUTTON_COLOR = (50, 50, 50)


BUTTON_HOVER_COLOR = (100, 100, 100) BUTTON_TEXT_COLOR = WHITE

pygame.mouse.set_visible(True)

clock = pygame.time.Clock()

left_paddle = pygame.Rect(30, (HEIGHT - PADDLE_HEIGHT) // 2,


PADDLE_WIDTH, PADDLE_HEIGHT) right_paddle = pygame.Rect(WIDTH - 40,
(HEIGHT - PADDLE_HEIGHT) // 2, PADDLE_WIDTH, PADDLE_HEIGHT)

ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_SIZE, BALL_SIZE)


ball_vel_x, ball_vel_y = BALL_SPEED_X, BALL_SPEED_Y

left_score, right_score = 0, 0

font = pygame.font.Font(None, 36)

power_up = pygame.Rect(WIDTH // 2 - 10, HEIGHT // 2 - 10, 20, 20)


power_up_active = False power_up_timer = 0 POWER_UP_DURATION = 5000

speed_timer = pygame.time.get_ticks() SPEED_INCREMENT_INTERVAL = 5000

MODE_SINGLE_PLAYER = 1 MODE_TWO_PLAYER = 2
GAME_STATE_PLAYING = 0 GAME_STATE_PAUSED = 1
GAME_STATE_SETTINGS = 2

AI_EASY = 1 AI_MEDIUM = 2 AI_HARD = 3 ai_difficulty = AI_EASY

AI_SPEED_MULTIPLIERS = { AI_EASY: 0.5, AI_MEDIUM: 1.0, AI_HARD: 1.5 }

def home_screen(): home_running = True selected_mode = None

# Create buttons
single_player_button = pygame.Rect(WIDTH//2 - BUTTON_WIDTH - 20,
HEIGHT//2, BUTTON_WIDTH, BUTTON_HEIGHT)
two_player_button = pygame.Rect(WIDTH//2 + 20, HEIGHT//2,
BUTTON_WIDTH, BUTTON_HEIGHT)

while home_running:
mouse_pos = pygame.mouse.get_pos()
mouse_clicked = False

for event in pygame.event.get():


if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click
mouse_clicked = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()

# Check button hover and clicks


single_player_hover = single_player_button.collidepoint(mouse_pos)
two_player_hover = two_player_button.collidepoint(mouse_pos)

if mouse_clicked:
if single_player_hover:
selected_mode = MODE_SINGLE_PLAYER
home_running = False
elif two_player_hover:
selected_mode = MODE_TWO_PLAYER
home_running = False
# Display home screen
screen.fill(BLACK)
title_text = font.render("Welcome to Pong!", True, WHITE)
screen.blit(title_text, (WIDTH // 2 - title_text.get_width() // 2, HEIGHT // 3))

# Draw buttons
pygame.draw.rect(screen, BUTTON_HOVER_COLOR if single_player_hover
else BUTTON_COLOR, single_player_button)
pygame.draw.rect(screen, BUTTON_HOVER_COLOR if two_player_hover else
BUTTON_COLOR, two_player_button)

# Button text
single_text = font.render("Single Player", True, BUTTON_TEXT_COLOR)
two_text = font.render("Two Players", True, BUTTON_TEXT_COLOR)

# Center text on buttons


screen.blit(single_text, (single_player_button.centerx -
single_text.get_width()//2,
single_player_button.centery - single_text.get_height()//2))
screen.blit(two_text, (two_player_button.centerx - two_text.get_width()//2,
two_player_button.centery - two_text.get_height()//2))

pygame.display.flip()

# Hide cursor for gameplay


pygame.mouse.set_visible(False)
return selected_mode

def settings_screen(): settings_running = True global ai_difficulty

# Create difficulty buttons


button_width = 200
button_height = 50
button_spacing = 20

easy_button = pygame.Rect(WIDTH//2 - button_width//2, HEIGHT//2 -


button_height*2, button_width, button_height)
medium_button = pygame.Rect(WIDTH//2 - button_width//2, HEIGHT//2 -
button_height//2, button_width, button_height)
hard_button = pygame.Rect(WIDTH//2 - button_width//2, HEIGHT//2 +
button_height, button_width, button_height)

while settings_running:

mouse_pos = pygame.mouse.get_pos()
mouse_clicked = False

# Check button hover and clicks


easy_hover = easy_button.collidepoint(mouse_pos)
medium_hover = medium_button.collidepoint(mouse_pos)
hard_hover = hard_button.collidepoint(mouse_pos)

if mouse_clicked:
if easy_hover:
ai_difficulty = AI_EASY
settings_running = False
pygame.mouse.set_visible(False)
elif medium_hover:
ai_difficulty = AI_MEDIUM
settings_running = False
pygame.mouse.set_visible(False)
elif hard_hover:
ai_difficulty = AI_HARD
settings_running = False
pygame.mouse.set_visible(False)
else:
pygame.mouse.set_visible(False)

# Draw settings screen


screen.fill(BLACK)
title_text = font.render("AI Difficulty Settings", True, WHITE)
screen.blit(title_text, (WIDTH//2 - title_text.get_width()//2, HEIGHT//4))

# Draw buttons with current selection highlighted


for button, text, hover, is_selected in [
(easy_button, "Easy", easy_hover, ai_difficulty == AI_EASY),
(medium_button, "Medium", medium_hover, ai_difficulty == AI_MEDIUM),
(hard_button, "Hard", hard_hover, ai_difficulty == AI_HARD)
]:
color = BUTTON_HOVER_COLOR if hover else (WHITE if is_selected else
BUTTON_COLOR)
pygame.draw.rect(screen, color, button)
button_text = font.render(text, True, BUTTON_TEXT_COLOR)
screen.blit(button_text, (button.centerx - button_text.get_width()//2,
button.centery - button_text.get_height()//2))

# Draw escape instruction


escape_text = font.render("Press ESC to return", True, WHITE)
screen.blit(escape_text, (WIDTH//2 - escape_text.get_width()//2,
HEIGHT*3//4))

pygame.display.flip()

game_mode = home_screen()

running = True game_state = GAME_STATE_PLAYING while running: for event


in pygame.event.get(): if event.type == pygame.QUIT: running = False if
event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running
= False pygame.mouse.set_visible(False) if event.key == pygame.K_p:
game_state = GAME_STATE_PAUSED if game_state == GAME_STATE_PLAYING
else GAME_STATE_PLAYING pygame.mouse.set_visible(False) if event.key ==
pygame.K_e and game_mode == MODE_SINGLE_PLAYER: # 'e' key for settings
game_state = GAME_STATE_SETTINGS pygame.mouse.set_visible(True)

if game_state == GAME_STATE_PAUSED:
pause_text = font.render("GAME PAUSED", True, WHITE)
continue_text = font.render("Press P to Continue", True, WHITE)
screen.blit(pause_text, (WIDTH//2 - pause_text.get_width()//2, HEIGHT//2
- 30))
screen.blit(continue_text, (WIDTH//2 - continue_text.get_width()//2,
HEIGHT//2 + 30))
pygame.display.flip()
pygame.mouse.set_visible(True)
continue

if game_state == GAME_STATE_SETTINGS:
settings_screen()
game_state = GAME_STATE_PLAYING
pygame.mouse.set_visible(False)
continue

# Get key presses


keys = pygame.key.get_pressed()

# Move left paddle


if keys[pygame.K_w] and left_paddle.top > 0:
left_paddle.y -= PADDLE_SPEED
if keys[pygame.K_s] and left_paddle.bottom < HEIGHT:
left_paddle.y += PADDLE_SPEED

# AI for right paddle in single-player mode


if game_mode == MODE_SINGLE_PLAYER:
if ai_difficulty == AI_EASY: # Easy AI
if right_paddle.centery < ball.centery and right_paddle.bottom < HEIGHT:
right_paddle.y += PADDLE_SPEED *
AI_SPEED_MULTIPLIERS[AI_EASY] # Slower movement
if right_paddle.centery > ball.centery and right_paddle.top > 0:
right_paddle.y -= PADDLE_SPEED *
AI_SPEED_MULTIPLIERS[AI_EASY] # Slower movement
elif ai_difficulty == AI_MEDIUM: # Medium AI
if right_paddle.centery < ball.centery and right_paddle.bottom < HEIGHT:
right_paddle.y += PADDLE_SPEED *
AI_SPEED_MULTIPLIERS[AI_MEDIUM] # Normal movement
if right_paddle.centery > ball.centery and right_paddle.top > 0:
right_paddle.y -= PADDLE_SPEED *
AI_SPEED_MULTIPLIERS[AI_MEDIUM] # Normal movement
elif ai_difficulty == AI_HARD: # Hard AI
if right_paddle.centery < ball.centery and right_paddle.bottom < HEIGHT:
right_paddle.y += PADDLE_SPEED *
AI_SPEED_MULTIPLIERS[AI_HARD] # Faster movement
if right_paddle.centery > ball.centery and right_paddle.top > 0:
right_paddle.y -= PADDLE_SPEED *
AI_SPEED_MULTIPLIERS[AI_HARD] # Faster movement
else:
# Move right paddle in two-player mode
if keys[pygame.K_UP] and right_paddle.top > 0:
right_paddle.y -= PADDLE_SPEED
if keys[pygame.K_DOWN] and right_paddle.bottom < HEIGHT:
right_paddle.y += PADDLE_SPEED

# Move ball
ball.x += ball_vel_x
ball.y += ball_vel_y

# Ball collision with top and bottom walls


if ball.top <= 0:
ball.top = 0
ball_vel_y = abs(ball_vel_y) # Ensure ball moves downward
elif ball.bottom >= HEIGHT:
ball.bottom = HEIGHT
ball_vel_y = -abs(ball_vel_y) # Ensure ball moves upward

# Ball collision with paddles


if ball.colliderect(left_paddle):
ball.left = left_paddle.right
ball_vel_x = abs(ball_vel_x) # Ensure ball moves right
elif ball.colliderect(right_paddle):
ball.right = right_paddle.left
ball_vel_x = -abs(ball_vel_x) # Ensure ball moves left

# Ball goes out of bounds


if ball.left <= 0:
right_score += 1
ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_SIZE, BALL_SIZE)
ball_vel_x, ball_vel_y = BALL_SPEED_X, BALL_SPEED_Y
screen.fill(BLACK)
left_text = font.render(f"Left Player: {left_score}", True, WHITE)
right_text = font.render(f"Right Player: {right_score}", True, WHITE)
screen.blit(left_text, (WIDTH // 4, HEIGHT // 2))
screen.blit(right_text, (WIDTH * 3 // 4 - right_text.get_width(), HEIGHT //
2))
pygame.display.flip()
time.sleep(1) # Pause for 1 second
if ball.right >= WIDTH:
left_score += 1
ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_SIZE, BALL_SIZE)
ball_vel_x, ball_vel_y = -BALL_SPEED_X, BALL_SPEED_Y
screen.fill(BLACK)
left_text = font.render(f"Left Player: {left_score}", True, WHITE)
right_text = font.render(f"Right Player: {right_score}", True, WHITE)
screen.blit(left_text, (WIDTH // 4, HEIGHT // 2))
screen.blit(right_text, (WIDTH * 3 // 4 - right_text.get_width(), HEIGHT //
2))
pygame.display.flip()
time.sleep(1) # Pause for 1 second

# Increment speed over time


if pygame.time.get_ticks() - speed_timer > SPEED_INCREMENT_INTERVAL:
PADDLE_SPEED += 0.5
ball_vel_x += 0.5 if ball_vel_x > 0 else -0.5
ball_vel_y += 0.5 if ball_vel_y > 0 else -0.5
speed_timer = pygame.time.get_ticks()

# Power-up logic
if not power_up_active and pygame.time.get_ticks() % 10000 < 50:
power_up.x, power_up.y = WIDTH // 2 - 10, HEIGHT // 2 - 10
power_up_active = True

if power_up_active and ball.colliderect(power_up):


PADDLE_SPEED += 2
power_up_active = False
power_up_timer = pygame.time.get_ticks()

if pygame.time.get_ticks() - power_up_timer > POWER_UP_DURATION and


PADDLE_SPEED > 5:
PADDLE_SPEED -= 2

# Clear screen
screen.fill(BLACK)

# Draw paddles and ball


pygame.draw.rect(screen, WHITE, left_paddle)
pygame.draw.rect(screen, WHITE, right_paddle)
pygame.draw.ellipse(screen, WHITE, ball)

# Draw center line


pygame.draw.aaline(screen, WHITE, (WIDTH // 2, 0), (WIDTH // 2, HEIGHT))

# Draw scores
left_text = font.render(str(left_score), True, WHITE)
right_text = font.render(str(right_score), True, WHITE)
screen.blit(left_text, (WIDTH // 4, 20))
screen.blit(right_text, (WIDTH * 3 // 4, 20))

# Draw power-up
if power_up_active:
pygame.draw.rect(screen, RED, power_up)

# Update display
pygame.display.flip()

# Limit frame rate


clock.tick(60)

thank_you_screen = True while thank_you_screen: for event in


pygame.event.get(): if event.type == pygame.QUIT: thank_you_screen = False if
event.type == pygame.KEYDOWN and event.key == pygame.K_q:
thank_you_screen = False

# Clear screen
screen.fill(BLACK)

# Display thank you message


thank_you_text = font.render("Thank you for playing! Press Q to quit.", True,
WHITE)
screen.blit(thank_you_text, (WIDTH // 2 - thank_you_text.get_width() // 2,
HEIGHT // 2))

# Update display
pygame.display.flip()

pygame.quit() sys.exit()

You might also like