0% found this document useful (0 votes)
10 views25 pages

TETRIS1 Merged

This document is a micro-project report on the Tetris game, submitted by students of the Yashwantrao Bhonsale Institute of Technology for their Computer Engineering diploma. It covers the implementation of Tetris using Java programming, detailing the game's rules, concepts of Java, and the programming design. The project aims to create a more challenging version of Tetris with augmented reality integration and modified gameplay mechanics.

Uploaded by

lochansawant0107
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)
10 views25 pages

TETRIS1 Merged

This document is a micro-project report on the Tetris game, submitted by students of the Yashwantrao Bhonsale Institute of Technology for their Computer Engineering diploma. It covers the implementation of Tetris using Java programming, detailing the game's rules, concepts of Java, and the programming design. The project aims to create a more challenging version of Tetris with augmented reality integration and modified gameplay mechanics.

Uploaded by

lochansawant0107
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/ 25

A

Micro-project
report on
Types of Network

Submitted To
MSBTE
In Partial Fulfilment of
Requirement of Diploma of
Computer Engineering
Under I Scheme
Submitted By

MS. TANAYA HANUMANT PASTE.


MS. ARYA SWANAND PAWAR.
MS. DASHMI PRAKASH RANE.
MS. LOCHAN DASHRATH SAWANT.

UNDER THE GUIDANCE of


Mr.T.C.MHAPANKAR
FOR ACADEMIC YEAR 2024-2025
YASHWANTRAO BHONASLE INSTITUE OF
TECHNOLOGY , SAWANTWADI
MAHARASHTRA STATE BOARD OF TECHNICAL
EDUCATION

CERTIFICATE

This is to certify that :-


MS. TANAYA HANUMANT PASTE. Roll No.98
MS. ARYA SWANAND PAWAR. Roll No.99
MS. DASHMI PRAKASH RANE. Roll No.100
MS. LOCHAN DASHRATH SAWANT. Roll No.104

Of Fourth semester of diploma in COMPUTER ENGINEERING Of Yashwantrao Bhonsale


Institute Of Technology (1742) has completed the Micro Project satisfactorily in subject Java
Programming (22412) for the academic year 2023 to 2024 as prescribed in the curriculum.

…………….. …………….. ……………...

Subject Faculty HOD Principal

Seal of
Institution
INDEX

SR.NO CONTENT PG.NO

1 Acknowledgement 1

2. Abstract 2

3. Introduction 3

4. Java Programming 4

5. Concepts of java 5-6

6. Rules to play tetris 7-8

7. Program 9-20

8. Output 21

9. Reference 22
Department of Computer Engineering Tetris Game

ACKNOWLEDGEMENT

First, I would like to take this opportunity to thank our lecturer MR.T.C.MHAPANKAR SIR
for guidance and advice on this project. This project would not have completed without their
enormous help and worthy experience.
I am very much thankful to Principal Mr. G. A. Bhosale for this support and encouragement.
This work I complete with blessings of my all-family members. I express my sincere
gratitude towards them for their kind co-operation and encouragement which helped me in
completion of this project. I would like to express my sincere thanks to all teaching and non-
teaching staff of department of COMPUTER ENGINEERING, YBIT for their expert advice
and help. It was indeed a fabulous experience and learning for me to work on this project.
Last but not least I would like to thank all my friends and well-wishers who were involved
directly or indirectly in successful completion of the present work.

YBIT 1|Page
Department of Computer Engineering Tetris Game

ABSTRACT

The Tetris game is one of the most popular computer games ever created. As the years go, there
are many developers that develop the tetris game due to the people in the world needs
something new in the game. This project will implement the concept of tetris game and make
the game more complicated by modify the directions of the falling tetrominoes and modify the
meeting point of the tetrominoes.
This project was made using the Java programming language and the data will be transformed
from binary numbers into a shape of the tetrominoes using the two dimensional array. The
output will be a tetris game which has four directions of the falling tetrominoes and will be met
together in the center of the board game.
Tetris game is a classic game of logic control. This article gives a programming design of Tetris
game based on the FPGA using VHDL. Game players can move and rotate blocks with the
PS/2 interface keyboard, and the game video is showed in a VGA monitor. The game realized
the function of the movement and rotation of blocks, randomly generating next blocks,
eliminating rows, getting scores and speeding up. It also contained the normal mode
corresponding to 7 types of blocks and the expert mode corresponding to 11 types of blocks.
Tetris is a very popular game that has served as an inspiration for many puzzle-style,
tilematching video games we have. The fan base is growing every year because there are many
variations of the game each with its own adjustments and different ways of gameplay. Each of
these variations have concepts such as, speed increase, special effects, music and theme
differences, colours, world environments, game boards and number of tetrominoes/shapes
possible to clear rows, new bonus awards other than getting a Tetris in the game, for example
DodecaTetris and OctoTetris.
Recently, the Tetris industry provided another variation called Tetris effect that heavily focuses
on effects and somewhat time manipulation which has helped the Tetris community experience
another addition of the game. This project seeks to provide a new variation of the Tetris game,
a harder and more compelling version. Previous variations kept the hold and next feature which
just makes the game too easy, especially for the Experts.
This Tetris project will remove them and may only make them available by earning scores and
levels for a temporary time. This project will also include an augmented reality integration to
give its final edge. The current literature on this Tetris game variation is examined in order to
clearly describe what has been done, what has worked, and the challenges that have arisen in
this context. To achieve the intended goal, a methodology and design approach were
established based on the literature research.

YBIT 2|Page
Department of Computer Engineering Tetris Game

INTRODUCTION

Java programming language, developed by Sun Microsystems (now owned by Oracle


Corporation), has emerged as one of the most popular and versatile programming languages
since its inception in the mid-1990s. Known for its platform independence, robustness, and
extensive libraries, Java has become the cornerstone of enterprise-level applications, mobile
app development, and web-based solutions.

One of Java's primary strengths lies in its "write once, run anywhere" philosophy, enabled by
the Java Virtual Machine (JVM). This unique feature allows Java programs to be compiled into
bytecode, which can then be executed on any device with a JVM installed, irrespective of the
underlying operating system. This portability makes Java an ideal choice for developing cross-
platform applications, ensuring consistent performance across diverse environments.

Furthermore, Java's object-oriented programming (OOP) paradigm facilitates modular and


scalable code development, enhancing code reusability and maintainability. With features like
classes, objects, inheritance, and polymorphism, developers can efficiently organize and
structure their codebase, leading to more manageable and extensible software projects.

Additionally, Java's rich standard library, coupled with a vast ecosystem of third-party libraries
and frameworks, provides developers with a wealth of tools and resources to streamline
development and tackle complex challenges effectively.

YBIT 3|Page
Department of Computer Engineering Tetris Game

JAVA PROGRAMMING

Java programming language, renowned for its versatility and robustness, offers a rich set of
features and capabilities that make it well-suited for a wide range of applications. One of the
key strengths of Java is its platform independence, achieved through the Java Virtual Machine
(JVM).
Java source code is compiled into bytecode, which can run on any device with a JVM installed,
regardless of the underlying hardware or operating system. This portability has made Java a
popular choice for developing cross-platform applications, including web applications, mobile
apps, and enterprise-level systems.
Java's object-oriented programming (OOP) paradigm is another fundamental aspect that
contributes to its popularity and effectiveness. With OOP, developers can model real-world
entities as objects, encapsulating data and behavior within classes. This approach promotes
code organization, modularity, and reusability, leading to more maintainable and scalable
software solutions. Inheritance, polymorphism, and encapsulation are core principles of OOP
supported by Java, allowing developers to create hierarchies of classes, achieve code
extensibility, and implement modular designs.
Java's security features, including its robust memory management, bytecode verification, and
sandboxing mechanisms, contribute to its reputation as a secure programming language,
making it a preferred choice for developing mission-critical and high-security applications.
Overall, Java's combination of platform independence, object-oriented programming,
extensive standard library, security features, and community-driven ecosystem makes it a
versatile and powerful tool for building a wide variety of software applications.

YBIT 4|Page
Department of Computer Engineering Tetris Game

CONCEPTS OF JAVA PROGRAMMING

Java programming encompasses a wide range of concepts that form the foundation of the
language and are essential for developing robust and efficient applications. Here are some key
concepts of Java programming:

1. Object-Oriented Programming (OOP): Java is a pure object-oriented


programming language, which means it revolves around the concept of objects. Objects
are instances of classes, which encapsulate data (attributes) and behavior (methods). OOP
principles such as encapsulation, inheritance, polymorphism, and abstraction are
fundamental to Java development.

2. Classes and Objects: Classes are blueprints for creating objects, defining their
structure and behavior. Objects are instances of classes, representing real-world entities.
Classes encapsulate data and behavior related to a particular entity, promoting code
reusability and modularity.

3. Inheritance: Inheritance allows a class (subclass or child class) to inherit attributes and
methods from another class (superclass or parent class). This promotes code reuse and
facilitates the creation of hierarchies of related classes.

4. Polymorphism: Polymorphism allows objects to be treated as instances of their parent


class or any of its subclasses interchangeably. This enables flexibility and extensibility in
code design, allowing different objects to respond differently to the same method call.

5. Abstraction: Abstraction involves hiding the implementation details of a class while


exposing a simplified interface for interacting with it. Abstract classes and interfaces are used
to achieve abstraction in Java, enabling modular and maintainable code.

6. Encapsulation: Encapsulation involves bundling data (attributes) and methods that


operate on that data within a single unit, typically a class. Access modifiers such as private,
protected, and public are used to control access to the encapsulated members, promoting data
security and code integrity.

YBIT 5|Page
Department of Computer Engineering Tetris Game

7. Packages: Packages are used to organize classes and interfaces into namespaces,
providing a hierarchical structure to Java applications. Packages help in avoiding naming
conflicts, enhancing code readability, and facilitating modular development.

8. Exception Handling: Java provides robust exception handling mechanisms to manage


runtime errors and unexpected situations gracefully. The try-catch-finally block is used to
handle exceptions, ensuring that programs can recover from errors and continue execution in a
controlled manner.

9. Multithreading: Java supports multithreading, allowing concurrent execution of


multiple threads within a single application. Multithreading enables efficient utilization of
system resources and enhances application responsiveness, especially in GUI and networked
applications.

10. Generics: Generics enable the creation of parameterized classes and methods, allowing
developers to write reusable and type-safe code. Generics enhance code readability and
maintainability by enabling compile-time type checking and reducing the need for explicit type
casting.

These are just a few of the many concepts that form the backbone of Java programming.
Mastering these concepts is essential for becoming proficient in Java development and building
robust, scalable, and maintainable software solutions.

YBIT 6|Page
Department of Computer Engineering Tetris Game

RULES TO PLAY TETRIS


There are several criteria which need to be met in order for a game to be considered fun.
Namely, it must have goals (so the player has something to achieve) and rules (so that the
player has a means to achieve those goals); it must also provide feedback (so that the players
can examine their progress or lack of it)

TETRIS

Tetris is a surprising game. On paper, at least, it seems unlikely that something so basic should
have done so well beyond the year 1975. Nevertheless, it’s been a consistently popular video
game for decades. It was invented in Russia, and it was never expected to be as popular as it
became. Yet, the reason it is so popular is that it meets the key criteria for fun in a game. That
is, it has goals, rules, feedback, participation is voluntary, and there are unnecessary obstacles
that keep the game challenging.

Goals
The aim in Tetris is simple; you bring down blocks from the top of the screen. You can move
the blocks around, either left to right and/or you can rotate them. The blocks fall at a certain
rate, but you can make them fall faster if you’re sure of your positioning. Your objective is to
get all the blocks to fill all the empty space in a line at the bottom of the screen; whenever you
do this, you’ll find that the blocks vanish and you get awarded some points.

A goal gives us a reason to play the game. Tetris offers an incredibly simple reason to play—
pitting your wits against the computerized block dropper in order to last as long as you can.

Rules
Tetris has very simple rules: you can only move the pieces in specific ways; your game is over
if your pieces reach the top of the screen; and you can only remove pieces from the screen by
filling all the blank space in a line.

Rules give much needed structure to our play. A completely random environment offers no
clue as to how to play and would be incredibly frustrating. How fortunate it is, then, that Tetris’s
three rules are what shape it into such an award-winning game.

YBIT 7|Page
Department of Computer Engineering Tetris Game

You have probably seen Tetris (or even played it), but, just in case—this is what Tetris looks
like.

Feedback
Each time you clear a line in Tetris, you are awarded more points. Each time your pieces reach
the top of the screen, your game is over. That means, if you’re not particularly attentive, your
game can be over very quickly.

Feedback in Tetris is instant and incontrovertible. You always know how well you are
performing as you play the game. We like feedback, and this enables us to feel
satisfied/dissatisfied with our performance. track here.

Obstacles
Tetris has a cunning means of adding challenge. It becomes faster the better you do. This means
you have to make the same decisions but under a higher level of pressure. There’s no end in
Tetris if you could think and move your fingers fast enough – you could literally play forever.
However, this is the real genius of Tetris – we play it because it keeps us in a state of “flow”;
that is, it balances our skills with the challenge in hand. We’ll never “finish” the game, but we
are constantly compelled to come back again and try to do a little bit better. Take the highest
level you’ve reached and remember the fast, furious gameplay involved. Yes, we’re talking
endorphins again… and going “Grr” when a piece lands badly… and perhaps shouting at
anyone who dares to distract us in these tension-laced-but-addictively-fun moments.

YBIT 8|Page
Department of Computer Engineering Tetris Game

PROGRAM

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Timer;

// this is class for all the shapes and their rotations


class Shape {
Tetrominoe pieceShape; // the shape of the piece
int coords[][]; // the coordinates of the piece
int[][][] coordsTable; // the coordinates of the piece in all its rotations

public Shape() {

initShape(); // initialize the shape


}

void initShape() {

coords = new int[4][2]; // initialize the size of the piece


setShape(Tetrominoe.NoShape); // set the shape to NoShape
}

// set the shape of the piece to the given shape and set the coordinates of the piece to the
coordinates of the given shape
protected void setShape(Tetrominoe shape) {

coordsTable = new int[][][] {


{ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } },
{ { 0, -1 }, { 0, 0 }, { -1, 0 }, { -1, 1 } },
{ { 0, -1 }, { 0, 0 }, { 1, 0 }, { 1, 1 } },
{ { 0, -1 }, { 0, 0 }, { 0, 1 }, { 0, 2 } },
{ { -1, 0 }, { 0, 0 }, { 1, 0 }, { 0, 1 } },
{ { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } },
{ { -1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } },
{ { 1, -1 }, { 0, -1 }, { 0, 0 }, { 0, 1 } }
};

for (int i = 0; i < 4 ; i++) { // for the no of rows in the shape

for (int j = 0; j < 2; ++j) { // for the no of columns in the shape

coords[i][j] = coordsTable[shape.ordinal()][i][j]; // set the coordinates of the piece to


the coordinates of the given shape
YBIT 9|Page
Department of Computer Engineering Tetris Game

}
}

pieceShape = shape;
}

void setX(int index, int x) { coords[index][0] = x; } // set the x coordinate of the piece
void setY(int index, int y) { coords[index][1] = y; } // set the y coordinate of the piece
public int x(int index) { return coords[index][0]; } // get the x coordinate of the piece
public int y(int index) { return coords[index][1]; } // get the y coordinate of the piece
public Tetrominoe getShape() { return pieceShape; } // get the shape of the piece

// set the shape of the piece to a random shape everytime a new piece is created
public void setRandomShape() {

Random r = new Random(); // create a random object


int x = Math.abs(r.nextInt()) % 7 + 1; // get a random number between 1 and 7
Tetrominoe[] values = Tetrominoe.values(); // get all the shapes
setShape(values[x]); // set the shape of the piece to a random shape
}

// get the minimum x coordinate of the piece


public int minX() {

int m = coords[0][0];

for (int i=0; i < 4; i++) { // for the no of rows in the shape

m = Math.min(m, coords[i][0]); // get the minimum x coordinate of the piece


}

return m; // return the minimum x coordinate of the piece


}

// get the minimum y coordinate of the piece


public int minY() {

int m = coords[0][1];

for (int i=0; i < 4; i++) { // for the no of rows in the shape

m = Math.min(m, coords[i][1]); // get the minimum y coordinate of the piece


}

return m; // return the minimum y coordinate of the piece


}

// rotate the piece to the left


YBIT 10 |
Page
Department of Computer Engineering Tetris Game

public Shape rotateLeft() {

if (pieceShape == Tetrominoe.SquareShape) // if the shape is a square shape


return this; // return the shape without rotation

Shape result = new Shape(); // create a new shape


result.pieceShape = pieceShape; // set the shape of the new shape to the shape of the piece

for (int i = 0; i < 4; ++i) { // for the no of rows in the shape

result.setX(i, y(i)); // set the x coordinate of the new shape to the y coordinate of the
piece
result.setY(i, -x(i)); // set the y coordinate of the new shape to the negative x coordinate
of the piece
}

return result; // return the new shape


}

// rotate the piece to the right


public Shape rotateRight() {

if (pieceShape == Tetrominoe.SquareShape) // if the shape is a square shape


return this; // return the shape without rotation

Shape result = new Shape(); // create a new shape


result.pieceShape = pieceShape; // set the shape of the new shape to the shape of the piece

for (int i = 0; i < 4; ++i) { // for the no of rows in the shape

result.setX(i, -y(i)); // set the x coordinate of the new shape to the negative y coordinate
of the piece
result.setY(i, x(i)); // set the y coordinate of the new shape to the x coordinate of the
piece
}

return result; // return the new shape


}
}

enum Tetrominoe { NoShape, ZShape, SShape, LineShape,


TShape, SquareShape, LShape, MirroredLShape };

// this is the class for the board


class Board extends JPanel {

static final long serialVersionUID = 1L;


final int BOARD_WIDTH = 10; // the width of the board
final int BOARD_HEIGHT = 22; // the height of the board
YBIT 11 |
Page
Department of Computer Engineering Tetris Game

final int INITIAL_DELAY = 100; // the initial delay of the timer


final int PERIOD_INTERVAL = 300; // the period interval of the timer

Timer timer;
boolean isFallingFinished = false; // check if the piece has finished falling
boolean isStarted = false; // check if the game has started
boolean isPaused = false; // check if the game is paused
int numLinesRemoved = 0; // the number of lines removed
int curX = 0; // the current x coordinate of the piece
int curY = 0; // the current y coordinate of the piece
JLabel statusbar;
Shape curPiece;
Tetrominoe[] board;

public Board(Tetris parent) {

initBoard(parent);
}

// initialize the board


void initBoard(Tetris parent) {

setFocusable(true);
setBorder(BorderFactory.createLineBorder(Color.pink, 4));
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(),
INITIAL_DELAY, PERIOD_INTERVAL);

curPiece = new Shape();

statusbar = parent.getStatusBar();
board = new Tetrominoe[BOARD_WIDTH * BOARD_HEIGHT];
addKeyListener(new TAdapter());
clearBoard();
}

int squareWidth() {
return (int) getSize().getWidth() / BOARD_WIDTH;
}

int squareHeight() {
return (int) getSize().getHeight() / BOARD_HEIGHT;
}

Tetrominoe shapeAt(int x, int y) {


return board[(y * BOARD_WIDTH) + x];
}

public void start() {


YBIT 12 |
Page
Department of Computer Engineering Tetris Game

isStarted = true;
clearBoard();
newPiece();
}

void pause() {

if (!isStarted) {
return;
}

isPaused = !isPaused;

if (isPaused) {

statusbar.setText("Paused");
} else {

statusbar.setText(String.valueOf(numLinesRemoved));
}
}

// draw the board


void doDrawing(Graphics g) {

Dimension size = getSize();


int boardTop = (int) size.getHeight() - BOARD_HEIGHT * squareHeight();

for (int i = 0; i < BOARD_HEIGHT; ++i) {

for (int j = 0; j < BOARD_WIDTH; ++j) {

Tetrominoe shape = shapeAt(j, BOARD_HEIGHT - i - 1);

if (shape != Tetrominoe.NoShape) {

drawSquare(g, 0 + j * squareWidth(),
boardTop + i * squareHeight(), shape);
}
}
}

if (curPiece.getShape() != Tetrominoe.NoShape) { // if the shape of the piece is not a no


shape

for (int i = 0; i < 4; ++i) { // for the no of rows in the shape

int x = curX + curPiece.x(i); // get the x coordinate of the piece


YBIT 13 |
Page
Department of Computer Engineering Tetris Game

int y = curY - curPiece.y(i); // get the y coordinate of the piece


drawSquare(g, 0 + x * squareWidth(),
boardTop + (BOARD_HEIGHT - y - 1) * squareHeight(),
curPiece.getShape()); // draw the piece on the board
}
}
}

// draw the square on the board


@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
doDrawing(g);
}

// draw the new coordinates of the piece while falling down


void dropDown() {

int newY = curY; // set the new y coordinate to the current y coordinate

while (newY > 0) { // while the new y coordinate is greater than 0

if (!tryMove(curPiece, curX, newY - 1)) { // if the piece cannot move to the new
coordinates

break; // break the loop


}

--newY; // decrement the new y coordinate


}

pieceDropped(); // call the piece dropped method


}

// draw the new coordinates of the piece while moving


void oneLineDown() {

if (!tryMove(curPiece, curX, curY - 1)) {

pieceDropped();
}
}

void clearBoard() {

for (int i = 0; i < BOARD_HEIGHT * BOARD_WIDTH; ++i) {


board[i] = Tetrominoe.NoShape;
}
YBIT 14 |
Page
Department of Computer Engineering Tetris Game

void pieceDropped() {

for (int i = 0; i < 4; ++i) {

int x = curX + curPiece.x(i);


int y = curY - curPiece.y(i);
board[(y * BOARD_WIDTH) + x] = curPiece.getShape();
}

removeFullLines(); // remove the full lines

if (!isFallingFinished) { // if the piece has not finished falling


newPiece(); // create a new piece
}
}

// create a new piece


void newPiece() {

curPiece.setRandomShape(); // set the shape of the piece to a random shape


curX = BOARD_WIDTH / 2 + 1; // set the x coordinate of the piece to the middle of the
board
curY = BOARD_HEIGHT - 1 + curPiece.minY();

if (!tryMove(curPiece, curX, curY)) { // if the piece cannot move to the new coordinates
curPiece.setShape(Tetrominoe.NoShape); // set the shape of the piece to a no shape
timer.cancel();
isStarted = false;
statusbar.setText("GAME OVER!");
}
}

// check if the piece can move to the new coordinates


boolean tryMove(Shape newPiece, int newX, int newY) {

for (int i = 0; i < 4; ++i) {

int x = newX + newPiece.x(i);


int y = newY - newPiece.y(i);

if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT) { // if the new


coordinates are out of the board
return false; // return false
}

if (shapeAt(x, y) != Tetrominoe.NoShape) { // if the new coordinates are not a no shape


return false; // return false
YBIT 15 |
Page
Department of Computer Engineering Tetris Game

}
}

curPiece = newPiece; // set the current piece to the new piece


curX = newX; // set the current x coordinate to the new x coordinate
curY = newY; // set the current y coordinate to the new y coordinate

repaint(); // repaint the board with the new coordinates of the piece

return true; // return true


}

// remove the full line from the board


void removeFullLines() {

int numFullLines = 0; // set the number of full lines to 0

for (int i = BOARD_HEIGHT - 1; i >= 0; --i) { // for the no of rows in the board
boolean lineIsFull = true; // set the line is full to true

for (int j = 0; j < BOARD_WIDTH; ++j) { // for the no of columns in the board

if (shapeAt(j, i) == Tetrominoe.NoShape) { // if the shape at the coordinates is a no


shape

lineIsFull = false; // set the line is full to false


break; // break the loop
}
}

if (lineIsFull) { // if the line is full

++numFullLines; // increment the number of full lines

for (int k = i; k < BOARD_HEIGHT - 1; ++k) { // for the no of rows in the board
for (int j = 0; j < BOARD_WIDTH; ++j) { // for the no of columns in the board

board[(k * BOARD_WIDTH) + j] = shapeAt(j, k + 1); // set the shape at the


coordinates to the shape at the coordinates below
}
}
}
}

if (numFullLines > 0) { // if the number of full lines is greater than 0

numLinesRemoved += numFullLines; // increment the number of lines removed by the


number of full lines

YBIT 16 |
Page
Department of Computer Engineering Tetris Game

statusbar.setText("Score: "+String.valueOf(numLinesRemoved)); // set the text of the


score to the number of lines removed
isFallingFinished = true; // set the piece has finished falling to true
curPiece.setShape(Tetrominoe.NoShape); // set the shape of the piece to a no shape
repaint();
}
}

// draw the square on the board


void drawSquare(Graphics g, int x, int y,
Tetrominoe shape) {

Color colors[] = {
new Color(0, 0, 0), new Color(204, 102, 102),
new Color(102, 204, 102), new Color(102, 102, 204),
new Color(204, 204, 102), new Color(204, 102, 204),
new Color(102, 204, 204), new Color(218, 170, 0),

};

Color color = colors[shape.ordinal()];

g.setColor(color);
g.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2);

g.setColor(color.brighter());
g.drawLine(x, y + squareHeight() - 1, x, y);
g.drawLine(x, y, x + squareWidth() - 1, y);

g.setColor(color.darker());
g.drawLine(x + 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + squareHeight() - 1);
g.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
x + squareWidth() - 1, y + 1);

void doGameCycle() {

update();
repaint();
}

void update() {

if (isPaused) { // if the game is paused


return; // return
}

YBIT 17 |
Page
Department of Computer Engineering Tetris Game

if (isFallingFinished) { // if the piece has finished falling

isFallingFinished = false; // set the piece has finished falling to false


newPiece(); // create a new piece
} else {

oneLineDown(); // move the piece down one line


}
}

// used to check the pressed keys


class TAdapter extends KeyAdapter {

@Override
public void keyPressed(KeyEvent e) {

if (!isStarted || curPiece.getShape() == Tetrominoe.NoShape) { // if the game has not


started or the shape of the piece is a no shape
return; // return
}

int keycode = e.getKeyCode(); // get the key code of the pressed key

if (keycode == KeyEvent.VK_ENTER) { // if the pressed key is the enter key


pause(); // pause the game
return; // return
}

if (isPaused) {
return;
}

switch (keycode) { // switch the key code of the pressed key

case KeyEvent.VK_LEFT: // if the pressed key is the left arrow


tryMove(curPiece, curX - 1, curY); // try to move the piece to the left
break;

case KeyEvent.VK_RIGHT: // if the pressed key is the right arrow


tryMove(curPiece, curX + 1, curY); // try to move the piece to the right
break;

case KeyEvent.VK_DOWN: // if the pressed key is the down arrow


tryMove(curPiece.rotateRight(), curX, curY); // try to rotate the piece to the right
break;

case KeyEvent.VK_UP: // if the pressed key is the up arrow


tryMove(curPiece.rotateLeft(), curX, curY); // try to rotate the piece to the left
break;
YBIT 18 |
Page
Department of Computer Engineering Tetris Game

case KeyEvent.VK_SPACE: // if the pressed key is the space bar


dropDown(); // drop the piece down
break;

case KeyEvent.VK_D: // if the pressed key is the d key


oneLineDown(); // move the piece down one line
break;
}
}
}

class ScheduleTask extends TimerTask {

@Override
public void run() {

doGameCycle();
}
}
}

// main class of the game


class Tetris extends JFrame {

static final long serialVersionUID = 1L;


JLabel statusbar;

public Tetris() {

initUI();
}

void initUI() {

JPanel panel = new JPanel();


panel.setBackground(new Color(0XF5EBE0));

statusbar = new JLabel("Score: 0");


statusbar.setFont(new Font("MV Boli", Font.BOLD, 30));
panel.add(statusbar, BorderLayout.NORTH);

Board board = new Board(this);


add(panel, BorderLayout.NORTH);
add(board);
board.setBackground(new Color(0Xf0e2d3));
board.start();

setTitle("Tetris");
YBIT 19 |
Page
Department of Computer Engineering Tetris Game

setSize(400, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
}

public JLabel getStatusBar() {

return statusbar;
}

// run the game from here


public static void main(String[] args) {

EventQueue.invokeLater(() -> {

Tetris game = new Tetris();


game.setVisible(true);
});
}
}

YBIT 20 |
Page
Department of Computer Engineering Tetris Game

OUTPUT

YBIT 21 |
Page
Department of Computer Engineering Tetris Game

REFERENCE

https://www.cs.cornell.edu/boom/1999sp/projects/Tetris/whatis.htmL

https://tetris.com/about-us

https://medium.com/better-advice/playing-tetris-with-your-time-6ea044e64e0a

https://www.britannica.com/topic/Tetris

YBIT 22 |
Page

You might also like