Design and implementation of Tetris game system based on Java (project report + defense PPT + source code + database + screenshots + deployment video)

Design and implementation of Tetris game based on Java

    Tetris is a popular game around the world and has been popular on computers, mobile phones, and handheld game consoles from the beginning to the present. It is a simple classic game with simple game rules, but it is not lacking in fun. It is easy to learn and applicable. The scope is broad and well known. The simple basic rules of the Tetris game are that 7 different regular graphics composed of small squares fall from the screen one after another. The player moves to make a complete horizontal bar when it falls, and then disappears. The player scores points and the game level increases. The game ends when the remaining graphics pile up to the top of the screen.

    Tetris was originally a casual game developed by Russian Alexei Pajitnov in 1984. It once created unparalleled commercial value and influenced the development and industrial chain of a generation of casual games. With the continuous development and changes of the information age and science and technology, computers have been popularized in everyone's life. In the busy work life, this type of casual games brings some relaxation to people.

    This paper describes and analyzes in detail the basic ideas and some basic game rules of the classic traditional Tetris implementation. On this basis, it further develops the innovative and creative model of Tetris and develops an accompanying game based on the classic game. As the score increases and the level increases, the difficulty increases. Modules that can control the color change of blocks have been creatively developed, and game sound and music modules have been added. This paper provides a specific implementation process, detailed description, and some source code for the above functions.

This paper explains the development and development history of the Tetris game, the significance of developing this game, the development environment, and the relevant knowledge of software development and java programming based on software engineering, as well as the program's requirements analysis, outline design, detailed design and implementation, and debugging A series of descriptions are given for the operation.

    This program design is based on the Microsoft Windows 7 system, using Java as the development language, and the game design and implementation on the Eclipse development platform.

Keywords: game design; Tetris; software engineering; Java; Eclipse.

Table of contents

Design and implementation of Tetris game based on Java ........................ I

Summary................................................. ..................... I

Based on the design and implementation of Java game Tetris.............. II

Abstract.................................................................. II

1 Introduction................................................ ..................... 1

1.1 Background and significance of program development...................................... ..... 1

1.2 Overview of development technology................................................ ......... 2

1.3 Current research status of Tetris game...................................... 2

1.3.1 Current research status at home and abroad........................................ .... 2

1.3.2 Literature review................................................ ........ 3

2Related technologies................................................ .............4

2.1 Introduction to JAVA................................................ ............ 4

2.2 Introduction to Swing components................................................ ....... 4

2.3 Introduction to Eclipse development platform................................................ ... 5

2.4 System platform environment : .................................................. ........ 6

2.4.1 Hardware platform:................................................ ....... 6

2.4.2 Software platform:................................................ ....... 6

3 System analysis................................................ ........................ 7

3.1 Feasibility analysis................................................ ........... 7

3.1.1 Economic feasibility analysis................................ .... 8

3.1.2 Technical feasibility analysis................................................ .... 8

3.1.3 Social feasibility analysis................................................ .... 8

3.2 Requirements analysis................................................ ............ 8

3.2.1 Functional requirements........................................ ....... 9

3.2.2 Non-functional requirements........................................ ...... 9

3.2.3 Interface control................................................ ....... 9

4 Outline design of the system...................................... ............ 11

4.1 Functional design of the system................................................ ...... 11

4.1.1 Basic process of manual business processing...................................... 11

4.1.2 Functional modules of basic process...................................... 12

5 Detailed design and implementation of the system........................................ ....... 15

5.1 Game main interface display module...................................... ... 15

5.2 Canvas and box display module................................ ... 16

5.2.1 Background canvas module design................................................ 16

5.2.2 Preview block module design................................................ 19

5.2.3 Design of block movement and rotation module...................................... 21

5.3 Control Panel Module................................................ ........ 25

5.3.1 Menu bar module design................................................ .. 25

5.3.2 Control panel button design................................................ 26

6 System test operation........................................ ............29

6.1 Test Overview................................................ ........ 29

6.1.1 Testing principles................................................ ...... 29

6.1.2 Test method................................................ ...... 30

6.1.3 Test significance and precautions........................ 31

6.2 Testing of game codes and algorithms........................................ ... 31

6.3 Functional testing of menu options in the game interface............................. 32

6.4 Functional test of key events........................................ .... 34

6.5 Block stacking and elimination function test...................................... 35

6.6 Test results................................................ ........... 35

in conclusion................................................. ............. 36

references................................................ .................. 38

Acknowledgments........................................................ ......................... 39

Appendix A Original foreign text........................................ .............40

The psychology of Tetris.............................................. 40

Appendix B Foreign Language Translation........................................ .............43

The psychological effects of Tetris........................................ ..... 43

1 Introduction

    The introduction briefly describes the program development background, development significance, required development technology, and the current research status of the Tetris game at home and abroad.

1.1 Program development background and significance

    The Tetris game is a popular and enduring game all over the world. It is a casual game that can be played on a series of products such as computers, mobile phones, TV game consoles, handheld game consoles, etc. It has created almost It is an unparalleled sensation and countless commercial value for any game. It is an important event in the history of games and software development.

    One day in June 1984, Alex Pajitnov, a mathematician in Moscow, Russia, was suddenly inspired to design this game after playing a jigsaw puzzle at the Moscow Scientific Computer Center where he worked. , at first he was only developing it on Electronica 60 (a computer), and later it was ported to the PC via Vadim Gerasimov, and it was widely spread in the Moscow computer community. Tetris began to become popular and became The best-selling classic casual game in history, it still retains its charm as always. The simple basic game rules of Tetris are on a standard virtual game field for placing small squares. The basic unit is a small square; it is composed of four small squares and 7 different regular graphics (field shape, Z shape, reverse Z shape , 7-shaped, inverted 7-shaped, T-shaped, long bar) There are 28 graphic schemes in total to rotate the block at 90 degrees, 180 degrees, 270 degrees, 360 degrees through the player's operation of the upper key, left and right keys, and the down key. To adjust the position by accelerating the fall, the blocks are formed into one or more complete blocks at the bottom of the screen, and then eliminated to make room for the newly falling blocks. Each time a complete horizontal bar is eliminated, the player's level increases by one level. When the level reaches a certain level As time passes, the falling speed accelerates. Once the blocks that have not been eliminated reach the top of the screen, the game ends.

    With the continuous updating and development of computer technology, Tetris games are constantly introducing various modes, and there are many different versions for everyone to play, because the game itself can be simple or complex, and can well train game players. Its mental reaction ability and logical thinking ability can also bring endless game fun to players, so it is deeply loved by the majority of players. When it comes to developing game software, most people feel that it is out of reach and magical. With the continuous innovation of development methods and tools, it is not out of reach to develop some small games by yourself. The Tetris game has an unparalleled status in the history of games. The game interface is simple and the code is not very complicated. There are also many algorithms and designs for the implementation of the Tetris game on the Internet, and the difficulty is not particularly high.

    Tetris is a simple and puzzle game. With its unique and concise interface and extremely fun playing mode, many game enthusiasts are deeply involved in it and cannot extricate themselves. It is suitable for all ages. In today's fast-paced life, the pressure of study and work on students and working parties is also increasing. Everyone's tasks are becoming increasingly heavy, and there is less and less free time for rest, which makes people more urgently need something simple. A time-saving casual game for everyone to enjoy. There is no doubt that Tetris is a simple puzzle and interesting casual game, and it can be transplanted to a series of portable devices such as computers, mobile phones, tablets, TV game consoles, handheld game consoles, electronic dictionaries, MP4 and other portable devices. This research project is very valuable both in terms of technical development and social significance. It is a bold attempt by me to develop games.

1.2 Overview of Development Technology

Software engineering is a discipline that studies the use of engineering methods to build and maintain effective, practical and high-quality software; design includes programming languages, databases, algorithms, software development tools, system platforms, design patterns and many other aspects; in In modern society, software is used in many typical aspects such as email, embedded systems, human-computer interaction interfaces, office suites, operating systems, editors, databases, games, etc.; at the same time, in various industries in today's society There are computer software applications, including industry, agriculture, banking, aviation, government departments, etc., which can effectively promote economic and social development and improve people's work efficiency and life efficiency.

The Tetris game development code is relatively not particularly complex. This paper is based on the Java programming language and uses Swing components commonly used in the Java language. Swing is a graphical user interface (GUI) toolkit in Java. It is part of the Java basic class. It includes text boxes, separated panes, buttons, tables and other GUI devices. It is written in pure Java. Developers can use a small amount of code to Swing's various flexible and rich functions and modular components can be written to create beautiful and graceful user interfaces. The Java Swing component includes the following commonly used classes: JFrame is a graphic object on the screen, which can perform basic operations such as maximizing, minimizing, and closing. It is the basic idea of ​​Java GUI programming; JPanel can be used for nesting. Components with the same logical functions in the form can be combined and added to the JFrame form. It is a panel container class in Swing. The JLabel object is used to display text, images, or both and can set some of its properties; JTextField is a running component used to edit a single line of text; JButton is a class used to create buttons. In addition, the Swing component in Java also contains many functional classes, which can easily create some beautiful graphical interfaces.

1.3 Research status of Tetris game

1.3.1 Research status at home and abroad

Since the beginning of the 21st century, computers have continued to develop, and the e-sports industry has also continued to enter a rising stage. The development of game software has become more and more popular. Game software, like dramas and movies, is a new type of technology that is becoming more and more popular. Comprehensive art product. Different from general web development and software development, the development of computer game software not only requires designers and developers to master professional programming skills and software engineering methods, but also requires professional knowledge in the game field and professional game development knowledge in order to be effective. Develop and implement the game's vivid interface, sound effects processing, and achieve perfect interaction with players, etc.

The "Tetris" game originally developed by the former Soviet scientist Alex Pajitnov was as an educational software, and then began to be licensed to various game companies. Since then, it has been available on all major platforms. Various versions of the game appeared.

The Game Boy version of Tetris sold 4.24 million units in Japan, making it the most popular game in the history of Game Boy games. During the Gulf War, the game Tetris became one of the most suitable time-killing games for American troops on the front lines.

The basic principles of Tetris are relatively simple for most programmers, and Tetris is mathematical, dynamic, and well-known. It is also often used as a practice subject for game programming.

1.3.2 Literature review

Documents [1] and [2] aim at zero-based explanation, using examples to guide readers to learn in depth, using the explanation mode of basic knowledge → core technology → advanced application → actual project practice to explain various Java technologies and practices in simple and easy-to-understand terms. Skill. From the perspective of beginners, through easy-to-understand language and colorful examples, it introduces in detail all aspects of technology that should be mastered in program development using Java language. Including: familiarity with Eclipse development tools, Java language basics, classes and objects, packaging classes, number processing classes, interfaces, inheritance and polymorphism, advanced features of classes, exception handling, Swing programming, collection classes, I/O input and output, Reflection, enumerated types and generics, multi-threading, network communication, database operations, Swing table components, Swing tree components, other advanced Swing components, advanced layout managers, advanced event handling, AWT drawing and audio playback, etc. These two documents cover "sufficient" Java language and technology, with rich examples and detailed content. For beginners and students with a certain Java foundation, they can quickly improve students' development technology and skills. In the design of this project, the contents related to graphical interface design, user interface components and design, event processing and window construction components, as well as the basic knowledge of Swing and its series of components were all referred to these two documents, which gave me a lot of inspiration. help.

Document [3] mainly explains 2D drawing; game animation production; network program foundation; enhanced game interface; artificial intelligence and 2.5D games; minesweeper, maze, Tetris and other game examples; collision, particle system, 5D three-dimensional coordinates and other drawing algorithms; multiplayer online game production. A series of algorithm formulas are collected so that readers can use them more conveniently. In a step-by-step approach, the game design process is gradually analyzed, leading readers to solve problems that may be encountered in the game development stage, and summarizing practical experience in Java game production. The principles of games, animation implementation, sound effects processing, mouse and keyboard event processing, artificial intelligence and other knowledge in the design of this course all refer to this document.

Literature [4] discusses the program principle and implementation technology of the classic computer game Tetris, and describes the program's functional requirements, data structure, graphics rotation, coordinate transformation and other key technologies from the perspective of software engineering. Through this document, I learned more about the professional field of Tetris game development.

Document [5] is an advanced book that focuses more on explaining how to use Java to think and solve problems. This document gave me a lot of help with Java programming ideas and techniques during the course design.

2Related technologies

2.1 Introduction to JAVA

    Java is the general name for the Java object-oriented programming language and Java platform launched by Sun Microsystems. It is an object-oriented programming language that can write cross-platform application software . Java technology has good versatility, efficiency, cross-platform and security. It is widely used in PCs, data centers, game consoles, scientific supercomputers, mobile phones and the Internet. It also has the world's largest professional community of developers.

Over the past twenty years, the Java language has developed into one of the most influential programming languages ​​in the history of human computers. To some extent, it has even exceeded the scope of a programming language and has become a development platform and a development platform. Canonical mode. Even more: Java has become a kind of belief. The open source, freedom, and other spirits advocated by the Java language have attracted countless outstanding programmers around the world. In fact, since the recorded history of mankind, there has never been a programming language that can attract so many outstanding programmers to use, and no programming language can derive so many open source frameworks.

The Java language is a very pure object-oriented programming language. It attracts the various advantages of the C language and the C++ language, and abandons the difficult-to-understand concepts such as multiple inheritance and pointers in the C++ language. Therefore, the Java language is powerful and Simplicity and ease of use are two very good features. As a representative of static object-oriented programming languages, the Java language excellently embodies object-oriented theory and allows programmers to conduct more complex programming development in a more elegant way of thinking.

Not only that, the relevant Java EE specifications in the Java language contain the most popular software engineering concepts today, and various advanced design ideas can be implemented in the Java EE specifications, platforms and related frameworks. principle. To a certain extent, learning to be proficient in various aspects of Java language-related knowledge is equivalent to systematically learning relevant knowledge of software development, rather than just learning a programming language.

Today, most banking, telecommunications, securities, e-commerce, e-government and other systems have either been built using the Java EE platform, or are gradually transitioning to the Java EE platform. The Java EE specification is currently the most mature. It is also the most widely used enterprise-level application development specification.

2.2 Introduction to Swing components

    Swing API is an extensible set of GUI components for creating JAVA-based front-end/GUI applications. It is built on top of the AWT API and serves as a replacement for the AWT API because almost every control in it corresponds to an AWT control. Swing components follow the model-view-controller architecture to meet the following guidelines. A single API is enough to support multiple looks and styles; the API is mock-driven, so that the highest-level API does not need to have data; the API uses the Java Bean pattern, so that Builder Tools and IDEs can provide better services to developers to use it.

    The Swing API architecture follows a loosely based MVC architecture in the following manner. The model represents the component's data. A view represents a visual representation of a component's data. The controller accepts user input on the view and reflects the changes on the component's data. Swing components treat the model as a separate element and combine view and controller parts into user interface elements. Using this approach, Swing has a pluggable look and feel architecture. The main features of Swing are:

    Lightweight - Swing components are independent of the native operating system API, because Swing API controls are usually rendered using pure JAVA code rather than using underlying operating system calls.

    Rich controls - Swing provides a rich set of advanced controls, such as trees, tab forms, sliders, color pickers, and table controls.

    Advanced Customization - Swing controls can be customized in a very simple way because the visual appearance is independent of the internal representation.

    Pluggable look and feel - The look and feel of a Swing-based GUI application can be changed at runtime based on valid values.

2.3 Introduction to Eclipse development platform

Eclipse is an open source, Java-based extensible development platform that focuses on providing a full-featured, commercial-quality industrial platform for highly integrated tool development. Eclipse is just a framework and a set of services for building development environments through plug-in components. Eclipse comes with a standard set of plug-ins, including Java Development Tools (JDT).
  Eclipse started in April 1999. It was originally developed by IBM as a next-generation IDE development environment to replace the commercial software Visual Age for Java. IBM provided the initial Eclipse code base, including Platform, JDT and PDE, in November 2001. Contributed to the open source community, currently led by IBM, the Eclipse project has developed into a huge Eclipse alliance, with more than 150 software companies participating in the Eclipse project, including Borland, Rational Software, Red Hat and Sybase, etc., and is now led by Governed by the Eclipse Foundation, a non-profit alliance of software vendors. In 2003, Eclipse 3.0 selected the OSGi service platform specification as the runtime architecture. In June 2007, stable version 3.3 was released. Version 3.4, codenamed Ganymede, was released in June 2008.
  Eclipse is a well-known cross-platform free integrated development environment (IDE). It was originally mainly used for Java language development, but currently some people use plug-ins to use it as a development tool for other computer languages ​​such as C++ and Python. Eclipse was originally just a framework platform, providing a plug-in development environment (Plug-in Development Environment, PDE). This component is mainly aimed at software developers who want to extend Eclipse, allowing the construction of tools that are seamlessly integrated with the Eclipse environment. The support of many plug-ins makes Eclipse It has flexibility that other IDE software with relatively fixed functions is difficult to have. Since everything in Eclipse is a plug-in, providing plug-ins for Eclipse provides users with a consistent and unified integrated development environment, so that all tool developers have an equal place to play.

Advantages of Eclipse:

Currently, millions of people around the world are using Eclipse for development. Why does Eclipse have so many fans? This has a lot to do with Eclipse integrating many features into one.

    Eclipse is open source software. This means that not only is Eclipse free to use, you can learn the programming techniques of the world's top developers by studying source code, and you can share public open source code libraries contributed by developers around the world.

    Eclipse is truly extensible and configurable. Eclipse uses a plug-in mechanism, which is like a vase. You can add flowers to the vase at any time, and you can also easily take out flowers that are no longer needed. At present, free and paid plug-ins are blooming all over the Internet, and plug-in development work is also in full swing at home and abroad.

Eclipse supports many development languages ​​not just Java. Eclipse only provides developers with a minimal core that can extend system functions. The plug-in architecture based on extension points makes it possible for Eclipse to support multiple languages. As long as the plug-in for the corresponding language is installed, Eclipse can support the development of that language. Currently, Eclipse can support C/C++, COBOL, PHP, Perl, Python and other languages. (Although Eclipse is primarily a Java development environment, its architecture ensures support for other programming languages).

   Eclipse provides support for multiple platform features. Developers can use the platform they feel most comfortable and familiar with, such as Windows, Linux, MacOS, etc. Eclipse has its own separate graphics toolkit for each platform, which gives applications a near-native operating system look and better performance.

 Based on the industry-leading OSGi specification. The OSGi specification was first launched by Sun Microsystems, IBM, Ericsson, etc. in 1999. Its service platforms include: service gateways, automobiles, mobile phones, industrial automation, building automation, PDA grid computing, entertainment (such as iPronto) and IDE, etc. OSGi-based systems run in the form of microkernels, so they can easily realize hot-swappable, dynamically changing behavior, stable and efficient systems that the software industry dreams of. Starting from 3.1, Eclipse has resolutely abandoned its original framework that has been recognized by the industry and adopted OSGi as its architecture. Starting from Eclipse3.2, Eclipse provides support for OSGi-based development, and developers can use it to develop OSGi-based systems.

   Eclipse's beautiful human-machine interface has been widely praised. Eclipse provides a new SWT/JFace API (instead of AWT/Swing), which changes the monotonous and boring interface style of SWT/Swing, making it possible to develop local-based applications with rich graphical interfaces, just like a spring breeze blowing in The field of Java desktop development gives people a refreshing feeling.

   Eclipse is launched by industry leaders and has strong industry power. The Eclipse Foundation has absorbed a large number of academic research institutions and commercial organizations to lead the long-term planning and development of Eclipse and ensure that Eclipse is in the leading position in the software tool industry.

2.4 System platform environment :

2.4.1 Hardware platform:

   The computer hardware developed by this program is as follows:

Memory: 4G

Hard drive: 500G

CPU:Intel(R)Core(TM)i5—3230M CPU  @2.60GHz

Interactive tools: keyboard, mouse

Display: LCD display

2.4.2 Software platform:

The development environment of this system is as follows   

Operating System: Microsoft Windows 7 Ultumate

JDK version: jdk-8u121-windows-x64

Eclipse version: Neon.2 Release (4.6.2), eclipse-inst-win64

System analysis

System analysis is the first step we take in the software development process, including system requirements analysis and feasibility analysis. System requirements analysis is mainly used to explain what the system is and what it must be used for, and to reach a consensus between developers and major users on this issue. Feasibility analysis of the system is mainly to analyze the implementation of all resources of the system to explain the rationality, feasibility and inevitability of the system's development and investment, and to rationalize unforeseen problems that may arise. analysis. The most challenging link in software development is the system demand analysis. The time spent on demand analysis is undoubtedly very valuable. If demand changes occur frequently, it will bring problems to the software development tasks completed within the scheduled plan. Very serious adverse effects. Doing a good job of system requirements analysis and feasibility analysis will help improve the convenience of the software development process, enable real-time monitoring and management of the software development process, and make it easier to proceed as planned, thereby achieving the purpose of improving the quality of the software. Provide more portable communication and cooperation for program developers, users, etc. As the original basis for work results, system demand analysis and feasibility analysis can also indirectly express the functions of the system to potential users, allowing users to judge whether the functions of the system meet the needs to be achieved.

3.1 Feasibility analysis

Feasibility analysis is based on the main content and supporting conditions of the project in terms of technology, economy, engineering, technology, etc., such as market demand, resource supply, construction scale, process route, equipment selection, environmental impact, fund raising, profitability, etc. Research, analysis and comparison of other aspects, prediction of the financial, economic and social environmental impacts that may be achieved after the project is completed, whether the project is worth investing in, and how to consult and construct project decisions, provide the basis for a comprehensive system analysis method. Feasibility analysis should be far-sighted, fair, reliable and scientific.

In order to ensure the scientificity, objectivity and impartiality of the feasibility study work and effectively prevent errors and omissions, in the feasibility study, we must first conduct investigation and research from an objective and impartial standpoint and do a good job in collecting basic data. The collected basic data must be demonstrated and evaluated based on objective actual conditions, truthfully reflecting objective economic laws, and starting from objective data and through scientific analysis to draw a conclusion on whether the project is feasible.

The content depth of the feasibility study report must meet the standards stipulated by the state, the basic content must be complete, and as much data as possible should be used to avoid shoddy work and formalism.

The following key points must be mastered in practice: Demonstrate first, then make decisions; properly handle the relationship between the three stages of project proposal, feasibility study, and evaluation. Research should be stopped at any stage when it is found to be unfeasible; investigation and research must be carried out Follow through. It is necessary to master practical and reliable information to ensure the comprehensiveness, importance, objectivity and continuity of data selection; compare multiple options and choose the best. For foreign-related projects, or projects that must be in line with foreign standards under the pressure of external factors such as joining the WTO, the content and depth of the feasibility study should be as consistent as possible with international standards.

In order to ensure the quality of the feasibility study, a sufficient work cycle of the consulting design unit should be ensured to prevent irresponsible and hasty behavior due to various reasons.

The purpose of the feasibility analysis is to determine whether the problem can be solved in the shortest time and at the lowest cost. The main point of feasibility analysis is not to solve problems, but to study whether these problems are worth spending human and financial resources to study and solve. If there is a simple and easy way then yes.

3.1.1 Economic feasibility analysis

    The purpose of the economic feasibility analysis of the system is to calculate the capital investment required from development and construction to system operation, as well as the market demand and economic benefits of the new system, compare the investment budget with the expected benefits, and calculate the economic costs. feasibility.

This game system is mainly used for the design of software engineering graduation courses for college students, and there is no need to consider the economic benefits it can generate and the future development status of the game. The economic requirements for the game system itself are not high, but students' own knowledge and ability levels are improved through the development of this game system. All you need is a computer equipped with the JDK operating environment and the Java development tool Eclipse software, so there is no need to consider economic issues.

3.1.2 Technical feasibility analysis

There are many programming languages ​​that can be used to write Tetris games. This topic is mainly to develop the game system in a Java-based environment. Therefore, this system mainly uses Swing components in Java for development, and requires variable definition and initialization. , interface design, game initialization, entering the game, exiting the game, handling various operations during the game and performing code requirements for corresponding functions. The technical requirements are not particularly difficult and technically feasible.

3.1.3 Social feasibility analysis

The development of this game system is mainly used for graduation course design and thesis, to consolidate the knowledge of four years of university study. It is mainly for individuals and schools. It is only for personal entertainment and school course design and graduation thesis checking into files. It is not It will have no impact on society, so there is no need to consider any legal, copyright and other social factors. It is completely feasible in this regard.

3.2 Requirements analysis

    The so-called "needs analysis" refers to a detailed analysis of the problem to be solved, clarifying the requirements of the problem, including what data needs to be input, what results are obtained, and what should be output in the end. It can be said that "needs analysis" in software engineering is to determine what the computer "does" and what effect it achieves. It can be said that the requirements analysis is completed before the system is completed.

    In software engineering, requirements analysis refers to all the work required to describe the purpose, scope, definition, and functionality of the new system when creating a new or changing an existing computer system. Requirements analysis is a key process in software engineering. During this process, systems analysts and software engineers determine the customer's needs. Only after these needs are identified can solutions for the new system be analyzed and pursued. The task of the requirements analysis phase is to determine the functionality of the software system.

    In the history of software engineering, people have always believed that requirements analysis is the simplest step in software engineering. But over the past decade, there has been a growing realization that needs analysis is the most important process. If the analyst cannot correctly understand the customer's needs during demand analysis, the final software will not truly meet the customer's needs, or the software project will not be completed within the specified time.

3.2.1 Functional requirements

    The entire game system will randomly generate 7 different shapes of blocks composed of four small blocks. After rotation, 28 states will be obtained. If the game difficulty is increased, six different shapes of blocks will be added. After rotation, 24 types will be added. state. The blocks fall freely at a certain speed. The player controls the left and right movement and rotation of the blocks through the up, down, left and right keys on the keyboard, and places the blocks in the appropriate position after falling. When the block falls, if a whole row is filled with blocks after the block falls, then the whole row will be eliminated. When a row is eliminated, the player's score increases by 10 points. When the score reaches 100 points, the player's level increases by one level, the speed increases by one level, and the difficulty increases. If the entire game canvas interface is occupied after the block falls, the block will no longer fall and the game will fail. The specific functional requirements of the game are as follows:

    ▪ Game interface requirements: A good interface of the game will make players' eyes shine, and they can fully feel the entertainment and relaxation brought by the game. The default background color of this game is dark green. The game's main interface screen can be customized to your favorite picture and can be changed. The default color of the main interface squares is orange, and the default color of the pre-display squares is lavender. The background color and foreground color are in sharp contrast to make the player's eyes brighter. When the game reaches a high level and the falling speed of the blocks increases, the players can clearly distinguish the shape of the falling blocks, which increases the ambience of the game. Irritating.

    ▪ Game shape requirements: Use an array as a data structure to store 52 states of the block, namely, a total of 7 shapes including primary-level long bar, Z-shape, reverse Z-shape, field-shape, 7-shape, reverse 7-shape, and T-shape. Rotation deformation in 4 directions, three blocks in the intermediate level and 12 different states, and three blocks in the advanced level with 12 different states. Each block can rotate counterclockwise, and whether the block can rotate needs to be judged by conditions. If the block may cross the boundary after rotation, it cannot rotate, and the position needs to be adjusted to ensure that it can rotate.

    ▪ Keyboard processing event requirements: When the block falls, the player can use the direction keys on the keyboard: the up key to rotate, the down key to accelerate the fall, the left key to move left, the right key to move right, and the space bar to realize one-click falling. The letter P key implements pause, and the letter C key implements a series of operations such as continue.

    ▪ Mouse processing event requirements: With the mouse, you can click the menu button and help button in the control panel, select menu items in the menu bar, start the game, select the game level, change the color display of the blocks in the game, and the background of the main game interface Display color and foreground color, change the game background image, block falling speed, whether to play in-game sounds and a series of functions.

▪ Display requirements: The display requirements of this game program are that when the blocks fall and fill a whole row, the row will be eliminated, and the remaining unfilled rows will automatically move downwards one by one. Eliminating a row will increase the score on the right interface by ten points. When the score increases to 100 points, the level increases by one level. When the block falls and is superimposed on all the rows of the main interface, the block no longer falls, the game ends, and the main interface prompts the word "Game Over".

3.2.2 Non-functional requirements

Non-functional requirements: The non-functional requirements of the Tetris game system include the icon display in the upper left corner of the game's main interface, adjusting the window size to maximize and minimize (but not including the size of the main interface), and the position of the pop-up window when the game is running. A set of non-functional requirements.

3.2.3  Interface control

Under the Windows operating system, this Russian game system mainly operates the game through the keyboard.

You can use the mouse to perform a series of operations such as start, exit, and settings. First of all, the game uses keyboard keys to operate the game, so it needs to use keyboard interface events. Secondly, during the whole process of the game, you need to use the mouse to control the game, including starting, selecting levels, changing settings, changing colors, viewing version information, exiting, etc., so you need to add an interface to monitor events for mouse clicks and buttons. , write the corresponding code to implement the corresponding functions of the mouse and keyboard.

System Outline Design

4.1  Functional design of the system

4.1.1  Basic process of manual business processing

    This game is designed with entertainment as its original intention and puzzle as its purpose. It is based on a comprehensive study of the functions of previous classic Tetris games and introduces new ones, adding new functions to give it new vitality and vitality. The basic process of the game is explained in detail below.

   Operating instructions:

   1>Run the program and click "Start" in the control panel on the right or the "Start" button in the "Control" menu to start the game.

   2>Use the up, down, left, right keys and the space bar, P key, and C key to control the deformation, fall, left and right movement of the block and rapid fall, pause, and continue with one click.

   3> Eliminate a full row of blocks, the score will automatically increase, and the level will automatically increase by one level.

   4>As the level increases and the falling speed of the blocks increases, press the "Elementary", "Intermediate" and "Advanced" buttons on the right control panel or in the "Game" menu to manually change the difficulty of the game. You can also click the options in the "Block Color" menu to change the color of the blocks, etc. You can also change some attributes of the game through the options in the "Customize" menu.

   5> Press the P key on the keyboard to pause the game, and then press the C key to continue the game. Pressing the "End Game" button will completely stop the ongoing game, and pressing "Start" or "Restart" in the "Control" menu will start a new game.

   6>When the blocks occupy the entire window and no new blocks can fall, the game will pop up a "Game Over" dialog box to prompt the game to end.

The basic flow chart of the game is shown in Figure 4-1:

                        Figure 4-1 Basic flow chart of the game

4.1.2  Function modules of basic process

This system designs each functional module of the game based on the various functions of the game. Figure 4-2 is a schematic diagram of the system function modules of this game. As shown in the figure, this game mainly has two modules: the game interface area and the game control area. The game interface is divided into two parts: displaying the player's optional operations and displaying the results of the player's operations. The game control is divided into some functional modules such as changing color, starting, changing the game level to elementary, changing the game level to intermediate, changing the game level to advanced, customizing falling speed, changing background, exit and others.

Figure 4-2 Schematic diagram of system function modules

    Figure 4-3 is a schematic diagram of the game interface area module design. As shown in the figure, the game interface area module can be subdivided into three functional modules: entering the new game interface, processing player operations, and displaying player operation results.

Figure 4-3 Schematic diagram of interface module

    Figure 3-4 is a schematic diagram of the game control area design. As shown in the figure, the game control area module is divided into functional modules such as start, customized operation settings, initial game level settings, initial color settings, and exit.

Figure 4-4 Schematic diagram of control area module

5Detailed  design and implementation of the system

    Java is a purely object-oriented (Object-Oriented) programming language, and its many advantages will not be discussed in detail here. Starting from the object-oriented concept, this program can be mainly divided into the following modules:

    ●Game main interface display module

    ●Block and data display module

    ●Block movement control module

    ●Game interface color control module

    ●Game progress and level control module

    The skill of analyzing an object lies in its functional scalability and maintenance efficiency. Just imagine, if the function of the program needs to be expanded or maintained due to changes in the external environment or user needs, the code will have to be significantly changed or even rewritten. In this way, the object-oriented advantage will be lost, so when analyzing this program, A highly independent module is used as an object to improve the scalability and maintainability of the program. The following is the design of the classes in the game:

    MyFrame class: Inherited from the JFrame class, as the main class of the game, it is responsible for controlling the main body of the game and connecting and commanding the hub of each class.

    PreView class: Inherited from the JPanel class, as an operation panel class, it is responsible for placing the main game window, scoreboard, level control buttons and other windows to control the game process.

    GameCanvas class: Inherited from the JPanel class, the ChangeBlockColor thread class dynamically changes the square color of the canvas class. The canvas class reflects the movement and elimination of the ChangeBlockColor square by checking the square color.

    Box class: Square class, the basic elements that make up the box. The main expression is color.

    Block class: As a class for manipulating blocks, it controls the movement, fall and deformation of blocks.

5.1  Game main interface display module

    An excellent software system is not only reflected in the diversity and power of the core functions. If the user is faced with a boring and old interface, then the software system will be unsuccessful. Therefore, a good and exquisite software system will not be successful. Interface design is an extremely important link. The importance of designing and producing an interface with reasonable layout and good visual effects for players is self-evident.

The main interface of the game is developed using Swing components, and listeners are registered with it to implement various control functions. Based on the design of the game form, at least three listeners need to be registered on it, namely action listener (ActionListener) and keyboard listener. listener (KeyListener), option listener (ItemListener).

    According to the preliminary design, it can be determined that the Swing component objects to be used on the client include JFrame objects, JPanel objects, JLabel objects, JButton objects, JMenuBar objects, JMenu objects, JMenuItem objects, JTextField objects, JTextArea objects, JDialog objects, etc., at least ten Swing component object. Figure 5-1 below is a screenshot of the game’s main interface.

Figure 5-1 Screenshot of the game’s main interface

The initial color matching of the main interface design of this game is based on the principle of sharp contrast. The default background color is dark green. The Tetris icon is set in the upper left corner. The initial value of the score is 0, the initial value of the level is 1, and the initial value of the highest score record is 0. The size of the main game form is set to (520, 580), the block movement range pane is controlled by a two-dimensional array with 20 rows and 12 columns, and the icon in the upper left corner is set to a block pattern for identification purposes.

5.2  Canvas and box display module

In this game, the canvas is designed as a custom picture. You can change the background picture yourself according to your own needs. During the falling process of the blocks, the falling blocks are identified according to the changes in color.

5.2.1  Background canvas module design

The main background canvas of the game is a two-dimensional array with 20 rows and 12 columns. The square display is identified by corresponding color changes. The main form is filled with color to form the background style and squares. This game uses the GameCanvas class inherited from JPanel to control the display of the background canvas. Rows represents the number of rows of the canvas, and cols represents the number of columns of the canvas. The number of rows and columns determine the number of squares the canvas has. The main implementation code of the background canvas is as follows:

First, use a constructor of the canvas class to represent the number of rows, columns and main border of the entire main interface.

Relative position in:

       /**

        * Constructor of canvas class

        * @param rows int, the number of rows in the canvas

        * @param cols int, the number of columns of the canvas

        * The number of rows and columns determines the number of squares the canvas has

        */

       public GameCanvas(int rows, int cols) {

              this.rows = rows;

              this.cols = cols;

              this.setOpaque(false);

              boxes = new Box[rows][cols];

              for (int i = 0; i < boxes.length; i++) {

                     for (int j = 0; j < boxes[i].length; j++) {

                            boxes[i][j] = new Box(false);

                     }

              }

              setBounds(0, 0, 300, 500);//Set relative position coordinates

              setBorder(new EtchedBorder(

                      EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)));

       }

       /**

        * Get the number of rows of squares in the canvas

        * @return int, the number of rows in the grid

        */

       public int getRows() {

              return rows;

       }

       /**

        * Get the number of columns in the canvas

        * @return int, the number of columns in the grid

        */

       public int getCols() {

              return cols;

       }

    Secondly, set a constructor of the canvas class to represent the foreground color and background color of the entire main interface and obtain its foreground and background colors:

       /**

        * Constructor of canvas class

        * @param rows is the same as public GameCanvas(int rows, int cols)

        * @param cols is the same as public GameCanvas(int rows, int cols)

        * @param backColor Color, background color

        * @param frontColor Color, foreground color

        */

       public GameCanvas(int rows, int cols,

                         Color backColor, Color frontColor) {

              this(rows, cols);

              this.backColor = backColor;

              this.frontColor = frontColor;

       }

       /**

        * Set game background color

       * @param backColor Color, background color

        */

       public void setBackgroundColor(Color backColor) {

              this.backColor = backColor;

       }

       /**

        * Get the game background color

       * @return Color, background color

        */

       public Color getBackgroundColor() {

              return backColor;

       }

5.2.2  Preview block module design

Blocks and data information are the most basic functional modules in the game. Box, a grid-like class, is the basic element that makes up a block. It uses its own color to represent the appearance of the block. MyTask inherits the TimerTask class to time the whereabouts and uses counting methods to achieve speed changes. The MyListener class inherits the KeyAdapter class to implement Button monitoring, control the up, down, left and right of the block. Define a 4x4 square matrix with a total of 16 cells. Use "0" and "1" to indicate whether each square is painted with a new color or retains the background color.

Each time a new block is obtained, one of the seven forms of blocks is randomly selected. The game defines a variable that represents the model of the new block. For example, define an int array STYLE to represent 28 types of blocks, with 7 rows and 4 columns, and each element represents one of the blocks. That is, 0<=blockkindnum<=6, 0=<blockstatusnum<=3

Then, when the block falls and you need to get a new block, you only need to randomly obtain a pair of blockkindnum and blockstatusnum values, and then construct the corresponding block based on the value of this STYLE. The remaining question is how to randomly generate a pair of STYLE row and column values.

The Math class in the Java language package provides a method random() for generating random numbers. Calling this method will generate a double-precision floating point number between 0-1. So every time you want to get a new block, you only need to call this method once to get a double-precision floating point number from 0 to 1, then multiply the number by 7, and then cast it to an integer to get an integer from 1 to 7. , used to control rows. Multiply this number by 4, and then cast it to an integer to get an integer from 1 to 4, which is used to control the column.

From this, multiple graphics definitions can be combined and the following functions can be implemented using code:

1> Each execution first generates a different initial value for the random number.

                  int col = (int) (Math.random() * (gc.getCols() - 3));//Generate columns at random positions

                     int style = Constant.STYLES[(int) (Math.random() * Block.get_addl())][(int) (Math.random() * 4)];

Figure 5-2 Flowchart of randomly generating blocks

    2> Randomly select a figure, Figure 5-2 randomly generates a block diagram to specifically describe the generated random CNC

The resulting graphics.

3>The position information of the current graphic in its 4*4 grid.

    Draw a pre-display grid of 4 rows and 4 columns of blocks, and randomly generate a pre-display block style. This game uses a two-dimensional array to store 28 styles of blocks.

It is worth noting that: on the basis of the traditional Tetris game, in order to reflect innovative thinking and in line with the principle of learning, this game system adds three other block styles at the intermediate level and three advanced levels on the basis of the traditional game. other block styles. There are 52 block styles in total. The main implementation code for the specific storage method is as follows:

       /**

        * Corresponds to 52 states of 13 models respectively

        */

       public final static int[][] STYLES = {// 28 states in total

              {0xf000, 0x8888, 0xf000, 0x8888}, // Four states of long bar

              {0x4e00, 0x4640, 0xe400, 0x4c40}, // Four states of 'T' type

              {0x4620, 0x6c00, 0x4620, 0x6c00}, // Four states of reverse 'Z' shape

              {0x2640, 0xc600, 0x2640, 0xc600}, // Four states of 'Z' type

              {0x6220, 0x1700, 0x2230, 0x7400}, // Four states of '7' type

              {0x6440, 0xe200, 0x44c0, 0x8e00}, // Four states of the reverse '7' type

              {0x6600, 0x6600, 0x6600, 0x6600}, // Four states of the block

              {0x8c88,0xf200,0x44c4,0x4f00},//Added 3 intermediate style blocks

              {0xea00,0xc4c0,0xae00,0xc8c0},

              {0x8c00,0xc800,0xc400,0x4c00},

              {0xac00,0xcc40,0x6e00,0x8cc0},//Added 3 advanced style blocks

              {0x4e40,0x4e40,0x4e40,0x4e40},

              {0x8480,0xa400,0x4840,0x4a00},

       };

   I believe many people know the 7 block styles of the traditional Tetris game, so I won’t take screenshots to show the common block styles one by one. The following are three block models of intermediate difficulty and three advanced difficulty added to the traditional game mode:

    ●Added three intermediate difficulty block models (four rotation states can be obtained after 90 degrees, 180 degrees, 270 degrees, and 360 degrees)

Figure 5-10 Three additional intermediate difficulty block models

    ●Added three advanced difficulty block models (four rotation states can be obtained after 90 degrees, 180 degrees, 270 degrees, and 360 degrees)

Figure 5-11 Three additional advanced difficulty block models

5.2.3  Block movement and rotation module design

The flipping and moving of blocks is relatively easy to implement. To move a block, you only need to change the abscissa or ordinate of the block, and then redraw the block. To flip the block, you only need to change the value of the background array and redraw the block.

When the blocks in this game fall, dynamic drawing is performed and the Cloneable interface is implemented to indicate that the Object.clone() method can legally copy the instance of this class by fields. The block operation class BlockOperation inherits the Thread class and overrides the run() method to realize the dynamic and correct whereabouts of the block. Of course, it is necessary to determine whether the block is in the moving state or the pausing state in the thread.

publicvoid run()

       {

              //moving determines whether the block is falling dynamically

              while (moving)

              {

                     try

                     {

                            //betweenleveltime indicates the time difference between adjacent levels

                            sleep(betweenleveltime

                                    * (ControlMainGame.maxlevel - level + flatgene));

                     } catch (InterruptedException ie)

                     {

                            ie.printStackTrace();

                     }

                     //pausing determines whether the game is paused

                     if (!pausing)

                            moving = (moveTo(y + 1, x) && moving);

                     //moving is waiting for 100 milliseconds, and moving has not been changed.

             }}

Of course, in the game, we also need to determine the boundary problem of block movement. For example, a block has exactly one grid of space on its left before it can be flipped, but there is exactly one grid of space on its right. In this case, if the block cannot be flipped Flip is inconvenient for users to operate. If it can be flipped, it will cross the boundary and occupy the existing blocks. If you want to flip the block without going out of bounds, you should move the block one square to the right after flipping it, and then draw the block again. In this way, the block will not crowd out other fixed blocks. The following solves the out-of-bounds problem. .

1>Block flip judgment

Cross-border may occur in two situations, one is when the block falls and is fixed, and the second is when the surrounding space does not allow it to flip.

In the first case, you only need to refer to the judgment that the block cannot move after it falls.

For the second case, before each block is flipped, the space around the block must first be calculated and flipped if space allows. Otherwise, it cannot be flipped.

Because the seven kinds of squares are irregular, the flipping space required for each kind of square is different. Even in its different flipping states, the flipping space required is also different. The first thing that comes to mind is naturally to provide each square with different flipping spaces. kind of blocks, and write a judgment condition for each state of the block, but this would be too troublesome.

According to observation, it is not difficult to find that among the seven shapes of blocks, if a long block falls in the form of a horizontal bar, it can be flipped as long as it can fall. If it falls in the form of a vertical bar, then it will be in the position after flipping. The position must have 4x1 grid space before it can be flipped. For the Tian-shaped square, as long as it can continue to fall, it will definitely be able to flip, so as long as the Tian-shaped square does not fall, it will always be able to flip. The other five shapes of blocks have one thing in common, that is, they all have two flipped states that occupy three grids of space horizontally and two spaces vertically. The other two flipped states occupy two grids of space horizontally. , occupying three grid spaces in the vertical direction. If they fall in a state of occupying three grids in the horizontal direction, then as long as they can fall, they will be able to flip. If they fall in the state of two grids in the horizontal direction, then after flipping, the surrounding There must be 3x2 grid space.

Therefore, the determination of the flipping of a block must be divided into three situations. The first situation is that the block cannot be flipped after falling; the second situation is that the long block that appears in the vertical state is flipped; the third situation is In addition to long strips and field-shaped squares, the other five squares that appear in a state of occupying two grids in the horizontal direction are judged for flipping.

Now that the problem of under what circumstances the block can be flipped has been solved, next, we should solve the problem of the position of the block after it is flipped, because only by knowing the position of the block after it is flipped in advance can we determine the spatial range of that position. Make a determination to see if it can accommodate the block.

What is certain is that no matter how the block is flipped, it is still in the block array, which means that the block must be within a certain 4x4 grid space in the game map.

The coordinates of the block array in the main interface of the game are determined. What is uncertain is where the block will be in the block array after flipping. In order to solve this problem, we can limit the storage principle of the block in the block array to the left or the left. In this way, no matter how you flip it, there will always be blocks in the first row and column of the block array. This also determines the position of the block in the block array, and you can also know how the block will appear on the game map after being flipped. location.

Assume that the horizontal and vertical coordinates of the block array are x and y, then this position is that the row where the long block is flipped is the yth row of the game map, and the columns it occupies are the xth to x+3 columns , the rows occupied by the five types of squares other than the long strip and the field shape after flipping are the yth and y+1th rows of the game map, and the columns they occupy are the xth to x+2 columns.

Therefore, if there are empty cells in the above space, the blocks can be flipped.

2>Flip out of bounds correction

A block can be flipped as long as there is enough space on it after flipping over, but what if the space after the block is flipped is not enough, but there is enough space on the other side?

When the block is at the boundary, it may not only fall out of the map after flipping, but also the array may go out of bounds. Of course, you only need to define the map array larger to avoid array out-of-bounds errors. For the block out of bounds, if it is on the other side of it If there is enough space, then the block should be moved to the other direction by the appropriate unit to correct the block out-of-bounds error. As shown in the block flipping flow chart in Figure 5-12, the flipping of a block requires three determinations: whether it has fallen to the bottom, whether there is enough space after flipping, and whether it has crossed the boundary after flipping.

Figure 5-12 Block flip processing flow chart

The player operates the keyboard to move and rotate the blocks. The code introduces the ControlKeyListener class and inherits the KeyAdapter class to implement the keyboard monitoring function. The KeyAdapter class inherits from the Object class and implements the KeyListener interface, an abstract adapter class used to receive keyboard events. Methods in this class are empty. This class exists to facilitate the creation of listener objects. Extend this class to create a KeyEvent listener and override the method of the required event, which is the ControlKeyListener class. Use ControlKeyListener to create a listener object, and then register the listener object with the component using the component's addKeyListener method. When a key is pressed, released, or typed, the corresponding method in the listener object is called and the KeyEvent is passed to the appropriate method. The implementation code is as follows:

       privateclass ControlKeyListener extends KeyAdapter

       {

              publicvoid keyPressed(KeyEvent ke)

              {

                     if (!game.isPlaying())

                            return;

                     BlockOperation blockope = game.getCurBlock();

                     switch (ke.getKeyCode())

                     {

                            case KeyEvent.VK_DOWN:

                                   blockope.moveDown();

                                   break;

                            case KeyEvent.VK_LEFT:

                                   blockope.moveLeft();

                                   break;

                            case KeyEvent.VK_RIGHT:

                                   blockope.moveRight();

                                   break;

                            case KeyEvent.VK_UP:

                                   blockope.turnNext();

                                   break;

                            default:

                                   break;}}}

5.3Control  Panel Module

5.3.1  Menu bar module design

     There are four menu options "Game" and "Help" in the menu bar. The "Game" option is divided into seven options: "Start", "Beginner", "Intermediate", "Advanced", "Customize", "Block Color", and "Exit". There is an "About" option in the "Help" option, which is used to display information such as game version.

    1>The "Start" button function is to redraw the game canvas, similar to the reset function. The monitoring implementation code of this button is as follows:

       /**

        * Reset canvas

        */

       public void reset() {

              for (int i = 0; i < boxes.length; i++) {

                     for (int j = 0; j < boxes[i].length; j++)

                            boxes[i][j].setColor(false);

              }

              repaint();

       }

    2>The "Elementary", "Intermediate" and "Advanced" buttons are used to manually adjust the level of the game, thereby changing the level difficulty of the game. The "Exit" button controls the game to exit at any time and terminate the game.

3>Click the "About" button in the "Help" button to display information related to the game software itself. The specific information is as shown in the figure:

                       Figure 4-19 Screenshot of the “About” option

5.3.2  Control panel button design

The game control panel contains fields such as score statistics and level statistics.

The TextField controls are provided by the statistics of the game itself, and players cannot edit them privately. The game rules of this game are 10 points for each line eliminated, and each additional 100 points increases by one level. The initial score is 0 and the initial level is 1.

The following is the main code for implementing functions such as score and level update:

              /**

               * Determine whether the line is full. If the line is full, call the elimination method.

               */

              private void isFullLine() {

                     // TODO Auto-generated method stub

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

                            int row = 0;

                            boolean flag = true;

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

                                   if (!gc.getBox(i, j).isColorBox()) {

                                          flag = false;

                                          break;

                                   }

                            }

                            if (flag == true) {

                                   row = i;

                                   gc.delete(row);//Delete row

                                   if(isMusic==true)

                                   {mp.playEraseSound();}

                                   addScor();//Add score

                                   if(scor%100==0)//Set to 100 points to increase one level

                                   upspeed=true;//Increase the speed flag to true

                                   if(upspeed==true)

                                          upLevel();

                            }

                     }

              }

              /**

               * How scores are calculated

               */

              private void addScor() {

                     scor=scor+10;

                     jt9.setText("Score: "+MyFrame.scor);

              }

       }

       private void reset() {

              scor=0;

              rank=0;

              jt10.setText("Level:"+rank);

              jt9.setText("Score: "+scor);

              upspeed=false;

              playing=true;

              runstop=false;

              gc.setGameOver(false);

              gc.repaint();

              gc.reset();

       }

The functions of the buttons in the control panel have been coded in 4.3.1 and will not be described again here.

6 system test runs

6.1 Test Overview

System testing is to confirm the software, computer hardware, peripheral equipment, network and other elements together for assembly testing and confirmation testing of various information systems. System testing is to test the entire product system with the purpose of verifying whether the system meets the required specifications. Define and identify inconsistencies or contradictions with the requirement specifications to propose a more comprehensive solution. After system testing reveals a problem, try to find out the cause and location of the error and then correct it. It is the overall system requirement based on black box testing and should cover all components of the system. Objects include not only the software to be tested, but also the hardware on which the software depends, peripheral devices and even some data, some supporting software and its interfaces.

System testing is an integrated testing software that, as part of the computer system, combines with other parts of the system to conduct a series of strict and effective tests in the actual operating environment of the computer system to identify potential problems with the software and ensure the normal operation of the system.

The purpose of system testing is to verify whether the final software system meets user requirements.

The main contents include:

(1) Functional testing. That is to say, the function of the test software system is correct according to the requirements of the document, such as the " Product Requirements Specification" . Since correctness is the most important quality factor of software, functional testing is crucial.

(2) Robustness test. That is, the ability to test a software system's normal operation under abnormal conditions. Robustness has two meanings: one is fault tolerance and the other is resilience.

6.1.1  Testing principles

 The basic principles of software testing include comprehensive testing from the perspective of product users, discovering as many problems and loopholes in the system use process as possible, researching and analyzing, and proposing problems and improvement suggestions on defective aspects of the product. The detailed testing principle is as follows:

(1) The software test plan is the action guide for software testing. The actual test should be carefully and strictly implemented, and the test plan should be strictly implemented with high feasibility, especially to determine the test method and test purpose.

(2) Testing standards are established based on user needs. The main purpose of software testing is to ensure product consistency and verify that the product can meet customer needs. Therefore, during the testing process, you should always look at the problem from the user's perspective and discover The impact of software defects and shortcomings, the most serious errors in the system, programs that fail to meet user needs, and functional defects.

(3) Tests cannot be treated casually.

Especially for system testing and repeated testing, if the test plan is not strictly implemented, it is very likely that new BUGs will be generated due to negligence. Therefore, the repeated testing phase should also be given full attention. There are many errors in early detection, most of which are not discovered due to negligence.

Purpose:

(1) Ensure that system testing activities are carried out normally;

(2) Verify the mismatch or contradiction between software products and system requirements;

(3) Establish a complete system testing defect tracking database;

(4) Ensure that relevant groups and individuals are notified of software system testing activities and results in a timely manner.

6.1.2  Test methods

In order to comprehensively test the system and find out the problems and faults in the system, using multiple testing methods to test together can more comprehensively summarize the advantages and disadvantages of the system design. The following test methods are used:

Functional testing: Test whether the function points under each functional module in the system can be used normally;

Manual testing: mainly tests input, click and other functions;

Black box testing: After inputting, check whether the result is correct.

Recovery testing: As a system test, recovery testing mainly focuses on various conditions that cause the software to fail and verifies that the recovery process can be implemented normally. In some cases, the system needs to be fault tolerant. In addition, system failures must be corrected within the specified time, otherwise serious economic losses will result. Recovery testing mainly checks the fault tolerance of the system. When a system error occurs, can the error be corrected and the system restarted within a specified time interval. Recovery testing must first use various methods to force the system to fail, and then verify whether the system can be restored as soon as possible. For automatic recovery, the correctness of reinitialization, checkpointing mechanisms, data recovery, and restart needs to be verified; for manual intervention recovery systems, the average repair time needs to be estimated , determine whether it is within the acceptable range.

Security testing: Security testing is used to verify the protection mechanism within the system to prevent illegal intrusions. In security testing, testers play the role of trying to invade the system and use various methods to try to break through the defense lines. So the standard for system security design is to find ways to make it more expensive to break into the system. Security testing checks the system's ability to prevent illegal intrusions. During the security test, testers pretended to be illegal intruders and used various methods to try to break through the defense lines. For example, ① try every means to intercept or decipher passwords; ② specially customize software to destroy the protection mechanism of the system; ③ deliberately cause the system to fail and attempt to illegally enter while it is recovering; ④ try to deduce the required information by browsing unconfidential data, etc. Theoretically, given enough time and resources, no system is inaccessible. Therefore, the principle of system security design is to make the cost of illegal intrusion exceed the value of the protected information. At this point there is no profit for the illegal trespassers.

Stress Testing: Stress testing refers to the implementation of a system using abnormal traffic, frequency, or data volumes under normal resources. The following tests can be performed during the pressure test:

① If the average number of interrupts is one to two per second, then the special test case is designed to generate 10 interrupts per second.

② Increase the amount of input data by an order of magnitude to determine how the input function responds.

③ In the virtual operating system, test cases that require the maximum amount of memory or other resources are required, or excessive disk storage data is generated.

Under normal circumstances, the system must be tested repeatedly. Because of the limitations of system time and functions, the system cannot be perfect. Therefore, it is necessary to examine various testing methods together.

Strength test

Strength testing checks a program's resistance to abnormal conditions. Stress testing always forces the system to run under abnormal resource configurations. For example, ① When the normal frequency of interrupts is one to two per second, run a test case that generates ten interrupts per second; ② Increase the data input rate quantitatively to check the response ability of the input sub-function; ③ The maximum storage space required for operation ( or other resources); ④ Run test cases that may cause the virtual memory operating system to crash or disk data to violently jitter, etc.

Performance Testing

    For those real-time and embedded systems, even if the software part meets the functional requirements, it may not be able to meet the performance requirements. Although starting from the unit test, every test step includes a performance test. The lead tester believes that only after the system is truly integrated, it will not be able to meet the performance requirements in the real environment. System performance testing is designed to accomplish this task in order to comprehensively and reliably test operational performance. Performance testing is sometimes combined with strength testing and often requires the support of other software and hardware.

6.1.3  Test significance and precautions

    Software testing is an extremely important link in the software design process and an important guarantee for ensuring the quality of software. The quality of the testing method will directly affect the quality of the software. Software testing can identify errors and deficiencies and improve them, thereby obtaining an efficient and reliable system.

    Software should be tested and analyzed from multiple angles so that errors can be found. It is best to find people who have nothing to do with the design system or analysts when testing. Because when developing software, developers have formed their own mindset and are always bound by this mindset when testing. It is difficult to find errors and it is easy for people and analysts who have nothing to do with the design to find them. Where the error occurred.

You must be patient and careful during the program debugging process. A slight error will cause the entire function to be unable to be realized and a lot of time will be wasted to modify it. Attention should be paid to the following aspects:

    1> Grammatical error

    Syntax errors are errors that are often encountered. For example, a misspelled command or incorrect parameters passed to a function will generate an error. Syntax errors may prevent you from continuing to write code.

    2> Logic error

    Logic errors can often be latent and difficult to detect. When there are logic errors caused by typing errors or program logic flow, it may run successfully, but the results produced are wrong. For example, when a greater than sign is used instead of comparing values ​​when a less than sign should be used, incorrect results will be returned.

    3> Runtime error

    Run-time errors are caused by instructions trying to perform impossible actions during execution. Run-time errors must be corrected to ensure the reliability of software operation.

    During the development process of this game, a variety of effective measures were used for testing to ensure software quality. The game was tested for boundary rotation, block flipping and cross-border testing, which greatly ensured software quality and error rates. However, there may still be some other errors and defects in the system. Therefore, the game must go through repeated running tests to minimize bugs as much as possible.

6.2 Testing of game codes and algorithms

    1> When writing the get() method, a return value is required, but there is no return statement in the program, causing an error when the program is compiled. The solution is to add a return statement to the method and return the corresponding content.

    2> When using a random function to generate blocks, no parameters are passed to each block, and the compilation cannot pass. The solution is to pass in the corresponding parameters according to the construction of each block.

    3> When writing the default position of each square of the T-shaped square, initialize the variable i that controls the position of the square to 0. The result of the operation is that the T-shaped square becomes a vertical square by default. The solution is to change the initialization value of variable i to 1 to achieve the designed effect.

    4> When running the program, the statistical scores are only the scores after each full row is eliminated, and the previous scores will be overwritten and there will be no accumulation. The solution is to change the "score=" in the program to "score+=", so that the scores can be accumulated.

    5> The errors in the algorithm process mainly focus on how to detect and eliminate blocks, how to process the accumulation of scores after clearing the level, and whether to upgrade. These aspects were finally solved after discussions with classmates and reference materials.

6.3 Functional testing of game interface menu options

1> “Game” menu test

Table 6.1 Game menu test case

Test case number

Test project name

Test execution steps

output

Test Results

01

"Start" button test

Click "Game" → "Start"

game reset

success

02

"End Game" button test

Click "Game" → "End Game"

game over

success

03

"Basic" button testing

Click "Game" → "Basic"

The game level is selected as beginner

success

04

"Intermediate" button test

Click "Game" → "Intermediate"

The game level is selected as intermediate

success

05

"Advanced" button test

Click "Game" → "Advanced"

The game level is selected as Advanced

success

06

"Custom" button test

"Custom" button test

A dialog box pops up to change custom information

success

07

"Fall Speed" slider test

Click "Game" → "Customize" → "Fall Speed"

Drag the slider to change the block's falling speed

success

08

"Block Shape" Radio Button Test

Click "Game" → "Customize" → "Block Shape" radio button

You can choose the block shape from elementary, intermediate, or advanced to change the shape of the block.

success

09

"Whether the box will automatically rise" selection box test

Click "Game" → "Customize" → "Whether the block will automatically rise" selection box

You can check the small squares. If you check them, the squares will rise automatically. If you don't check them, the squares will not rise automatically.

success

10

"Whether to play sound during the game" selection box test

Click "Game" → "Customize" → "Whether to play sounds during the game" selection box

You can check the small box. If it is checked, the sound will be played during the game. If it is not checked, the sound will not be played during the game.

success

11

"Change background" selection box

Click "Game" → "Customize" → "Whether to play sounds during the game" selection box

You can check the small square. If you select it, the game background image will be changed. If you uncheck it, the game background image will not be changed.

success

12

OK and Cancel button testing

Click the "Game" → "Customize" → "OK" or "Cancel" button

Click OK to save the changed settings and exit the dialog box; click Cancel to exit the dialog box without changing the settings.

success

13

"Block Color" button test

Click "Game" → "Block Color"

A dialog box pops up and you can change the block color, HSB, RGB and other customized information.

success

14

"Exit" button test

 Click "Game" → "Exit"

Exit the game and close the main interface window

success

2> "Help" menu test

Table 6.2 "Help" menu test case

Test case number

Test project name

Test execution steps

output

Test Results

15

"About" button test

Click "Help" → "About"

A dialog box pops up, prompting game version and other information.

success

6.4 Functional testing of key events

Table 6.3 Key event function test cases

Test case number

Test project name

Test execution steps

output

Test Results

16

Block movement test

During the game, click "Left, Right, Down"

Blocks move normally and will not move out of bounds

success

17

Block rotation test

During the game, click the "up" direction key

Blocks can be reversed without borders or obstacles.

success

6.5 Block stacking and elimination function test

Table 6.4 Block stacking and elimination function test cases

Test case number

Test project name

Test execution steps

output

Test Results

18

Block stacking test

When the block falls to the bottom or comes into contact with an obstacle

The blocks are successfully stacked at the bottom

success

19

Block elimination test

When a full row occurs

All full rows are eliminated and the blocks move down one by one.

success

20

game over test

When the screen is full

A session window pops up, prompting "Game Over"

success

6.6  Test results

After multiple testing methods to test various aspects and functions of the system, the test results show that the system basically meets the overall design requirements and the expected functions are basically completed. The system can basically meet the requirements at the beginning of design and development, and the test is over.However, the overall function is not powerful enough, and the innovation is slightly inferior. As the first version of development, the game still needs further improvement in many aspects such as functions and interface design.

in conclusion

Before I did my graduation project, my Java-related development was only at the level of theoretical knowledge. This graduation project made me understand the principle of "what you learn on paper is ultimately shallow, but you must practice it if you know it." The lack of actual software development experience is the conclusion I have made for myself. Through this graduation project, I completed all the development tasks of the Tetris game. I encountered many problems during the entire development process, such as the drawing and deformation of blocks, thread creation issues, synchronization control, full row judgment, elimination row processing, and the implementation of the highest score record function, but in the end I solved them one by one. , some of the more important points are summarized as follows:

First, in order to become familiar with the related functions and design of Tetris, I often download the stand-alone version of Tetris game from major game download websites, and study the implementation of functions and the design of the interface, think about and consult the data for analysis, and gradually design After repeated modifications and arguments, the development of the entire game was completed.

Second, in the game design process, I adopt the design pattern from rough to fine and the principle of testing from small to large. First design the game framework and test it layer by layer, then add specific implementation code and gradually conduct more detailed testing. During the design process, I often encounter problems. Through repeated thinking and testing, I will find out my mistakes and correct them, and then proceed to the next step to ensure that nothing goes wrong and try my best to reduce the final debugging workload.

Third, the graduation design industry can be regarded as a process of constantly learning new things. From not understanding the design at the beginning to successfully completing it in the end, I realize the importance of continuous learning in practice, which is important for me to get into the job in the future. educational significance. Through the creation of my graduation project, I have a deeper understanding of the Java course, which also laid a certain foundation for my future employment.

Graduation project is the last step in our learning stage as students. It is a comprehensive application of basic knowledge and professional knowledge. It is a comprehensive re-learning and then improvement process. The process of students' learning ability and independent thinking and working ability is also a training, and graduation The design level also reflects the comprehensive level of university education, so the school attaches great importance to graduation design and strengthens the guidance of graduation design work and mobilization education. In the process of university study, graduation project is an important part of our social participation in practical work. It is also for our ability to learn and solve life problems, and is a transformation of school life and social life. After completing my graduation project, I tried to integrate research design and practical work. This is more conducive to us strengthening our abilities.

After a period of hard work and with the help of some classmates and teachers, I finally completed my graduation project, which is an important task. Looking back on our design process, it can be said that difficulty and ease coexist. Among them, incorporating the knowledge learned at the university is actually a big challenge for me, and it is also a test of university knowledge. 

In the process of graduation project, we encountered many difficulties, and many of them were problems that we had never encountered before. If we did not do it ourselves, it might be difficult to find the knowledge we lack to some extent. For us, finding the problem, To solve the problem, this is the most practical. Facing problems that are difficult to solve by oneself, these problems can be solved with the help of teachers and students while obtaining some information, so the graduation project is successfully completed. It is understood that the knowledge of this project is still very profound, so we must continue to explore not only now, but also in the future.

The combination of theory and practice includes not only the knowledge of classroom participation, but also the combination of skills training and guidance on how students understand and contact socially relevant things. Students' graduation projects, under the guidance of professional theoretical knowledge, can solve some practical problems in a variety of ways. During the design process, students can use theoretical knowledge for practice, not only to deepen their understanding of professional theoretical knowledge, but also to enrich and develop the theoretical knowledge in this book and turn it into higher-level experience and skills. Due to the existing teaching model, there is a serious separation between theoretical knowledge and skills and production practice. Students are unable to learn knowledge outside the classroom. Practical production problems are often irrelevant to learning and cannot be effectively applied. Through reasonable selection of topics, students are guided to consciously use knowledge and skill systems to analyze and think, and contribute to the organic integration of theoretical knowledge and practice.

Society is constantly changing. At present, society is transforming and developing, and the requirements for talents are getting higher and higher. Use perspective to look at problems, learn to innovate, and learn to adapt to the requirements of social development. Outside school, enter society, seize today's opportunities, and create the future. The teacher's influence and professor's knowledge allowed me to understand many truths and face future challenges with a certain innovative spirit. 

    In short, for this graduation project, I feel that I have not only become more familiar with some professional knowledge than before, but also exercised my hands-on ability, and I feel that I have gained a lot. At the same time, you will also have a small sense of accomplishment because you have worked hard during this task. In future actual work, we should also work hard, not seeking the best, only seeking better! Also, I would like to express my sincere gratitude to my instructors and classmates for their help in this graduation project process!

The program basically meets the needs of users both technically and functionally. However, due to the initial design, the functions are not perfect enough and the design details are still insufficient.

这次的毕业设计,我受益匪浅,让我的思维方式更加缜密,能多个角度的看待、处理问题;知道遇到问题该如何去分析问题、解决问题。相信这些都会让我在以后的工作中受益无穷的。

参考文献

[1] 李刚,疯狂Java讲义(第3版),北京:电子工业大学出版社,2014.7

[2] 明日科技,Java从入门到精通(第4版),北京:清华大学出版社,2016(2017.1重印)

[3] 荣钦科技 Java2游戏设计.清华大学出版社,2004.

[4] 高凌琴 陈青华.俄罗斯方块游戏关键技术探讨[J].信息技术与信息化讨,2008年第二期

[5] 艾克尔.Java编程思想[M].北京:机械工业出版社,2005.2

[6] (美) Paul Hyde.Java线程编程[M].北京:人们邮电出版社,2003

[7] Martin dejode.Symbian OS J2ME[M].北京:人民邮电出版社,2005.10

[8] 朱福喜. Java程序设计技巧与开发实例[M].北京:人民邮电出版社,2004.2

[9] 袁海燕 王文涛.Java实用程序设计100例[M].北京:人民邮电出版社,2005.2:51~96

[10] 黄复贤.俄罗斯方块游戏的敏捷设计与开发[J]. 电脑编程技巧与维护,2005.4

[11] (美)Bill Venners.深入Java虚拟机[M].北京:机械工业出版社,2003.9.63~98

[12] 闻怡洋.J2ME MIDP 1.0/2.0无线设备编程指南[M].北京:北京大学出版社,2004.5:393~420

[13]赵东跃.俄罗斯方块编程[J].电脑编程技巧与维护,1998年第六期

[14]殷兆麟.Java网络编程基础[M].北京:北方交通大学出版社,2004

[15] (美)John Zukowski.Java 2 从入门到精通[M].北京:电子工业出版社,1999

[16] 宋波.Java应用开发教程[M].北京:电子工业出版社,2002

[17] 托普雷.J2ME技术手册[M].北京:中国电力出版社,2004.6:259~312

附录A 外文原文

The psychology of Tetris

   Shapes fall from the sky, all you have to do is to control how they fall and fit within each other. A simple premise, but add an annoyingly addictive electronica soundtrack (based on a Russian folk tune called Korobeiniki, apparently) and you have a revolution in entertainment.

   Since Tetris was launched on the world in the 1980s, millions of hours have been lost through playing this simple game. Since then, we’ve seen games consoles grow in power, and with it the appearance of everything from Call of Duty to World of Warcraft. Yet block and puzzle games like Tetris still have a special place in our hearts. Why are they are so compelling?

   The writer Jeffrey Goldsmith was so obsessed with Tetris that he wrote a famous article asking if the game’s creator Alexey Pajitnov had invented “a pharmatronic?” – a video game with the potency of an addictive drug. Some people say that after playing the game for hours they see falling blocks in their dreams or buildings move together in the street – a phenomenon known as the Tetris Effect. Such is its mental pull, there’s even been the suggestion that the game might be able to prevent flashbacks in people with PTSD.

   I had my own Tetris phase, when I was a teenager, and spent more hours than I should have trying to align the falling blocks in rows. Recently, I started thinking about why games like Tetris are so compelling. My conclusion? It’s to do with a deep-seated psychological drive to tidy up.

   Many human games are basically ritualised tidying up. Snooker, or pool if you are non-British, is a good example. The first person makes a mess (the break) and then the players take turns in potting the balls into the pockets, in a vary particular order. Tetris adds a computer-powered engine to this basic scenario – not only must the player tidy up, but the computer keeps throwing extra blocks from the sky to add to the mess. It looks like a perfect example of a pointless exercise – a game that doesn't teach us anything useful, has no wider social or physical purpose, but which weirdly keeps us interested.

   There's a textbook psychological phenomenon called theZeigarnik Effect, named after Russian psychologist Bluma Zeigarnik. In the 1930s, Zeigarnik was in a busy cafe and heard that the waiters had fantastic memories for orders – but only up until the orders had been delivered. They could remember the requests of a party of 12, but once the food and drink had hit the table they forgot about it instantly, and were unable to recall what had been so solid moments before. Zeigarnik gave her name to the whole class of problems where incomplete tasks stick in memory.

   The Zeigarnik Effect is also part of the reason why quiz shows are so compelling. You might not care about the year the British Broadcasting Corporation was founded or the percentage of the world's countries that have at least one McDonald's restaurant, but once someone has asked the question it becomes strangely irritating not to know the answer (1927 and 61%, by the way). The questions stick in the mind, unfinished until it is completed by the answer.

Game theory

   Tetris holds our attention by continually creating unfinished tasks. Each action in the game allows us to solve part of the puzzle, filling up a row or rows completely so that they disappear, but is also just as likely to create new, unfinished work. A chain of these partial-solutions and newly triggered unsolved tasks can easily stretch to hours, each moment full of the same kind of satisfaction as scratching an itch.

   The other reason why Tetris works so well is that each unfinished task only appears at the same time as its potential solution – those blocks continuously fall from the sky, each one a problem and a potential solution. Tetris is a simple visual world, and solutions can immediately be tried out using the five control keys (move left, move right, rotate left, rotate right and drop – of course). Studies of Tetris players show that people prefer to rotate the blocks to see if they'll fit, rather than think about if they'll fit. Either method would work, of course, but Tetris creates a world where action is quicker than thought – and this is part of the key to why it is so absorbing. Unlike so much of life, Tetris makes an immediate connection between our insight into how we might solve a problem and the means to begin acting on it.

   The Zeigarnik Effect describes a phenomenon, but it doesn't really give any reason for why it happens. This is a common trick of psychologists, to pretend they solved a riddle of the human mind by giving it a name, when all they've done is invented an agreed upon name for the mystery rather than solved it. A plausible explanation for the existence of the Effect is that the mind is designed to reorganise around the pursuit of goals. If those goals are met, then the mind turns to something else.

   Trivia takes advantage of this goal orientation by frustrating us until it is satisfied. Tetris goes one step further, and creates a continual chain of frustration and satisfaction of goals. Like a clever parasite, Tetris takes advantage of the mind's basic pleasure in getting things done and uses it against us. We can go along with this, enjoying the short-term thrills in tidying up those blocks, even while a wiser, more reflective, part of us knows that the game is basically purposeless. But then all good games are, right?

   If you would like to comment on this article or anything else you have seen on Future, head over to our Facebook page or message us on Twitter.

附录B 外文翻译

俄罗斯方块的心理效应

这一人们喜闻乐见的游戏成功的秘诀在于抓住了我们重复排列与使用的心理乐趣。

几何图形从屏幕上方缓缓降落,你要做的就是控制其降落方式并与其他图形排列消除。游戏的初衷很简单,但加上了令人上瘾的背景电子音乐后(据说来自俄罗斯民谣Korobeiniki)人们的娱乐生活发生了翻天覆地的变化。

自从1986年俄罗斯方块问世后,这一简单的游戏耗去了玩家数百万个小时。从那时起,从使命召唤到魔兽世界,游戏操纵平台的外观和性能都在茁壮发展。但像俄罗斯方块这样的方块益智类游戏始终占据了我们心中的一席之地。为何它们如此经久不衰呢?

作家杰弗里·戈德史密斯是沉迷于俄罗斯方块不能自拔,乃至于他写了一篇著名的文章,文中提到俄罗斯方块的发明者阿里克谢·帕吉诺特夫是否发明了一种“瘾药”——让人可以玩出瘾。一些人说自己连玩了几小时俄罗斯方块后连梦里都会出现降落的方块,还有看街上的大楼都在移动——这是一种名为“俄罗斯效应”的现象。这是游戏产生的心理推动作用,还有建议称那些患有创伤后精神紧张性障碍的人们需要预防游戏产生的幻觉重现。

当我十几岁的时候也有过一段俄罗斯方块沉迷期,我花了很多时间在方块的排列组合上。最近,我开始反思为什么俄罗斯方块这类游戏能够长青。说说我的结论吧,植根人们心中的心理驱使作用是整理这些方块的关键。

很多游戏的宗旨大体都是整理消除。落袋台球(snooker)就是典型的例子(对于非英国人来说叫做pool)。第一个人把球打乱后,其他人依照不同规则轮流将球射入落袋里。俄罗斯方块在这一基本框架中加入了电脑控制的成分——不光是玩家要整理方块,电脑还会不断从上方扔下额外的方块来制造凌乱。游戏看起来就是整一个漫无目的的过程,完全没有寓教于乐的成分在内,也没有深远的社交或是心理意义,但是我们却意外地为此着迷。

There is a typical psychological phenomenon called the "Zaigarnik Effect", named after Russian psychologist Bruma Zegarnik. In the 1830s, Zeigarnik discovered in a busy café that the waiters had amazing memories—but only until the meal was delivered. They can remember what a table of 12 people ordered, but once the food and drinks are served they forget everything and can't recall their previously solid memories. Zeigarnik named this phenomenon of persisting in memory unfinished tasks after himself.

The Zeigarnik Effect is one of the reasons why intelligence shows are so popular. You may not care in what year the BBC was founded or how many countries in the world have at least one McDonald's, but once a question like this comes up, you will feel uncomfortable if you don't know the answer (by the way, the answer is 1927 and 61%). Questions linger in your mind until they are answered.

Game principle

Tetris keeps its grip on our nerves by constantly creating tasks. Each link in the game leads us to solve a mystery. After lining up or completing a column, the graphics disappear, but new ones are constantly appearing, and the cycle starts again. Partially solved and newly formed task chains are very convenient to pass the time, and repeated feelings of satisfaction and anxiety fill every moment.

Another reason for the popularity of Tetris is that the tasks to be completed are juxtaposed with potential solutions - each of the blocks that gradually emerged has its own way of placement. Tetris is a simple visual world where solutions can be quickly arrived at by manipulating five buttons (left, right, turn left, turn right and land, of course). Studies of Tetris players show that people generally prefer to rotate the blocks to see if they match, rather than thinking about it while watching the blocks fall. Of course both methods are possible, but in the world of Tetris it's the action that always comes first - and that's the key to the appeal. Unlike in life, Tetris directly connects what we see and think when dealing with problems, and we can take immediate action on the problem.

The Zeigarnik effect is a description of a phenomenon, but it cannot explain its cause and effect. This is a common trick used by psychologists. It seems that they have solved the mysteries of human beings by naming them. In fact, all they did was greedily name them after themselves and did not solve the problem at all. A reasonable explanation for this reality is that brain circuits reorganize in the process of achieving goals. If this goal is achieved, thoughts will move on to other things.

Puzzle games exploit the principle of psychological attainment to continually frustrate us until we are satisfied. Tetris goes a step further by creating a continuous chain between failure and success. Like a clever parasite, Tetris exploits people's psychological pleasure in completing and reusing games. As we play, we briefly revel in the fun of arranging the blocks, even though the rational and mature part of our personality understands that this is basically a meaningless game. But isn’t that the case with all fun games, am I right?

References:

Graduation project of Tetris game system based on Java (project report + defense PPT + source code + database + screenshots + deployment video) icon-default.png?t=N5K3https://download.csdn.net/download/dwf1354046363/87813602

174 examples of Java graduation projects, including deployment videos_Yi Xiaoxia's blog-CSDN blog Various Java graduation projects are self-picked, and there are 160+ sets of Java graduation projects with explanation videos, and a collection https://cv2022.blog.csdn .net/article/details/124463185?spm=1001.2014.3001.5502

Guess you like

Origin blog.csdn.net/woaimx_1314/article/details/130789752