Report On
Tetris Game
Submitted in partial fulfillment of the requirements of the Course project in
Semester IV of Second Year Computer Engineering
by
Jagruti Chavan (Roll No. 73)
Shreeya Gosavi (Roll No. 77)
Supervisor
Prof. Snehal Mhatre
University of Mumbai
Vidyavardhini's College of Engineering & Technology
Department of Computer Engineering
(2024-25)
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
CERTIFICATE
This is to certify that the project entitled “Tetris Game” is a bonafide work of “Jagruti Chavan
(Roll No. 73), Shreeya Gosavi (Roll No. 77)" submitted to the University of Mumbai in partial
fulfillment of the requirement for the Course project in semester IV of Second Year Computer
Engineering.
Supervisor
Prof. Snehal Mhatre
Internal Examiner
Contents Pg. No
1. Abstract 1
2. Introduction 2
3. Problem Statement 3
4. Proposed Solution Features 4
5. Methodology 5
6. Code 7
7. Result 14
8. References 17
Abstract
Tetris is one of the most iconic and widely recognized puzzle games, originally developed by
Alexey Pajitnov in 1984. The game challenges players to manipulate falling tetrominoes to form
and clear complete horizontal lines, increasing in difficulty as the speed of falling pieces
accelerates. This project aims to recreate the Tetris game using Python and Pygame, integrating
additional features such as user authentication and a leaderboard system to enhance the gaming
experience.
The game follows the traditional mechanics of Tetris while introducing database connectivity to
store high scores and user information. Players can create accounts, log in, and track their
progress over multiple sessions. The leaderboard feature fosters a competitive environment by
displaying the top-performing players. The project utilizes object-oriented programming (OOP)
principles and graphical user interface (GUI) development to ensure a smooth and interactive
gameplay experience.
1
Introduction
Tetris is a classic tile-matching puzzle game originally developed by Alexey Pajitnov in 1984. It
has remained one of the most popular and widely played games worldwide. Our project aims to
recreate the Tetris experience using Python and Pygame, incorporating a user authentication
system and a leaderboard to enhance competitiveness.
In this game, players manipulate falling tetrominoes geometric shapes composed of four square
blocks to create and clear full horizontal lines. The game becomes progressively challenging as
the speed of falling blocks increases.
Through this project, we explore game development concepts, real-time event handling, and
database management. The implementation showcases the application of Python for game
programming, emphasizing its capabilities in creating engaging and dynamic applications. The
project serves as both an educational tool and an entertainment application, demonstrating how
fundamental programming techniques can be leveraged to develop classic games with modern
enhancements.
2
Problem Statement
Classic games like Tetris have been widely enjoyed for decades, but many implementations lack
features such as user authentication, score tracking, and competitive elements that enhance user
engagement. Traditional Tetris versions do not offer a personalized experience, preventing
players from saving their progress and competing with others efficiently.
From a development perspective, creating a game with real-time event handling, smooth
gameplay mechanics, and database connectivity can be challenging for beginners. Many game
development projects focus only on core mechanics but lack features that integrate gaming with
data management, making it difficult for players to have a seamless and personalized experience.
3
Proposed Solution Features
Our project aims to recreate the Tetris game using Python and Pygame while integrating a user
authentication system and a leaderboard to enhance player experience. The proposed solution
includes:
1. Game Implementation: Developing a fully functional Tetris game with smooth
mechanics, increasing difficulty levels, and interactive gameplay using Python and
Pygame.
2. User Authentication System: Allowing players to create accounts, log in, and save their
high scores using database connectivity.
3. Leaderboard Feature: Maintaining a real-time scoreboard to display the top players,
encouraging competitiveness and engagement.
4. Graphical User Interface (GUI): Designing an intuitive and visually appealing interface
for a better user experience.
5. Efficient Data Management: Using a database to store user details and high scores for
long-term tracking.
4
Methodology
To develop an enhanced version of the Tetris game, we followed a structured approach that
ensured smooth gameplay, user authentication, and score tracking through database integration.
The development methodology consists of the following key steps:
1. Requirement Analysis
● Identified the essential game mechanics, including tetromino movement, rotation, line
clearing, and increasing difficulty.
● Defined additional features such as user authentication, a leaderboard system, and
persistent score storage.
● Selected Python as the programming language and Pygame as the primary library for
game development.
● Choose SQLite or another lightweight database for storing user credentials and scores.
2. Game Design & Development
● Implemented the game logic, including tetromino generation, movement, collision
detection, and scoring system.
● Designed an intuitive user interface (UI) with menus for login, registration, and
gameplay.
● Ensured real-time event handling for smooth user interactions using Pygame.
3. Database Integration
● Integrated a user authentication system (registration & login) using SQLite to store player
credentials securely.
● Implemented a leaderboard system to track and display high scores of registered players.
4. Testing & Debugging
● Conducted unit testing to verify the correctness of game logic and database operations.
● Performed user testing to check the responsiveness and user experience of the game.
5
● Identified and fixed bugs related to tetromino movement, scoring inconsistencies, and
database connectivity.
5. Optimization & Enhancements
● Improved game performance by optimizing rendering and event handling.
● Added a difficulty scaling mechanism to gradually increase game speed.
● Enhanced the user experience with animations, sound effects, and UI refinements.
6. Deployment & Documentation
● Packaged the game for easy installation and use.
● Created a user guide explaining game controls and authentication features.
● Documented the source code and database structure for future improvements.
6
Code
#main.py import pygame import sys
from game import Game from colors
import Colors from database import
Database from login import
LoginApp import tkinter as tk
pygame.init()
db = Database()
def get_logged_in_user():
"""Runs the Tkinter login system and returns the logged-in user."""
root = tk.Tk() app = LoginApp(root) root.mainloop()
return app.username if app.username else None
username = get_logged_in_user() if not
username:
sys.exit("Authentication failed. Exiting...")
title_font = pygame.font.Font(None, 40) small_font =
pygame.font.Font(None, 30)
score_surface = title_font.render("Score", True, Colors.white) next_surface =
title_font.render("Next", True, Colors.white) leaderboard_surface =
title_font.render("Leaderboard", True, Colors.white) game_over_surface =
title_font.render("GAME OVER", True, Colors.red)
score_rect = pygame.Rect(320, 55, 200, 100) next_rect =
pygame.Rect(320, 215, 200, 180) leaderboard_rect =
pygame.Rect(320, 430, 200, 150)
7
screen = pygame.display.set_mode((550, 620))
pygame.display.set_caption(f"Tetris - {username}") clock =
pygame.time.Clock()
game = Game(username)
GAME_UPDATE = pygame.USEREVENT pygame.time.set_timer(GAME_UPDATE, 200)
game_over_time = None score_saved =
False
top_scores = db.fetch_top_scores(5) best_score
= db.get_best_score(username) while True:
for event in pygame.event.get(): if
event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if game.game_over:
# Allow reset only after 2 seconds if game_over_time and
pygame.time.get_ticks() - game_over_time > 2000: game.reset()
game_over_time = None
score_saved = False # Allow saving in next game
# Refresh leaderboard after reset
top_scores = db.fetch_top_scores(5) best_score
= db.get_best_score(username) else: if
event.key == pygame.K_LEFT:
game.move_left() elif
event.key == pygame.K_RIGHT:
8
game.move_right() elif
event.key == pygame.K_DOWN:
game.move_down()
game.update_score(0, 1) elif event.key
== pygame.K_UP:
game.rotate()
if event.type == GAME_UPDATE and not game.game_over:
game.move_down()
# Drawing UI
screen.fill(Colors.dark_blue)
# Score
score_value_surface = title_font.render(str(game.score), True, Colors.white)
screen.blit(score_surface, (365, 20))
pygame.draw.rect(screen, Colors.light_blue, score_rect, 0, 10)
screen.blit(score_value_surface,
score_value_surface.get_rect(centerx=score_rect.centerx, centery=score_rect.centery))
# Next Piece
screen.blit(next_surface, (375, 180))
pygame.draw.rect(screen, Colors.light_blue, next_rect, 0, 10)
# Leaderboard
screen.blit(leaderboard_surface, (340, 400))
pygame.draw.rect(screen, Colors.light_blue, leaderboard_rect, 0, 10)
# Display Best Score
best_score_surface = small_font.render(f"Best: {best_score}", True, Colors.white)
screen.blit(best_score_surface, (365, 120))
9
# Display Top Scores y_offset = 430 for rank, (user,
score) in enumerate(top_scores, start=1):
leaderboard_entry = small_font.render(f"{rank}. {user}: {score}", True, Colors.white)
screen.blit(leaderboard_entry, (330, y_offset)) y_offset
+= 30
game.draw(screen) if
game.game_over:
screen.blit(game_over_surface, (180, 300))
if game_over_time is None:
game_over_time = pygame.time.get_ticks()
score_saved = False
elif pygame.time.get_ticks() - game_over_time > 2000:
if not score_saved: db.save_score(username,
game.score) score_saved = True
for event in pygame.event.get(): if
event.type == pygame.KEYDOWN:
game.reset() game_over_time = None
score_saved = False top_scores =
db.fetch_top_scores(5) best_score =
db.get_best_score(username)
break
pygame.display.update() clock.tick(60)
#database.py import
mysql.connector
10
# MySQL Database Configuration
DB_CONFIG = {
"host": "localhost",
"user": "root",
"password": "Jaggu@0431",
"database": "tetris"
}
class Database: def
__init__(self):
"""Initialize the database connection.""" self.conn =
mysql.connector.connect(**DB_CONFIG) self.cursor =
self.conn.cursor() self.create_tables()
def create_tables(self):
"""Create required tables if they don't exist."""
self.cursor.execute("CREATE DATABASE IF NOT EXISTS tetris")
self.cursor.execute("USE tetris")
# Create Users table self.cursor.execute("""
CREATE TABLE IF NOT EXISTS users ( id
INT AUTO_INCREMENT PRIMARY KEY, username
VARCHAR(50) UNIQUE NOT NULL, password
VARCHAR(255) NOT NULL
)
""")
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS scores ( id
INT AUTO_INCREMENT PRIMARY KEY,
11
username VARCHAR(50) NOT NULL, score INT
NOT NULL,
PRIMARY KEY (username),
FOREIGN KEY (username) REFERENCES users(username) ON DELETE
CASCADE)""")
self.conn.commit()
def register_user(self, username, password):
"""Register a new user.""" try:
query = "INSERT INTO users (username, password) VALUES (%s, %s)"
self.cursor.execute(query, (username, password)) self.conn.commit()
return True except mysql.connector.IntegrityError: print("Error: Username
already exists.") return False
def login_user(self, username, password):
"""Check if a user exists for login."""
query = "SELECT * FROM users WHERE username = %s AND password = %s"
self.cursor.execute(query, (username, password))
return self.cursor.fetchone() is not None # Returns True if user exists
def save_score(self, username, score):
"""Save every score entry into the database."""
query = "INSERT INTO scores (username, score) VALUES (%s, %s)"
self.cursor.execute(query, (username, score)) self.conn.commit()
def fetch_top_scores(self, limit=10):
"""Fetch top scores, showing only the highest score per user.""" query
= """
SELECT username, MAX(score) AS max_score
12
FROM scores
GROUP BY username
ORDER BY max_score DESC
LIMIT %s
"""
self.cursor.execute(query, (limit,)) return
self.cursor.fetchall()
def get_best_score(self, username):
"""Retrieve the highest score of a specific user."""
query = "SELECT MAX(score) FROM scores WHERE username = %s"
self.cursor.execute(query, (username,)) result = self.cursor.fetchone()
return result[0] if result[0] is not None else 0
def close_connection(self):
"""Close the database connection properly."""
self.cursor.close() self.conn.close()
if __name__ == "__main__": db =
Database()
print(db.fetch_top_scores())
db.close_connection()
13
Results:
Fig. 1 - User Registration
Fig. 2 - User Login
14
Fig. 3 - Game UI
Fig. 4 - Game Terminated
15
Fig. 5 - Database
16
References
1. https://www.geeksforgeeks.org/python-programming-language-tutorial/
2. https://youtu.be/BDi3SD7E6no?si=Pq2TKEDfQG2OiMZx
17