Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the simple version of Tetris game by Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces Java how to achieve a simple version of the Tetris game, the content is very detailed, interested friends can refer to reference, I hope to help you.

The effect of the game page is as follows:

The logic of Tetris itself:

The logic of Tetris is relatively simple. It is similar to building houses, and various square shapes are different. However, the Tetris interface is evenly divided into rows and columns, so the essence of the block is how many cells it occupies.

First, consider the problem of data. For the interface, you need a two-dimensional int array that holds which places should have coloring and which ones don't, and then the blocks themselves, although they don't have the same shape, they can be surrounded by a 4x4 square, so it takes 16 bytes to save the information of a block.

Note: In fact, the data of the square can also be expressed as an int array, but it involves efficiency issues, and bit operations are faster than ordinary arithmetic operations.

Here are a few things to think about:

1) Birth of the box. It was born using random principles, and how does it initialize to be placed at the top of the game interface?

(2) The box needs to fall automatically. In the process of falling, it also needs to judge whether it conflicts with the surrounding environment and whether it can continue to fall.

(3) The square itself can also be deformed. After deformation, the square has different data, and the judgment method will be different. (4) When the user keeps holding down the s key, the square needs to keep falling.

Then there is the process, the player's main operation places have the following aspects:

(1) Left and right operation. You need to listen for KeyEvents and move the box left and right until it hits the boundary.

(2) Operation of deformation. Also listen for KeyEvents to make the box deform automatically.

(3) Downward operation. Also listen for KeyEvents and let the blocks drop quickly.

As for the end of the game, there is only one situation, and that is, the birth of the block conflicts with other blocks.

The source code is as follows:

package tetris; import java.awt.BorderLayout;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.KeyEvent;import java.awt.event.KeyListener; import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField; public class Main extends JFrame implements KeyListener { private JTextArea[][] grids;//Turn the entire interface into a text area where the entire game is played private int data[][]; //For each cell of data, 1 means there is a square, 0 means it is blank private int[] allRect; //All block types are stored in 16 bytes, Tetris graphics are in 4*4 cells private int rect; //type of block dropped by the current game; private int x, y; //Coordinates of the current square, x for row, y for column private int score = 0; //Record the score of the current game, 10 points for each level eliminated private JLabel label; //label showing score private JLabel label1;//Shows whether the game is over private boolean running; //Used to determine if the game is over /* parameterless constructor */ public Main() { grids = new JTextArea[26][12];//Sets the rows and columns of the game area data = new int[26][12];//open up data array space consistent with the rows and columns of the game area allRect = new int[] { 0x00cc, 0x8888, 0x000f, 0x0c44, 0x002e, 0x088c, 0x00e8, 0x0c88, 0x00e2, 0x044c, 0x008e, 0x08 c4, 0x006 c, 0x04 c8, 0x00 c6, 0x08 c8, 0x004 e, 0x04 c4, 0x00 e4 };//19 square shapes, such as 0x00 cc 0000 represents a square square 2*2 //0000 //1100 //1100 label = new JLabel("score: 0"); //This label stores scores, initialized to 0 points label1 = new JLabel("Start game"); //This label indicates the game status: start or end running = false; //for flag variable, false for game end, true for game in progress init(); //game interface initialization } /* game interface initialization function */ public void init() { JPanel center = new JPanel(); //This panel is the core area of the game JPanel right = new JPanel(); //This panel is the game description area center.setLayout(new GridLayout(26, 12, 1, 1)); //Divide the game core area into rows and columns totaling 26 rows and 12 columns for (int i = 0; i

< grids.length; i++) {//初始化面板 for (int j = 0; j < grids[i].length; j++) { grids[i][j] = new JTextArea(20, 20); grids[i][j].setBackground(Color.WHITE); grids[i][j].addKeyListener(this);// 添加键盘监听事件 //初始化游戏边界 if (j == 0 || j == grids[i].length - 1 || i == grids.length - 1) { grids[i][j].setBackground(Color.PINK); data[i][j] = 1; } grids[i][j].setEditable(false);// 文本区域不可编辑 center.add(grids[i][j]); //把文本区域添加到主面板上 } } //初始化游戏说明面板 right.setLayout(new GridLayout(4, 1)); right.add(new JLabel(" a : left d : right")); right.add(new JLabel(" s : down w : change")); right.add(label); label1.setForeground(Color.RED);// 设置标签内容为红色字体 right.add(label1); //把主面板和说明面板添加到窗体中 this.setLayout(new BorderLayout()); this.add(center, BorderLayout.CENTER); this.add(right, BorderLayout.EAST); running = true; //初始化running状态为true,表示程序运行即游戏开始 this.setSize(600, 850);// 设置窗体大小 this.setVisible(true);// 窗体可见 this.setLocationRelativeTo(null);// 设置窗体居中 this.setResizable(false);// 窗体大小不可改变 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 释放窗体 } /*主函数*/ public static void main(String[] args) { Main m = new Main(); //创建Main对象,主要用于初始化数据 m.go();// 开始游戏 } /*开始游戏*/ public void go() {// 开始游戏 while (true) {//游戏开始直到游戏失败才结束,否则一直执行 if (running == false) {//如果游戏失败 break; } ranRect();// 绘制下落方格形状 start();// 开始游戏 } label1.setText("游戏结束!");//则游戏结束 } /*绘制下落方格形状*/ public void ranRect() { rect = allRect[(int) (Math.random() * 19)];// 随机生成方块类型(共7种,19个形状) } /*游戏开始函数*/ public void start() { x = 0; y = 5; //初始化下落方块的位置 for (int i = 0; i < 26; i++) {//共26层,一层一层下落 try { Thread.sleep(1000);//每层延时1秒 if (canFall(x, y) == false) {// 如果不可以掉落 saveData(x, y);//把此方块区域data[][]标志为1,表示有数据 for (int k = x; k < x + 4; k++) {//循环遍历4层,看是否有哪一层都有方块的情况,以便消除那一行方格和统计得分 int sum = 0; for (int j = 1; j = 1; } m++;// 下一行 n = n - 4;// 回到首列 } return true;//可以掉落返回true } /*把不可下降的方块的对应的data存储为1,表示此坐标有方块*/ public void saveData(int m, int n) { int temp = 0x8000;//表示1000 0000 0000 0000 for (int i = 0; i < 4; i++) {//循环遍历16个方格(4*4) for (int j = 0; j < 4; j++) { if ((temp & rect) != 0) {// 此处有方块时 data[m][n] = 1;//data数组存放为1 } n++;//下一列 temp >

>= 1; } m++;//next line n = n - 4;//back to first column } } /* Remove all squares in row, descending from the top */ public void removeRow(int row) { for (int i = row; i >= 1; i--) { for (int j = 1; j 0)//When the square falls one level clear(m - 1, n);//Clear the previous colored square draw(m, n);//Redraw the square image } /* Clear the color before the block drops */ public void clear(int m, int n) { int temp = 0x8000;//indicates 1000 0000 0000 for (int i = 0; i

< 4; i++) {//循环遍历16个方格(4*4) for (int j = 0; j < 4; j++) { if ((temp & rect) != 0) {// 此处有方块时 grids[m][n].setBackground(Color.WHITE);//清除颜色,变为白色 } n++;//下一列 temp >

>= 1; } m++;//next line n = n - 4;//back to first column } } /* Draws the image of the fallen block */ public void draw(int m, int n) { int temp = 0x8000;//indicates 1000 0000 0000 for (int i = 0; i

< 4; i++) {//循环遍历16个方格(4*4) for (int j = 0; j < 4; j++) { if ((temp & rect) != 0) {// 此处有方块时 grids[m][n].setBackground(Color.GREEN);//有方块的地方变为绿色 } n++;//下一列 temp >

>= 1; } m++;//next line n = n - 4;//back to first column } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == 'a'){//square moves left if (running == false) { return; } if (y >= 1; } } clear(x, y);//Clear the color of the square before left shift when left shift operation is possible y--; draw(x, y);//then redraw the image of the left moved square } if (e.getKeyChar() == 'd'){//box moves right if (running == false) { return; } int temp = 0x8000; int m = x, n = y; int num = 7; for (int i = 0; i

< 4; i++) { for (int j = 0; j < 4; j++) { if ((temp & rect) != 0) { if (n >

num) { num = n; } } temp >>= 1; n++; } m++; n = n - 4; } if (num >= 10) { return; } temp = 0x8000; for (int i = x; i

< x + 4; i++) { for (int j = y; j < y + 4; j++) { if ((rect & temp) != 0) { if (data[i][j + 1] == 1) { return; } } temp >

>= 1; } } clear(x, y);//Clear the color of the square before the right shift when the right shift operation can be performed y++; draw(x, y);//then redraw the image of the square moved right } if (e.getKeyChar() == 's'){//box moves down if (running == false) { return; } if (canFall(x, y) == false) { saveData(x, y); return; } clear(x, y);//Clear the color of the box before moving down if it can be moved down x++; draw(x, y);//then redraw the image of the moved square } if (e.getKeyChar() == 'w'){//Change the shape of the box if (running == false) { return; } int i = 0; for (i = 0; i

< allRect.length; i++) {//循环遍历19个方块形状 if (allRect[i] == rect)//找到下落的方块对应的形状,然后进行形状改变 break; } if (i == 0)//为正方形方块无需形状改变,为方块图形种类1 return; clear(x, y); if (i == 1 || i == 2) {//为方块图形种类2 rect = allRect[i == 1 ? 2 : 1]; if (y >

7) y = 7; } if (i >= 3 && i 6 ? 3 : i + 1]; } if (i >= 7 && i 10 ? 7 : i + 1]; } if (i == 11 ||i == 12) {//is the type of square figure 5 rect = allRect[i == 11 ? 12 : 11]; } if (i == 13 ||i == 14) {//is the type of square graph 6 rect = allRect[i == 13 ? 14 : 13]; } if (i >= 15 && i 18 ? 15 : i + 1]; } draw(x, y); } }} About Java how to achieve a simple version of Tetris game to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report