-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTetris.java
155 lines (144 loc) · 3.46 KB
/
Tetris.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/**
* Creates a tetris game on a grid using blocks
*
* @author Anna Wang
* @version January 9, 2017
*/
public class Tetris implements ArrowListener
{
private MyBoundedGrid<Block> grid;
private BlockDisplay display;
private Tetrad tetrad;
/**
* Rotates the tetrad
*/
public void upPressed()
{
tetrad.rotate();
display.showBlocks();
}
/**
* Translates the tetrad one down
*/
public void downPressed()
{
tetrad.translate(1,0);
display.showBlocks();
}
/**
* Translates the tetrad one left
*/
public void leftPressed()
{
tetrad.translate(0,-1);
display.showBlocks();
}
/**
* Translates the tetrad one right
*/
public void rightPressed()
{
tetrad.translate(0,1);
display.showBlocks();
}
/**
* Constructs a Tetris game.
*/
public Tetris()
{
grid= new MyBoundedGrid<Block>(20,10);
display= new BlockDisplay(grid);
display.setArrowListener(this);
display.setTitle("Tetris");
tetrad=new Tetrad(grid);
display.showBlocks();
}
/**
* Plays the tetris game
*/
public void play()
{
while(true)
{
try
{
//Pause for 1000 milliseconds.
Thread.sleep(1000);
tetrad.translate(1,0);
display.showBlocks();
}
catch (InterruptedException e)
{
//ignore
}
if(!tetrad.translate(1,0))
{
tetrad=new Tetrad(grid);
for (int i=0; i<grid.getNumRows(); i++)
{
clearRow(i);
}
}
}
}
/**
* Checks if it's a completed row
* @param row the row it is checking
* @return true if it can be completed; otherwise
* false
*/
private boolean isCompletedRow(int row)
{
for (int i=0; i<grid.getNumCols(); i++)
{
Location temp= new Location(row, i);
if (grid.get(temp)==null)
{
return false;
}
}
return true;
}
/**
* Clears the row
* @param row the row it is clearing
*/
private void clearRow(int row)
{
if (isCompletedRow(row))
{
for (int i=0; i<grid.getNumCols(); i++)
{
Location temp= new Location(row, i);
Block removeThis= grid.get(temp);
removeThis.removeSelfFromGrid();
}
for (int r=grid.getNumRows()-1; r>=0; r--)
{
for (int c=0; c<grid.getNumCols(); c++)
{
Location loc=new Location(r,c);
if (grid.get(loc)!=null)
{
Block temporary=grid.get(loc);
Location newLoc= new Location(r+1,c);
if (grid.isValid(newLoc))
{
temporary.moveTo(newLoc);
}
}
}
}
}
}
/**
* Plays the game
*
* @param args arguments from the command line
*/
public static void main(String [ ] args)
{
Tetris game=new Tetris();
game.play();
}
}