0% found this document useful (0 votes)
13 views21 pages

Tetris Game Development in Python

The document presents a project report on recreating the classic Tetris game using Python and Pygame, incorporating features like user authentication and a leaderboard. It outlines the game's mechanics, development methodology, and the integration of database connectivity for score tracking. The project aims to enhance user engagement and provide a personalized gaming experience while demonstrating fundamental programming techniques in game development.

Uploaded by

Jagruti Chavan
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)
13 views21 pages

Tetris Game Development in Python

The document presents a project report on recreating the classic Tetris game using Python and Pygame, incorporating features like user authentication and a leaderboard. It outlines the game's mechanics, development methodology, and the integration of database connectivity for score tracking. The project aims to enhance user engagement and provide a personalized gaming experience while demonstrating fundamental programming techniques in game development.

Uploaded by

Jagruti Chavan
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

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
#[Link] import pygame import sys
from game import Game from colors
import Colors from database import
Database from login import
LoginApp import tkinter as tk

[Link]()

db = Database()

def get_logged_in_user():
"""Runs the Tkinter login system and returns the logged-in user."""
root = [Link]() app = LoginApp(root) [Link]()
return [Link] if [Link] else None

username = get_logged_in_user() if not


username:
[Link]("Authentication failed. Exiting...")

title_font = [Link](None, 40) small_font =


[Link](None, 30)

score_surface = title_font.render("Score", True, [Link]) next_surface =


title_font.render("Next", True, [Link]) leaderboard_surface =
title_font.render("Leaderboard", True, [Link]) game_over_surface =
title_font.render("GAME OVER", True, [Link])

score_rect = [Link](320, 55, 200, 100) next_rect =


[Link](320, 215, 200, 180) leaderboard_rect =
[Link](320, 430, 200, 150)

7
screen = [Link].set_mode((550, 620))
[Link].set_caption(f"Tetris - {username}") clock =
[Link]()

game = Game(username)

GAME_UPDATE = [Link] [Link].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 [Link](): if
[Link] == [Link]:
[Link]()
[Link]()

if [Link] == [Link]:
if game.game_over:
# Allow reset only after 2 seconds if game_over_time and
[Link].get_ticks() - game_over_time > 2000: [Link]()
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
[Link] == pygame.K_LEFT:
game.move_left() elif
[Link] == pygame.K_RIGHT:

8
game.move_right() elif
[Link] == pygame.K_DOWN:
game.move_down()
game.update_score(0, 1) elif [Link]
== pygame.K_UP:
[Link]()

if [Link] == GAME_UPDATE and not game.game_over:


game.move_down()

# Drawing UI
[Link](Colors.dark_blue)

# Score
score_value_surface = title_font.render(str([Link]), True, [Link])
[Link](score_surface, (365, 20))

[Link](screen, Colors.light_blue, score_rect, 0, 10)


[Link](score_value_surface,
score_value_surface.get_rect(centerx=score_rect.centerx, centery=score_rect.centery))

# Next Piece
[Link](next_surface, (375, 180))
[Link](screen, Colors.light_blue, next_rect, 0, 10)

# Leaderboard
[Link](leaderboard_surface, (340, 400))
[Link](screen, Colors.light_blue, leaderboard_rect, 0, 10)

# Display Best Score


best_score_surface = small_font.render(f"Best: {best_score}", True, [Link])
[Link](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, [Link])
[Link](leaderboard_entry, (330, y_offset)) y_offset
+= 30

[Link](screen) if
game.game_over:
[Link](game_over_surface, (180, 300))

if game_over_time is None:
game_over_time = [Link].get_ticks()
score_saved = False

elif [Link].get_ticks() - game_over_time > 2000:


if not score_saved: db.save_score(username,
[Link]) score_saved = True

for event in [Link](): if


[Link] == [Link]:
[Link]() game_over_time = None
score_saved = False top_scores =
db.fetch_top_scores(5) best_score =
db.get_best_score(username)
break

[Link]() [Link](60)

#[Link] import
[Link]

10
# MySQL Database Configuration
DB_CONFIG = {
"host": "localhost",
"user": "root",
"password": "Jaggu@0431",
"database": "tetris"
}

class Database: def


__init__(self):
"""Initialize the database connection.""" [Link] =
[Link](**DB_CONFIG) [Link] =
[Link]() self.create_tables()

def create_tables(self):
"""Create required tables if they don't exist."""
[Link]("CREATE DATABASE IF NOT EXISTS tetris")
[Link]("USE tetris")

# Create Users table [Link]("""


CREATE TABLE IF NOT EXISTS users ( id
INT AUTO_INCREMENT PRIMARY KEY, username
VARCHAR(50) UNIQUE NOT NULL, password
VARCHAR(255) NOT NULL
)
""")

[Link]("""
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)""")

[Link]()

def register_user(self, username, password):


"""Register a new user.""" try:
query = "INSERT INTO users (username, password) VALUES (%s, %s)"
[Link](query, (username, password)) [Link]()
return True except [Link]: 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"
[Link](query, (username, password))
return [Link]() 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)"


[Link](query, (username, score)) [Link]()

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
"""
[Link](query, (limit,)) return
[Link]()

def get_best_score(self, username):


"""Retrieve the highest score of a specific user."""
query = "SELECT MAX(score) FROM scores WHERE username = %s"
[Link](query, (username,)) result = [Link]()
return result[0] if result[0] is not None else 0

def close_connection(self):
"""Close the database connection properly."""
[Link]() [Link]()

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. [Link]
2. [Link]

17

Common questions

Powered by AI

Testing and debugging are integral processes that verify the correctness of game logic and database operations, ensuring that the game operates smoothly and meets user expectations . Through unit testing, issues with tetromino movements and score consistency can be identified, while debugging helps fix database connectivity bugs. This process not only enhances the game's reliability and performance but also improves user experience by delivering a polished final product .

The user authentication system enhances user engagement by allowing players to create accounts, log in, and thus personalize their gaming experiences. It makes it possible for players to save their progress and high scores, and track their performance over multiple sessions . This fosters a sense of continuity and investment in the game, as players can strive to improve their personal best or compete against others on the leaderboard .

The project uses animations and sound effects to enhance the gaming experience by making it more immersive and dynamic. Animations provide visual feedback for game events like clearing lines or game over scenarios, while sound effects heighten the interactive feel by audibly punctuating player actions and game achievements . These multimedia enhancements contribute to a more engaging and enjoyable user experience .

Implementing a GUI contributes to Tetris game development by providing an intuitive and visually engaging user experience. It facilitates player interactions through clearly designed menus for login, registration, and gameplay, enhancing accessibility and navigation . A well-constructed GUI can improve user experience by making the game more appealing and user-friendly, thereby supporting prolonged engagement .

OOP principles enhance the implementation by enabling modularity, reusability, and abstraction. The use of classes and objects allows for clear separation of concerns, where different game components (like the game logic and GUI elements) can be developed independently . Encapsulation helps in maintaining clean code by controlling access to certain parts of the game logic, which reduces errors and improves maintainability .

Database management plays a critical role by facilitating the storage and retrieval of user data, such as credentials and high scores, which are essential for implementing features like user authentication and leaderboards . This ensures that player data is securely stored and easily accessible, enhancing the game experience by enabling persistent gameplay across sessions and fostering competitiveness .

The leaderboard feature promotes competitiveness by displaying the top-performing players and their scores, encouraging others to improve and beat high scores . Its significance lies in fostering a competitive environment, which can increase player engagement and retention by appealing to players' desire for recognition and accomplishment .

Beginners might face challenges in managing real-time event handling while ensuring smooth gameplay, as this requires efficient coding practices and an understanding of asynchronous operations . Additionally, integrating database connectivity involves understanding how to securely store and retrieve data, manage concurrency issues, and ensure data integrity, all of which can be complex for those with limited experience .

Python and Pygame are effective for developing a game like Tetris due to their simplicity and ease of use, which is particularly beneficial for educational and prototyping purposes. Python's clear syntax allows developers to focus on game logic rather than language intricacies, while Pygame provides robust libraries for handling graphics, sounds, and input events, crucial for real-time games . However, performance limitations due to Python’s interpreted nature might pose challenges for more complex games .

The methodology contributes to success by providing a structured approach that includes requirement analysis, game design, and development phases. By emphasizing real-time event handling, database integration, and GUI design, it ensures that the game's core mechanics are robust and that additional features like user authentication and leaderboards are seamlessly integrated . Testing and debugging stages identify and rectify issues early, while optimization enhances performance, all leading to a smooth deployment process .

You might also like