0% found this document useful (0 votes)
62 views34 pages

CS Project

The document outlines the requirements and development of a Tetris game project. It details the hardware and software requirements, aims and objectives of the project, and provides code snippets of the game implementation including block and tetromino classes.
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)
62 views34 pages

CS Project

The document outlines the requirements and development of a Tetris game project. It details the hardware and software requirements, aims and objectives of the project, and provides code snippets of the game implementation including block and tetromino classes.
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/ 34

HARDWARE REQUIREMENT:

1. Computer, with more than 4GB RAM (8 GB RAM preferable)


2. Relatively strong internet connection with free access
3. Mouse/Touchpad
4. Intel core i5 processor or equivalent
5. 15 GB available hard disk space

SOFTWARE REQUIREMENT:
1.Python 3.8.10
2.Spyder ide
3.Tetriminos Sprites (PNG Format)
4. Pygame, Math, Pathlib, Random, SYS Modules
5. Anaconda Packages
6. Font if any (.TTF Format)
SYNOPSIS OF THE PROJECT:

The Tetris Game Development Project is a comprehensive exploration into the


realms of software development and game design.
"In Tetris, players complete lines by moving differently shaped pieces
(tetrominoes) which descend onto the playing field. The completed lines
disappear and grant the player points, and the player can proceed to fill the
vacated spaces. The game ends when the playing field is filled.” The purpose of
this project was to build a Tetris video game system using Python language and
pygame module. Our Tetris game is a single player game where the computer
randomly generates tetromino blocks (in the shapes of O, J, L, Z, S, I) that the
user can rotate using their game controller.
Tetrominoes can be stacked to create lines to be cleared by the computer and be
counted as points that will be tracked. Once a tetromino passes the boundary of
the screen the user will lose.
In addition to the technical aspects, the project places emphasis on user
interface design, aiming to craft an intuitive and visually appealing interface.
This includes elements such as score displays, level progression indicators, and
responsive feedback mechanisms.
The Tetris Game Development Project is not only a demonstration of
programming prowess but also an opportunity to apply theoretical knowledge
practically. Through detailed documentation, rigorous testing, and creative
customization options, the project aims to present a comprehensive showcase of
the student's skills in software development, combining theoretical
understanding with hands-on application to bring the timeless Tetris game to a
new digital realm. The primary objective is to bring the iconic Tetris game to
life through programming and algorithmic implementation.
COMPUTER SCiEnCE
PROJECT FiLE

PROJECT NAME: TETRIS GAME

CLASS AND SECTION: XII B

Student Names:
1. ANUJ PANDEY
2.YASHASVIE CHANDRA
3. OJAS PEDNEKER
AIM AND OBJECTIVE

Aim:
The primary aim of my Class 12 Computer Science project is to develop a captivating and
functional video game based on the classic Tetris. This project aims to provide an immersive
gaming experience that reflects both creativity and technical proficiency.

Objectives:
1. *Game Development Proficiency: * Demonstrate a comprehensive understanding of
programming languages and game development tools to create a Tetris game from scratch.

2. *Algorithmic Implementation: * Implement the core algorithms and logic required for
Tetris gameplay, including block movement, rotation, and line clearing, while ensuring
efficiency and responsiveness.

3. *User Interface Design: * Design an intuitive and visually appealing user interface that
enhances the overall gaming experience, incorporating elements such as score displays, level
progression, and clear feedback mechanisms.

4. *Scalability: * Develop the game with a focus on scalability, allowing for potential future
enhancements and modifications to the game structure or features.

5. *Code Optimization: * Apply effective coding practices to optimize the performance of the
game, ensuring smooth gameplay even on devices with varying specifications.

6. *Documentation: * Create comprehensive documentation that outlines the project's design,


implementation details, and user instructions, providing a clear reference for users and future
developers.

7.*Learning and Application: * Utilize this project as a practical application of theoretical


concepts learned during the computer science course, showcasing the ability to translate
knowledge into real-world software development.
DECLARATION

I, Anuj Pandey, Board roll No. a student of DPS, Navi

Mumbai humbly submit that I have completed the project work as

described in this report by my own skill and study as per the

instructions of my teacher Ms. Radhika Sridhar and that I have not

copied the report or its any appreciable parts from any other literature

in contravention of the academic ethics.

DATE: SIGNATURE OF THE STUDENT


Integrating Python with MySQL: A Brief Overview:

In the realm of database management, the integration of Python and MySQL


stands as a powerful combination, offering developers a versatile toolkit for
building robust and scalable applications. Python, a widely used programming
language known for its readability and ease of use, seamlessly connects to
MySQL, a popular open-source relational database management system. The
initial section introduces the fundamentals of Python and MySQL connectivity,
covering the installation of necessary libraries and configuration of connection
parameters. Following this, the outline delves into the execution of basic CRUD
(Create, Read, Update, Delete) operations, emphasizing the essential aspects of
establishing connections, handling errors, and executing SQL queries within the
Python environment.
There are also various career options where Python is a key skill such as:
• Game developer
• Web designer
• Python developer
• Full-stack developer
• Machine learning engineer
• Data scientist
Moving beyond the basics, the second paragraph explores advanced topics and
best practices in Python-MySQL integration. It addresses error handling and
exception management, shedding light on common pitfalls and strategies to
ensure robustness in applications. Additionally, the outline touches upon
security considerations, emphasizing the protection of database credentials and
the implementation of best practices to prevent SQL injection. The advanced
topics section delves into transaction management, discussing the importance of
data integrity through transactions and the utilization of rollbacks. Lastly, the
outline introduces connection pooling as an optimization strategy, enhancing
performance by efficiently managing database connections. This comprehensive
approach aims to equip developers with a holistic understanding of Python and
MySQL integration, spanning from fundamental connectivity to advanced
techniques and best practices.
ACKNOWLEDGEMENT

I hereby thank the school and the staff of the computer science
department for all the guidance and support extended to me
during this project.

My special thanks are due to the principal for providing us


with the right platform and environment to complete the
project.

My sincere thanks to Ms. Radhika Sridhar, our Computer


Science teacher, for her able guidance, unflinching support
and the affectionate touch without which this project would
not have been a success.

Finally, I thank all those who have directly or indirectly


contributed to the success of this project.

Name: Anuj Pandey


Board Roll No:
CODE
INPUT

SETTING.PY:
import pygame as pg
vec = pg.math.Vector2
#FRAMES PER SECOND
FPS = 60
#COLOUR
FIELD_COLOR = (48, 39, 32)
BG_COLOR = (24, 89, 117)

SPRITE_DIR_PATH = 'TETRIS/assets/sprites'

FONT_PATH = 'FREAKSOFNATUREMASSIVE.ttf'
#MILLISECONDS
ANIM_TIME_INTERVAL = 200
FAST_ANIM_TIME_INTERVAL = 15

TILE_SIZE = 50
FIELD_SIZE = FIELD_W, FIELD_H = 10, 20
FIELD_RES = FIELD_W * TILE_SIZE, FIELD_H * TILE_SIZE

FIELD_SCALE_W, FIELD_SCALE_H = 1.7, 1.0


WIN_RES = WIN_W, WIN_H = FIELD_RES [0] * FIELD_SCALE_W, FIELD_RES[1] *
FIELD_SCALE_H
#INITIAL POSITION OF TETROMINO ON THE FIELD
INIT_POS_OFFSET = vec(FIELD_W // 2 - 1, 0)
NEXT_POS_OFFSET = vec(FIELD_W * 1.3, FIELD_H * 0.45)
MOVE_DIRECTIONS = {'left': vec(-1, 0), 'right': vec(1, 0), 'down': vec(0, 1)}
#TETRIMONO SHAPES
TETROMINOES = {
'T': [(0, 0), (-1, 0), (1, 0), (0, -1)],
'O': [(0, 0), (0, -1), (1, 0), (1, -1)],
'J': [(0, 0), (-1, 0), (0, -1), (0, -2)],
'L': [(0, 0), (1, 0), (0, -1), (0, -2)],
'I': [(0, 0), (0, 1), (0, -1), (0, -2)],
'S': [(0, 0), (-1, 0), (0, -1), (1, -1)],
'Z': [(0, 0), (1, 0), (0, -1), (-1, -1)]
}
TETROMINO.PY:
from TETRIS.settings import *

import random

#CREATING BLOCK CLASS


class Block(pg.sprite.Sprite):
#INTIALIZING ATTRIBUTES OF BLOCK CLASS
def __init__(self, tetromino, pos):
self.tetromino = tetromino
self.pos = vec(pos) + INIT_POS_OFFSET
self.next_pos = vec(pos) + NEXT_POS_OFFSET
self.alive = True

super().__init__(tetromino.tetris.sprite_group)
self.image = tetromino.image
self.rect = self.image.get_rect()
self.sfx_image = self.image.copy()
self.sfx_image.set_alpha(110)
self.sfx_speed = random.uniform(0.2, 0.6)
self.sfx_cycles = random.randrange(6, 8)
self.cycle_counter = 0
#SPECIAL EFFECT DURATION
def sfx_end_time(self):
if self.tetromino.tetris.app.anim_trigger:
self.cycle_counter += 1
if self.cycle_counter > self.sfx_cycles:
self.cycle_counter = 0
return True
#SPECIAL EFFECT ANIMATION
def sfx_run(self):
self.image = self.sfx_image
self.pos.y -= self.sfx_speed
self.image = pg.transform.rotate(self.image, pg.time.get_ticks() * self.sfx_speed)
#CHECKING FOR GAME STATE
def is_alive(self):
if not self.alive:
if not self.sfx_end_time():
self.sfx_run()
else:
self.kill()
#ROTATING THE BLOCKS
def rotate(self, pivot_pos):
translated = self.pos - pivot_pos
rotated = translated.rotate(90)
return rotated + pivot_pos
#UPDATING THE POSITION OF THE BLOCKS
def set_rect_pos(self):
pos = [self.next_pos, self.pos][self.tetromino.current]
self.rect.topleft = pos * TILE_SIZE
#RUNNING THE ABOOVE FUNCTION WHILE GAME RUNS
def update(self):
self.is_alive()
self.set_rect_pos()
#CHECKING FOR BLOCK COLLISION WITH BOUNDRIES
def is_collide(self, pos):
x, y = int(pos.x), int(pos.y)
if 0 <= x < FIELD_W and y < FIELD_H and (
y < 0 or not self.tetromino.tetris.field_array[y][x]):
return False
return True
#DEFINING TETROMINO CLASS
class Tetromino:
#INITIALIZING ATTRIBUTES OF TETROMINO CLASS
def __init__(self, tetris, current=True):
self.tetris = tetris
self.shape = random.choice(list(TETROMINOES.keys()))
self.image = random.choice(tetris.app.images)
self.blocks = [Block(self, pos) for pos in TETROMINOES[self.shape]]
self.landing = False
self.current = current
#ROATATING TETROMINO BLOCKS
def rotate(self):
pivot_pos = self.blocks[0].pos
new_block_positions = [block.rotate(pivot_pos) for block in self.blocks]
if not self.is_collide(new_block_positions):
for i, block in enumerate(self.blocks):
block.pos = new_block_positions[i]
#CHECKING FOR TETROMINO COLLISON WITH THE BOUNDRIES
def is_collide(self, block_positions):
return any(map(Block.is_collide, self.blocks, block_positions))
#NEW POSITION OF THE TETROMINO
def move(self, direction):
move_direction = MOVE_DIRECTIONS[direction]
new_block_positions = [block.pos + move_direction for block in self.blocks]
is_collide = self.is_collide(new_block_positions)
if not is_collide:
for block in self.blocks:
block.pos += move_direction
elif direction == 'down':
self.landing = True
#MOVING TETROMINO DOWN
def update(self):
self.move(direction='down')
TETRIS.PY:

from TETRIS.settings import *


import math
from TETRIS.tetromino import Tetromino
import pygame.freetype as ft

#ON SCREEN TEXT DISPLAY


class Text:
#INTIALIZING TEXT
def __init__(self, app):
self.app = app
self.font = ft.Font(FONT_PATH)
#PICKING COLOUR
def get_color(self):
time = pg.time.get_ticks() * 0.001
n_sin = lambda t: (math.sin(t) * 0.5 + 0.5) * 255
return n_sin(time * 0.5), n_sin(time * 0.2), n_sin(time * 0.9)
#DISPLAYING TEXT
def draw(self):
self.font.render_to(self.app.screen, (WIN_W * 0.595, WIN_H * 0.02),
text='TETRIS', fgcolor=self.get_color(),
size=TILE_SIZE * 1.65, bgcolor='black')
self.font.render_to(self.app.screen, (WIN_W * 0.65, WIN_H * 0.22),
text='next', fgcolor='orange',
size=TILE_SIZE * 1.4, bgcolor='black')
self.font.render_to(self.app.screen, (WIN_W * 0.595, WIN_H * 0.67),
text='score', fgcolor='orange',
size=TILE_SIZE * 1.1, bgcolor='black')
self.font.render_to(self.app.screen, (WIN_W * 0.88, WIN_H * 0.67),
text=f'{self.app.tetris.score}', fgcolor='white',
size=TILE_SIZE * 1.1)

Class Tetris:
#INTIALIZING TETRIS CLASS
def __init__(self, app):
self.app = app
self.sprite_group = pg.sprite.Group()
self.field_array = self.get_field_array()
self.tetromino = Tetromino(self)
self.next_tetromino = Tetromino(self, current=False)
self.speed_up = False
self.highscore= 0
self.score = 0
self.full_lines = 0
self.points_per_lines = {0: 0, 1: 10, 2: 30, 3: 70, 4: 150}
#SCORE CALCULATION AND SAVING
def get_score(self):
self.score += self.points_per_lines[self.full_lines]
self.full_lines = 0
#CHECKING FOR FULL LINES FOR SCORE
def check_full_lines(self):
row = FIELD_H - 1
for y in range(FIELD_H - 1, -1, -1):
for x in range(FIELD_W):
self.field_array[row][x] = self.field_array[y][x]

if self.field_array[y][x]:
self.field_array[row][x].pos = vec(x, y)

if sum(map(bool, self.field_array[y])) < FIELD_W:


row -= 1
else:
for x in range(FIELD_W):
self.field_array[row][x].alive = False
self.field_array[row][x] = 0

self.full_lines += 1
#PUTTING TETROMINO BLOCKS IN THE ARRAY
def put_tetromino_blocks_in_array(self):
for block in self.tetromino.blocks:
x, y = int(block.pos.x), int(block.pos.y)
self.field_array[y][x] = block
#CREATING A 2D ARRAY FOR STORING INFORMATION OF LANDED
TETROMINOS
def get_field_array(self):
return [[0 for x in range(FIELD_W)] for y in range(FIELD_H)]
#GAMES= STATE CEHCK FOR GAME OVER
def is_game_over(self):
if self.tetromino.blocks[0].pos.y == INIT_POS_OFFSET[1]:

pg.time.wait(300)
return True
#CHECK FOR LANDING OF TETROMINO
def check_tetromino_landing(self):
if self.tetromino.landing:
if self.is_game_over():
self.__init__(self.app)
else:
self.speed_up = False
self.put_tetromino_blocks_in_array()
self.next_tetromino.current = True
self.tetromino = self.next_tetromino
self.next_tetromino = Tetromino(self, current=False)
#USER INPUT KEYS DEFINITION
def control(self, pressed_key):
if pressed_key == pg.K_LEFT:
self.tetromino.move(direction='left')
elif pressed_key == pg.K_RIGHT:
self.tetromino.move(direction='right')
elif pressed_key == pg.K_UP:
self.tetromino.rotate()
elif pressed_key == pg.K_DOWN:
self.speed_up = True
#CREATING TETROMINO GRID
def draw_grid(self):
for x in range(FIELD_W):
for y in range(FIELD_H):
pg.draw.rect(self.app.screen, 'black',
(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE),
1),pg.RESIZABLE
#UPDATING SCORE,CHECKING FOR LINES,GAME STATE
def update(self):
trigger = [self.app.anim_trigger, self.app.fast_anim_trigger][self.speed_up]
if trigger:
self.check_full_lines()
self.tetromino.update()
self.check_tetromino_landing()
self.get_score()
self.sprite_group.update()
#DISPLAYING TETROMINO IN GRID
def draw(self):
self.draw_grid()
self.sprite_group.draw(self.app.screen)
MAIN.PY:
from TETRIS.settings import *
from TETRIS.tetris import Tetris, Text
import sys
import pathlib

#CREATING APPLICATION CLASS (MAIN PROGRAM)


class App:
#INTIALIZING ATTRIBUTES OF APPLICATION CLASS
def __init__(self):
pg.init()
pg.display.set_caption('Tetris')
self.screen = pg.display.set_mode(WIN_RES)
self.clock = pg.time.Clock()
self.set_timer()
self.images = self.load_images()
self.tetris = Tetris(self)
self.text = Text(self)
#LOADING TETROMINO SPRITES
def load_images(self):
files = [item for item in pathlib.Path(SPRITE_DIR_PATH).rglob('*.png') if
item.is_file()]
images = [pg.image.load(file).convert_alpha() for file in files]
images = [pg.transform.scale(image, (TILE_SIZE, TILE_SIZE)) for image in images]
return images
#FUNCTION TO SET THE TIMER FOR ANIMATION
def set_timer(self):
self.user_event = pg.USEREVENT + 0
self.fast_user_event = pg.USEREVENT + 1
self.anim_trigger = False
self.fast_anim_trigger = False
pg.time.set_timer(self.user_event, ANIM_TIME_INTERVAL)
pg.time.set_timer(self.fast_user_event, FAST_ANIM_TIME_INTERVAL)
#UPDATING TIMER AND TETRIS CLASS
def update(self):
self.tetris.update()
self.clock.tick(FPS)

#DRAWING TETRIS FIELD


def draw(self):
self.screen.fill(color=BG_COLOR)
self.screen.fill(color=FIELD_COLOR, rect=(0, 0, *FIELD_RES))
self.tetris.draw()
self.text.draw()
pg.display.flip()
#CHECKING FOR USER INPUTS
def check_events(self):
self.anim_trigger = False
self.fast_anim_trigger = False
for event in pg.event.get():
if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key ==
pg.K_ESCAPE):
pg.quit()
sys.exit()
elif event.type == pg.KEYDOWN:
self.tetris.control(pressed_key=event.key)
elif event.type == self.user_event:
self.anim_trigger = True
elif event.type == self.fast_user_event:
self.fast_anim_trigger = True
#RUNNING APPLICATION
def run(self):
while True:
self.check_events()
self.update()
self.draw()

#EXECUTING THE CODE


if __name__ == '__main__':
app = App()
app.run()
OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy