The examples in this article share with you the specific code of Java implementation Tetris for your reference. The specific content is as follows
Tetris design ideas
Tetris has been playing since childhood. Everyone knows the rules. In the past, I thought that thing was very fun, but I just couldn’t win. Now I have learned to write one by myself and practice it every day!
Keyboard operation:
Left key: move left; right key: move right;
Up key: Change the shape and lower key: Accelerate the drop (no problem, no further rectification)
If the squares of any row are full, this line will be eliminated. Eliminating a row of squares will get 10 points. At present, I have not set the levels. Babies who like it can set the levels themselves;
So where did those square shapes come from? It is designed by us ourselves. The common shapes are: I type, T type, L type, Tianzi grid type, etc., add them yourself!
So what happened? In fact, it’s just a 4*4 array. Of course, you can design n*n happily, you have the final say!
So, I gave an example below to tell you why the shapes you see can be changed is designed in advance, 0 is empty and 1 is a filler, so that you can create shapes in your game!
Forget it: Just put the picture and see the code running results first:
Like it? If you like it, just do it directly. Maybe the code is not well written enough. Please forgive me. I will summarize more when I look back and will keep updating the code;
GamePanel class: game interface class, the entire block is dropped and displayed, and the game's logic Slow is implemented in this class;
package tetris;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.Timer;public class GamePanel extends JPanel implements KeyListener{ private int mapRow = 21; private int mapCol = 12; private int mapGame[][] = new int[mapRow][mapCol];//Open a two-dimensional array space to store our map information private Timer timer; private int score = 0;//Record the score Random random = new Random(); private int curShapeType = -1; private int curShapeState = -1;//Set the current shape type and current shape status private int nextShapeType = -1; private int nextShapeState = -1;//Set the type and status of the block group that appears next time private int posx = 0; private int posy = 0; private final int shapes[][][] = new int[][]{ //T glyphs are stored in counterclockwise order { {0,1,0,0, 1,1,1,0, 0,0,0,0,0,0,0}, {0,1,0,0, 1,1,0,0,0,0,0,0,0}, //I glyphs are stored in counterclockwise order { {0,0,0,0, 1,1,1,1,1,0,0,0,0, 0,0,0,0,0}, {0,1,0,0,0, 0,1,0,0, 0,1,0,0,0,0,0,0,0,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0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0}, {1,1,0,0, 0,1,0,0,0,0,0,0,0}, {1,1,1,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0} } } }; private int rowRect = 4; private int colRect = 4;//Here we regard the stored image as a 4*4 two-dimensional array. Although we use a one-dimensional array to store it above, we still need to regard it as a two-dimensional array to implement private int RectWidth = 10; public GamePanel()//Constructor----Create a good map { CreateRect(); initMap();//Initialize this map SetWall();//Set wall// CreateRect(); timer = new Timer(500,new TimerListener()); timer.start(); } class TimerListener implements ActionListener{ public void actionPerformed(ActionEvent e) { MoveDown(); } } public void SetWall()//Column 0 and 11 are both walls, and row 20 is also walls { for(int i = 0; i < mapRow; i++)//Draw the column first { mapGame[i][0] = 2; mapGame[i][11] = 2; } for(int j = 1; j < mapCol-1; j++)//Draw the last line { mapGame[20][j] = 2; } } public void initMap()//Initialize this map, the wall ID is 2, the space ID is 0, and the block ID is 1 { for(int i = 0; i < mapRow; i++) { for(int j = 0; j < mapCol; j++) { mapGame[i][j] = 0; } } } public void CreateRect()//Create block---If the current block type and state exist, set the next time, if not, set the current state and type { if(curShapeType == -1 && curShapeState == -1)//The current block state is 1, indicating that the game has just started { curShapeType = random.nextInt(shapes.length); curShapeState = random.nextInt(shapes[0].length); } else { curShapeType = nextShapeType; curShapeState = nextShapeState; } nextShapeType = random.nextInt(shapes.length); nextShapeState = random.nextInt(shapes[0].length); posx = 0; posy = 1;//Create a square in the upper left corner of the wall if(GameOver(posx,posy,curShapeType,curShapeState)) { JOptionPane.showConfirmDialog(null, "Game end!", "Tip", JOptionPane.OK_OPTION); System.exit(0); } } public boolean GameOver(int x, int y, int ShapeType, int ShapeState)//Judge whether the game ends { if(IsOrNoMove(x,y,ShapeType,ShapeState)) { return false; } return true; } public boolean IsOrNoMove(int x, int y, int ShapeType, int ShapeState)//Judge whether the current figure can be moved. Here we emphasize that the coordinates of x and y refer to the upper left target of a two-dimensional array of 4*4 (the array describing the figure) { for(int i = 0; i < rowRect ; i++) { for(int j = 0; j < colRect; j++) { if(shapes[ShapeType][ShapeState][i*colRect+j] == 1 && mapGame[x+i][y+j] == 1 || shapes[ShapeType][ShapeState][i*colRect+j] == 1 && mapGame[x+i][y+j] == 2) { return false; } } } return true; } public void Turn()//Rotate { int temp = curShapeState; curShapeState = (curShapeState+1) % shapes[0].length; if(IsOrNoMove(posx,posy,curShapeType,curShapeState)) { } else { curShapeState = temp; } repaint(); } public void MoveDown()//Move down { if(IsOrNoMove(posx+1,posy,curShapeType,curShapeState)) { posx++; } else { AddToMap();//Fix this line in the map CheckLine(); CreateRect();//Recreate a new block} repaint(); } public void MoveLeft()//Move left { if(IsOrNoMove(posx,posy-1,curShapeType,curShapeState)) { posy--; } repaint(); } public void MoveRight()//Move right { if(IsOrNoMove(posx,posy+1,curShapeType,curShapeState)) { posy++; } repaint(); } public void AddToMap()//Fix the fallen image into the map { for(int i = 0; i < rowRect; i++) { for(int j = 0; j < colRect; j++) { if(shapes[curShapeType][curShapeState][i*colRect+j] == 1) { mapGame[posx+i][posy+j] = shapes[curShapeType][curShapeState][i*colRect+j]; } } } } public void CheckLine()//Check whether there are full rows in these lines { int count = 0; for(int i = mapRow-2; i >= 0; i--) { count = 0; for(int j = 1; j < mapCol-1; j++) { if(mapGame[i][j] == 1) { count++; } else break; } if(count >= mapCol-2) { for(int k = i; k > 0; k--) { for(int p = 1; p < mapCol-1; p++) { mapGame[k][p] = mapGame[k-1][p]; } } score += 10; i++; } } } public void paint(Graphics g)//Repaint window { super.paint(g); for(int i = 0; i < rowRect; i++)//Draw the falling block { for(int j = 0; j < colRect; j++) { if(shapes[curShapeType][curShapeState][i*colRect+j] == 1) { g.fillRect((posy+j+1)*RectWidth, (posx+i+1)*RectWidth, RectWidth, RectWidth); } } } for(int i = 0; i < mapRow; i++)//Draw the block information that has been fixed on the map { for(int j = 0; j < mapCol; j++) { if(mapGame[i][j] == 2)//Draw the wall{ g.drawRect((j+1)*RectWidth, (i+1)*RectWidth, RectWidth, RectWidth); } if(mapGame[i][j] == 1)//Draw small square{ g.fillRect((j+1)*RectWidth, (i+1)*RectWidth, RectWidth, RectWidth); } } } g.drawString("score = "+ score, 225, 15); g.drawString("next square:", 225, 50); for(int i = 0; j < colRect; j++) { if(shapes[nextShapeType][nextShapeState][i*colRect+j] == 1) { g.fillRect(225+(j*RectWidth), 100+(i*RectWidth), RectWidth, RectWidth); } } } } public void NewGame()//The game starts again{ score = 0; initMap(); SetWall(); CreateRect(); repaint(); } public void StopGame()//The game pauses{ timer.stop(); } public void ContinueGame() { timer.start(); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_UP://up------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- KeyEvent.VK_RIGHT://right----MoveRight(); break; } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub }} GameFrame class: The entry port of the entire game, well, to put it bluntly, it is a class with the main() function. This class implements some designs of the game interface, which you can understand as a small UI;
package tetris;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;public class GameFrame extends JFrame implements ActionListener{ private int widthFrame = 500; private int heightFrame = 600; private JMenu menu = new JMenu("Game");//Create a menu private JMenuItem newGame = menu.add("Restart");//Create a built-in menu option private JMenuItem exitGame = menu.add("Game Exit"); private JMenuItem stopGame = menu.add("Game Pause"); private JMenuItem goOnGame = menu.add("Game Continue"); private JMenu menutwo = new JMenu("Help");//Create a second menu private JMenuItem aboutGame = menutwo.add("About the game"); GamePanel gamepanel = new GamePanel(); public GameFrame()//Constructor { addKeyListener(gamepanel); newGame.addActionListener(this); exitGame.addActionListener(this); stopGame.addActionListener(this); goOnGame.addActionListener(this); aboutGame.addActionListener(this); this.add(gamepanel); JMenuBar menu = new JMenuBar(); menu.add(menuone); menu.add(menutwo); this.setJMenuBar(menu); this.setTitle("Tetris"); this.setBounds(50, 10, widthFrame, heightFrame); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if(e.getSource() == newGame)//The game starts again{ gamepanel.NewGame(); } if(e.getSource() == exitGame)//Game Exit { System.exit(0); } if(e.getSource() == stopGame)//Game pause { gamepanel.StopGame(); } if(e.getSource() == goOnGame)//Game Continue { gamepanel.ContinueGame(); } if(e.getSource() == aboutGame)//About game information { JOptionPane.showMessageDialog(null, "Move left and right keys, create rotation upward", "Prompt", JOptionPane.OK_OPTION); } } public static void main(String[] args) { new GameFrame(); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.