Business requirements -> Business object model ( Object relation )-> Data modeling -> Class design -> Summary code -> Detailed functional design

Basic rules :

1) Tetris is made one by one Cell Constitutive :

Row width :10, Column height :20, In units of each small square

2) secondly , All Tetris are a set of 4 A regular figure consisting of a small square Tetromino

Respectively :S,Z,L,J,I,O,T These kinds

Data structure design :

Cell     lattice

|--     int row that 's ok

|--     int col column

|--     Image image Mapping

Tetromino     Four squares , have 7 Subclass

|--     Cell[] cells     contain 4 A grid

Tetris     Tetris

|--     int score     fraction

|--     int lines       Number of rows

|--     Cell[][] wall = new Cell[20][10]     20*10 Wall of

|--     Tetromino tetromino     Falling block

|--     Trtromino nextOne         Next drop box

The second is function :

Drop movement function

Rotating process

Timed automatic falling

suspend

continue

End the game

Algorithm design :

4 Initial form of grid :I S Z J L T O

In the numerical state design of the initial data

Calculation of the falling of four squares : Is to put each grid row+1

Calculation of left-right movement of four grid blocks : Is to put each grid col+1 or col-1

Falling process control : Controls the control relationship between the falling block and the wall

1) If " Can fall ", Just one step down

2) Otherwise " Land inside the wall "

3) After landing , " Destroy full rows ", And score

4) Check if the game is over

5) If it's not over , Can you play , The next box is generated

Score calculation

Interface drawing

Keyboard event control

Rotary process control

Accelerated descent process control

Scoring

Start process control (Timer)

Master refresh (Timer) frequency : 1/100 second

0.5 Perform a drop every 2 seconds ( Is the primary refresh 50 times )

Timed call using timer Falling process

If you pause , Don't perform the drop process

Implementation process :

1) stay Tetris Class Timer, Used to start the main refresh rate

2) stay Tetris Class level Is the number of fall intervals

as : 50 express 50 After refresh , Execute once whereabouts , If reduced ,

Speed up the fall

3)  stay Tetris Class stepIndex Is the drop count

whenever stepIndex % level == 0 time Execute once whereabouts

4) stay Tetris Class   pause Pause execution status control

5) stay action() Method to add a master refresh Timer Start of

In master refresh Add code Control fall

Draw background picture

1) stay Tetris Class background

2) Using static code blocks Load disk file to memory object

Will be used to Picture reading API: ImageIO

3) stay paint Method

draw Falling block

1) First in action Production in method The falling box and the next box

2) stay paint Call in method paintTetromino() method

3) stay Tetris In class increase paintTetromino() method

Will be falling 4 Each grid of the grid box is drawn one by one

Move the box

1) Handling keyboard events (API), Get when the user pressed -> 

2) When pressed -> When pressing the key , Execute current 4 Grid square Move right method

3) Move right method Will change the current 4 The column coordinates of each grid of a grid

4) Call inherited from JPanel Class repaint(), This method will be as soon as possible

call paint()

5) paint() Based on the current data ( Data that has been moved right )

Draw all panel effects

The following is the source code :

Cell.java( Ripstop )

1 packagecom.timmy.tetris;2 importjava.awt.Image;3 public classCell {4 /**

5 * A grid 6 */

7 private introw;8 private intcol;9 privateImage image;10 public Cell(int
row,intcol,Image image){11 this.row =row;12 this.col =col;13 this.image
=image;14 }15

16 //toString Print rows and columns , Convenient debugging

17 publicString toString(){18 return "["+row+","+col+"]";19 }20

21 public voiddrop(){22 row++;23 }24

25 public voidmoveLeft(){26 col--;27 }28

29 public voidmoveRight(){30 col++;31 }32

33

34 public void setRow(introw){35 this.row =row;36 }37

38 public intgetRow(){39 returnrow;40 }41 public intgetCol() {42 returncol;43
}44 public void setCol(intcol) {45 this.col =col;46 }47 publicImage getImage()
{48 returnimage;49 }50 public voidsetImage(Image image) {51 this.image
=image;52 }53 }

Tetromino.java( Quad block class )

1 packagecom.timmy.tetris;2 importjava.util.Random;3 // abstract class

4 public abstract classTetromino {5 /**

6 * Quad block class 7 */

8 // It's for subclasses , So use protection

9 protected Cell[] cells = new Cell[4];10 protected State[] states;// Rotation state

11

12 /** Private constructor , There will be no subclasses */

13 privateTetromino(){14 }15

16 /** Inner class , rotate */

17 protected classState{18 introw0,col0,row1,col1,row2,col2,row3,col3;19
public State(int row0, int col0, int row1, int col1, introw2,20 int col2, int
row3, intcol3) {21 super();22 this.row0 =row0;23 this.col0 =col0;24 this.row1
=row1;25 this.col1 =col1;26 this.row2 =row2;27 this.col2 =col2;28 this.row3
=row3;29 this.col3 =col3;30 }31 }32

33 /** Rotation subscript */

34 private int index = 10000;35

36 /** turn right */

37 public voidrotateRight(){38 index++; //10001

39 State s = states[index%states.length];// Remainder is [1]40 //s = s1

41 Cell o = cells[0];// find 0 No. 1 grid as rotation axis

42 int row =o.getRow();43 int col =o.getCol();44
cells[1].setRow(row+s.row1);45 cells[1].setCol(col+s.col1);46
cells[2].setRow(row+s.row2);47 cells[2].setCol(col+s.col2);48
cells[3].setRow(row+s.row3);49 cells[3].setCol(col+s.col3);50 }51

52 /** turn left */

53 public voidrotateLeft(){54 index--;55 State s =
states[index%states.length];56 Cell o = cells[0];57 int row =o.getRow();58 int
col =o.getCol();59 cells[1].setRow(row+s.row1);60
cells[1].setCol(col+s.col1);61 cells[2].setRow(row+s.row2);62
cells[2].setCol(col+s.col2);63 cells[3].setRow(row+s.row3);64
cells[3].setCol(col+s.col3);65 }66

67 /** One step down */

68 public voidsoftDrop(){69 for(int i=0;i

86 }87

88 // Simple factory method model :

89 public staticTetromino randomOne(){90 Random r = newRandom();91 int type =
r.nextInt(7);92 switch(type){93 case 0: return newT();94 case 1: return
newI();95 case 2: return newS();96 case 3: return newZ();97 case 4: return
newL();98 case 5: return newJ();99 case 6: return newO();100 }101 return
null;102 }103

104 // Using private inner classes , Encapsulates the details of subclass implementation , Forever only 7 Seed class 105 // Static will cause direct access with class names , External don't know , Others can't new

106 private static class T extendsTetromino{107 publicT(){108 cells[0] = new
Cell(0,4,Tetris.T);109 cells[1] = new Cell(0,3,Tetris.T);110 cells[2] = new
Cell(0,5,Tetris.T);111 cells[3] = new Cell(1,4,Tetris.T);112 states = new
State[4];113 states[0] = new State(0,0,0,-1,0,1,1,0);114 states[1] = new
State(0,0,-1,0,1,0,0,-1);115 states[2] = new State(0,0,0,1,0,-1,-1,0);116
states[3] = new State(0,0,1,0,-1,0,0,1);117 }118 }119 private static class I
extendsTetromino{120 publicI(){121 cells[0] = new Cell(0,4,Tetris.I);122
cells[1] = new Cell(0,3,Tetris.I);123 cells[2] = new Cell(0,5,Tetris.I);124
cells[3] = new Cell(0,6,Tetris.I);125 states = new State[2];126 states[0] = new
State(0,0,0,-1,0,1,0,2);127 states[1] = new State(0,0,-1,0,1,0,2,0);128 }129

130 }131 private static class S extendsTetromino{132 publicS(){133 cells[0] =
new Cell(0,4,Tetris.S);134 cells[1] = new Cell(0,5,Tetris.S);135 cells[2] = new
Cell(1,3,Tetris.S);136 cells[3] = new Cell(1,4,Tetris.S);137 states = new
State[2];138 states[0] = new State(0,0,1,0,-1,-1,0,-1);139 states[1] = new
State(0,0,0,1,1,-1,1,0);140

141 }142

143 }144 private static class Z extendsTetromino{145 publicZ(){146 cells[0] =
new Cell(1,4,Tetris.Z);147 cells[1] = new Cell(0,3,Tetris.Z);148 cells[2] = new
Cell(0,4,Tetris.Z);149 cells[3] = new Cell(1,5,Tetris.Z);150 states = new
State[2];151 states[0] = new State(0,0,-1,1,0,1,1,0);152 states[1] = new
State(0,0,-1,-1,-1,0,0,1);153 }154

155 }156 private static class L extendsTetromino{157 publicL(){158 cells[0] =
new Cell(0,4,Tetris.L);159 cells[1] = new Cell(0,3,Tetris.L);160 cells[2] = new
Cell(0,5,Tetris.L);161 cells[3] = new Cell(1,3,Tetris.L);162 states = new
State[4];163 states[0] = new State(0,0,-1,0,1,0,-1,-1);164 states[1] = new
State(0,0,0,1,0,-1,-1,1);165 states[2] = new State(0,0,1,0,-1,0,1,1);166
states[3] = new State(0,0,0,-1,0,1,1,-1);167 }168

169 }170 private static class J extendsTetromino{171 publicJ(){172 cells[0] =
new Cell(0,4,Tetris.J);173 cells[1] = new Cell(0,3,Tetris.J);174 cells[2] = new
Cell(0,5,Tetris.J);175 cells[3] = new Cell(1,5,Tetris.J);176 states = new
State[4];177 states[0] = new State(0,0,-1,0,1,0,1,-1);178 states[1] = new
State(0,0,0,1,0,-1,-1,-1);179 states[2] = new State(0,0,1,0,-1,0,-1,1);180
states[3] = new State(0,0,0,-1,0,1,1,1);181 }182

183 }184 private static class O extendsTetromino{185 publicO(){186 cells[0] =
new Cell(0,4,Tetris.O);187 cells[1] = new Cell(0,5,Tetris.O);188 cells[2] = new
Cell(1,4,Tetris.O);189 cells[3] = new Cell(1,5,Tetris.O);190 states = new
State[1];191 states[0] = new State(0,0,0,1,1,0,1,1);192 }193

194 }195 }

Tetris.java( Tetris class 【 Main class 】)

1 packagecom.timmy.tetris;2 importjava.awt.Color;3 importjava.awt.Font;4
importjava.awt.Graphics;5 importjava.awt.Image;6
importjava.awt.event.KeyAdapter;7 importjava.awt.event.KeyEvent;8
importjava.awt.event.KeyListener;9 importjava.util.Arrays;10
importjava.util.Timer;11 importjava.util.TimerTask;12
importjavax.imageio.ImageIO;13 importjavax.swing.JPanel;14
importjavax.swing.JFrame;15 //JPanel A blank panel that can be displayed on the graphical interface ( Blank rectangular area )16 // Extended panel for
Tetris , Expand out fraction and Falling 17 // block , And the next falling box

18 public class Tetris extendsJPanel{19 /**

20 * Tetris class , Inherit from JPanel21 */

22 public static final int ROWS = 20;23 public static final int COLS = 10;24
// The drawing size of the grid

25 public static final int CELL_SIZE = 26;26 // Number of rows

27 private intlines;28 // fraction

29 private intscore;30 // Font color

31 public static final int FONT_COLOR =0x667799;32 public static final int
FONT_SIZE = 30;33

34 private booleanpause;35 private booleangameOver;36 privateTimer timer;37
// time interval

38 private int inteval = 500;39 // wall

40 private Cell[][] wall = new Cell[20][10];41 // Falling block

42 privateTetromino tetromino;43 // Next box

44 privateTetromino nextOne;45 // Score table , Used to eliminate different rows at one time , Give different scores

46 private int[] scoreTable= {0,1,5,10,20};47 // Static loading of picture resources using static code blocks 48
// Picture files on disk , Picture object loaded into memory

49 public staticImage background;50 public staticImage gameOverImg;51 public
staticImage I;52 public staticImage T;53 public staticImage S;54 public
staticImage Z;55 public staticImage L;56 public staticImage J;57 public
staticImage O;58

59 static {// Static code block , Execute only once 60 //Class Class provides methods getResource() Can locate 61 //package File location in 62
// Picture files to objects in memory 63 //tetris.png Documents and Tetris.class In the same package

64 try{65 Class cls = Tetris.class;66 background =
ImageIO.read(cls.getResource("tetris.png"));67 gameOverImg =
ImageIO.read(cls.getResource("game-over.png"));68 I =
ImageIO.read(cls.getResource("I.png"));69 L =
ImageIO.read(cls.getResource("L.png"));70 J =
ImageIO.read(cls.getResource("J.png"));71 O =
ImageIO.read(cls.getResource("O.png"));72 S =
ImageIO.read(cls.getResource("S.png"));73 T =
ImageIO.read(cls.getResource("T.png"));74 Z =
ImageIO.read(cls.getResource("Z.png"));75 }catch(Exception e){76
e.printStackTrace();77 }78 }79

80 /** Draw interface */

81 // Override parent class JPanel Class paint method ( Drawing method )82 // The of the parent class was modified after overriding paint method , The purpose is to achieve custom drawing 83 //Graphics
Understood as a brush bound to the current panel

84 public voidpaint(Graphics g){85 g.drawImage(background, 0, 0, null);86
// Coordinate system translation

87 g.translate(15,15);88 // Painting wall

89 paintWall(g);90 // Draw a falling square

91 paintTetromino(g);92 // Draw the next falling square

93 paintnextOne(g);94 // Draw score

95 paintScore(g);96 if(gameOver){97 g.translate(-5, -5);98
g.drawImage(gameOverImg,0,0,null);99 }100 }101

102 /** Draw score */

103 private voidpaintScore(Graphics g) {104

105 int x = 289;106 int y = 165;107 g.setColor(newColor(FONT_COLOR));108 Font
font = getFont();// Get system font

109 font = newFont(font.getFontName(),font.BOLD,FONT_SIZE);110
g.setFont(font);111 String str = "SCORE:" +score;112 g.drawString(str, x,
y);113 y+= 54;114 str = "LINES:" +lines;115 g.drawString(str, x, y);116 y+=
54;117 str = "[P]Pause";118 if(pause){119 str = "[C]CONTINUE";120 }121
if(gameOver){122 str = "[S]RESTART";123 }124 g.drawString(str, x, y);125 }126

127 /** Draw wall , Is to Wall Draw the contents of the array to the interface */

128 private voidpaintWall(Graphics g){129 for(int row=0;row

131 Cell[] line =wall[row];132 for(int col=0;col

134 Cell cell =line[col];135 int x = col*CELL_SIZE;136 int y =
row*CELL_SIZE;137 if(cell==null){138 g.setColor(new Color(0));// black 139 // Draw a square

140 g.drawRect(x, y,CELL_SIZE, CELL_SIZE);141 }else{142
g.drawImage(cell.getImage(), x-1, y-1, null);143 }144 }145 }146 }147

148 /** execute */

149 public voidaction(){150 startAction();151 repaint();//JPanel
Redrawing method in , Will be called as soon as possible paint152 // Keyboard key listener ,KeyListener yes KeyAdapter Parent class of 153 // Using anonymous inner classes

154 KeyListener l = newKeyAdapter() {155 // If a key is pressed , Will execute

156 public voidkeyPressed(KeyEvent e){157 int key =e.getKeyCode();158 if(key
==KeyEvent.VK_Q){159 System.exit(0);// End program

160 }161 if(gameOver){162 if(key ==KeyEvent.VK_S){163 startAction();164
repaint();165 }166 return;167 }168 if(pause){169 if(key ==KeyEvent.VK_C){170
continueAction();171 }172 return; // Early termination method , Do not process subsequent events

173 }174 switch(key){175 caseKeyEvent.VK_DOWN:softDropAction();176 break;177
caseKeyEvent.VK_RIGHT:moveRightAction();178 break;179
caseKeyEvent.VK_LEFT:moveLeftAction();180 break;181
caseKeyEvent.VK_UP:rotateRightAction();182 break;183
caseKeyEvent.VK_SPACE:hardDropAction();184 break;185
caseKeyEvent.VK_P:pauseAction();186 break;187 }188 repaint();// Repaint

189 }190 };191 // The keyboard listener object , Add to panel

192 this.addKeyListener(l);//this Represents the current Tetris panel

193 this.requestFocus();// Get focus

194 }195

196 /** Square rotation */

197 private voidrotateRightAction() {198 tetromino.rotateRight();199
if(outOfBounds() ||coincide()){200 tetromino.rotateLeft();201 }202 }203

204 /** Painting falling blocks */

205 public voidpaintTetromino(Graphics g){206 // If there is no falling box , Don't draw

207 if(tetromino==null){208 return;209 }210 Cell[] cells =tetromino.cells;211
for(int i=0;i

219 /** Draw the next box */

220 public voidpaintnextOne(Graphics g){221 // If there is no falling box , Don't draw

222 if(tetromino==null){223 return;224 }225 Cell[] cells =nextOne.cells;226
for(int i=0;i

234 /** Falling method */

235 private voidsoftDropAction(){236 if(canDrop()){237
tetromino.softDrop();238 }else{239 landToWall();240 destroyLines();241
checkGameOver();242 tetromino =nextOne;243 nextOne =Tetromino.randomOne();244
}245 }246

247 /** Check whether the current square can fall */

248 private booleancanDrop(){249 Cell[] cells =tetromino.cells;250
// Check whether the current square reaches the bottom

251 for(Cell cell: cells){252 int row =cell.getRow();253 if(row==ROWS-1){254
return false;255 }256 }257 // Check to see if the wall

258 for(Cell cell:cells){259 int row =cell.getRow();260 int col
=cell.getCol();261 if(wall[row+1][col]!=null){262 return false;263 }264 }265
return true;266 }267 /** Land on the wall */

268 private voidlandToWall(){269 Cell[] cells =tetromino.cells;270 for(Cell
cell:cells){271 int row =cell.getRow();272 int col =cell.getCol();273
wall[row][col] =cell;274 }275 }276

277 /** Hard fall */

278 public voidhardDropAction(){279 while(canDrop()){280
tetromino.softDrop();281 }282 landToWall();283 destroyLines();284
checkGameOver();285 tetromino =nextOne;286 nextOne =Tetromino.randomOne();287
}288

289 /** Eliminate row */

290 private voiddestroyLines(){291 int lines = 0;292 for(int row=0;row

302 /** Check if this line is full */

303 private boolean fullCells(introw){304 Cell[] line =wall[row];305 for(Cell
cell:line){306 if(cell==null){307 return false;308 }309 }310 return true;311
}312

313 /** Delete row */

314 private void deleteLine(introw){315 for(int i=row;i>=1;i--){316
//wall[i-1]->wall[i]

317 System.arraycopy(wall[i-1], 0, wall[i], 0, COLS);318 }319
Arrays.fill(wall[0], null);// Zero line

320 }321

322 /** Check if the game is over */

323 private voidcheckGameOver(){324 if(wall[0][4] != null){325 gameOver =
true;326 timer.cancel();327 repaint();328 }329 }330

331 /** Move left */

332 private voidmoveLeftAction(){333 tetromino.moveLeft();334 if(outOfBounds()
||coincide()){335 tetromino.moveRight();336 }337 repaint();338 }339

340 /** Move right */

341 private voidmoveRightAction(){342 tetromino.moveRight();343
// The inspection sequence must be to check whether it is out of bounds first , Recheck whether it coincides

344 if(outOfBounds() ||coincide()){345 tetromino.moveLeft();346 }347
repaint();348 }349

350 /** Check out of bounds */

351 private booleanoutOfBounds(){352 Cell[] cells =tetromino.cells;353
for(Cell cell : cells){354 int col =cell.getCol();355 if(col<0 ||
col>=COLS){356 return true;357 }358 }359 return false;360 }361

362 /** Check whether the grid will coincide */

363 private booleancoincide(){364 Cell[] cells =tetromino.cells;365 for(Cell
cell : cells){366 int row =cell.getRow();367 int col =cell.getCol();368
if(row>=0 && row=0 && col

375 /** start */

376 public voidstartAction(){377 pause = false;378 gameOver = false;379 score
= 0;380 lines = 0;381 for(Cell[] line : wall){382 Arrays.fill(line, null);383
}384 tetromino =Tetromino.randomOne();385 nextOne =Tetromino.randomOne();386
TimerTask task = newTimerTask() {387 public voidrun(){388 softDropAction();389
repaint();390 }391 };392 timer = newTimer();393 timer.schedule(task, inteval,
inteval);394 }395

396 /** suspend */

397 public voidpauseAction(){398 timer.cancel();399 pause = true;400 }401

402 /** continue */

403 public voidcontinueAction(){404 pause = false;405 timer = newTimer();406
timer.schedule(newTimerTask(){407 public voidrun(){408 softDropAction();409
repaint();410 }411 },inteval,inteval);412 pause = false;413 }414

415 /**main method */

416

417 public static voidmain(String[] args) {418 JFrame frame = new
JFrame(" Tetris ");// Window box

419 Tetris tetris = new Tetris();//Tetris Inherited JPanel420 //Tetris
It's also a panel , The panel can be placed frame Display in

421

422 frame.add(tetris);423 // Go window decoration

424 frame.setUndecorated(true);425 frame.setSize(530,580);426
// The default closing action of the setup window is to exit the program

427 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);428
// Set window visible ,frame It will be called as soon as possible when it is displayed paint method

429 frame.setVisible(true);430 // Set window center

431 frame.setLocationRelativeTo(null);432 // starting position

433 tetris.action();434 }435 }

Technology
©2019-2020 Toolsou All rights reserved,
Redis Underlying data structure A person who dissuades others from learning computer , Are not good people win10 System computer C Where's the disc ,c disc users where? (win10c Disk not found users) Freshman c Language student management system ( lower ) hospital WIFI Which family is strong ? utilize Python Script unlimited spoof girlfriend computer C language program design —— Student management system Byte runout - Test development practice - One side cool meridian python Run code at specified time 5 Best style Linux Server system recommendation Anti anxiety life after naked resignation , I believe everything will have the best arrangement