search
HomeJavajavaTutorialFinite state machine for java game development

How do these different operations display different effects in the game? By setting different states in the program, whatever the current state is, the logic will be executed. In fact, this is called: finite state machine! Let’s find out more with the editor below.

At different stages, the logic of the game and the interface displayed are different.

Take Gomoku as an example. The corresponding interface and logic are different when the game starts, during the game, and when the outcome is determined.

In the game, it is divided into multiple states: playing chess by yourself, playing chess by the opponent, pausing the game, regretting the game, etc.

Another example is the characters in RPG games. Standing, walking, running, attacking, and dying are all different animations.

Send a bullet from appearing to moving forward and hitting the target. , or flying out of the screen, all have different logic.


How to achieve these effects?

Different states are set in the program. Whatever the current state is, the logic will be executed.

This is called: finite state machine!

Isn’t it very simple? Don’t underestimate it. Complex game functions are all realized by it. Related tutorials: Java Video Tutorial


Next we use code to achieve a simple effect.

Also take a small square as an example, let it move in a prescribed way on the screen.

package game6;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
 * java游戏开发杂谈
 * ---demo6:有限状态机
 * 
 * @author 台哥编程课堂
 * https://www.cnblogs.com/chaohi/
 * 
 * @date 2019-04-25
 */
public class GamePanel extends JPanel{
	/** 屏幕的宽和高 */
	private int width,height;
	public GamePanel(int width, int height) {
		this.width = width;
		this.height = height;
		this.setSize(width, height);
		//设置当前画布可以获得焦点。
		this.setFocusable(true);
	}
	/**方块的位置*/
	private int fk_x = 60;
	private int fk_y = 60;
	/**
	 * 画布的绘制
	 */
	public void paintComponent(Graphics g) {
		super.paintComponent(g);	
		//画绿色背景
		g.setColor(new Color(0x9391d6));
		g.fillRect(0, 0, width, height);
		//绘制方块,大小为80
		g.setColor(Color.red);
		g.fillRect(fk_x, fk_y, 80, 80);
	}
	//四个状态,对应四个方向的运动
	private static final int stage_left = 0;
	private static final int stage_right = 1;
	private static final int stage_up = 2;
	private static final int stage_down = 3;
	//当前状态,初始为向右
	private int stage = stage_right;
	/**
	 * 游戏逻辑,处理方块的运动,每次横纵坐标都移动1个像素
	 */
	public void logic()
	{
		switch(stage)
		{
		case stage_right:
			if(fk_x < 260){
				fk_x = fk_x + 1; //右移一个像素
			}else{
				stage = stage_down; //超出指定范围,改为向下状态
			}
			break;
		case stage_down:
			if(fk_y < 260){
				fk_y = fk_y + 1;
			}else{
				stage = stage_left;
			}
			break;
		case stage_left:
			if(fk_x > 60){
				fk_x = fk_x - 1; 
			}else{
				stage = stage_up;
			}
			break;
		case stage_up:
			if(fk_y > 60){
				fk_y = fk_y - 1; 
			}else{
				stage = stage_right;
			}
			break;
		}
	}
}

The other two classes, GameFrame and GameThread, are the same as those in the previous blog and will not be posted here.


Finite state machine for java game development

The effect of the program is that the red square starts from the upper left corner, moves right, down, left Move, move up, cycle clockwise.

In the code, we have defined four states, corresponding to the movement in the four directions.

In the logic method of the game thread, the position attribute is changed according to the current state. The thread Then call the interface to redraw.

The code examples used have rough interfaces because the purpose is to introduce knowledge points. The simpler it is, the easier it is to understand.

The above is the detailed content of Finite state machine for java game development. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools