Piotr Sikora - Logo - Automatyzacja procesów | AI | JavaScript | Front End | Team Leader
  • Home
  • Services
    • Process Automation
    • AI for Lawyers
  • Blog
  • Quotes
  • Contact
PL/EN

State Machine Game: Build Your Own Redux-Like Engine

  • Home
  • Blog
  • State Machine Game: Build Your Own Redux-Like Engine
State Machine Game: Build Your Own Redux-Like Engine

By Piotr Sikora

  • javascript

  • 6 min read

Table of Contents

  • Redux like engine - Step 1 - Draft of state management function
  • Redux like engine - Step 2 - Initial State
  • Redux like engine - Step 3 - Reducer
  • Redux like engine - Step 4 - Body of state management function
  • Redux like engine - Step 5 - Combine and run

This article will describe shortly how to build Redux-like state machine engine.

So shortly what we need to define state machine? - State itself (method which will deliver the state) - Subscribe method (which will subscribe to state changes) - Dispatch method (which will execute changes of our state engine)

Redux like engine - Step 1 - Draft of state management function

Lets define the draft of Redux-like function with previously defined methods getState, dispatch and subscribe. Parameter of our state managing function will be reducer - function which will describe how state should behave on given action.

const createStore = (reducer) => {
        let state;

        const getState = () => state;

        const dispatch = () => console.log('this method will execute change of state');

        const subscribe = () => console.log('this method will subscribe to changes on state);

        return {
            getState,
            dispatch,
            subscribe
        }
    };

Defined arrow function will return three methods: 1. getState - which will return our current state 2. dispatch - dispatcher of actions 3. subscribe - method which subscribes to state changes

Inside createStore function we defined state. This is the variable which keeps our current state. If we want to have a direct access to state we need to invoke getState method.

Redux like engine - Step 2 - Initial State

Our Redux-like engine won't work without reducer and initial state. In this section let's define initial state. Let's imagine that we are developing game and one action of the game will be related to shots made by user. So when user will be clicking on screen or touching screen on mobile devices this action will be invoked. After invoking this action our state will be changed. In this case the number of shots made by user will be incremented. Initially it will be equal 0.

initialState = {
    shots: 0
};

Redux like engine - Step 3 - Reducer

In this section we will define our reducer which will describe how our state should be changed after dispatching / executing given action. Reducer will get two params: 1. Initial state (defined previously) 2. Action

Action is an object with two parameters: 1. type 2. payload

Initially we will describe how our state should behave when user will invoke SHOT action.

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SHOT':
           state = {
                ...state,
                shots: state.shots +1
            }
            return state;
        default:
            return state;
    }
}

To make interpretation of our reducer function lets imagine that we want to invoke action SHOT. To do it we have to pass to reducer action object like

{
    type: 'SHOT'
}

Redux like engine - Step 4 - Body of state management function

Let's make our state usable. To do it we need to define two methods inside it 1. subscribe 2. dispatch

Before subscribe function will be created we have to define listeners inside createStore. Listeners will be an array of elements which will subscribe to our state and will react on each change of the state.

const createStore = (rootReducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = action => {
        state = rootReducer(state, action);
        listeners.forEach(listener => listener(state));
    };

    const subscribe = (listener) => {
        listeners.push(listener);

        return () => {
            listeners = listeners.filter(l => l !== listener)
        }
    };

    return {
        getState,
        dispatch,
        subscribe
    }
};

Redux like engine - Step 5 - Combine and run

Lets make a short tests. In this subchapter we will combine reducer and our statemanagement engine. At the end of code we will make an instance of store, we will subscribe to it and will get its value.

const initialState = {
    shots: 0
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SHOT':
          console.log('shot')
           state = {
                ...state,
                shots: state.shots +1
            }
            return state;
        default:
            return state;
    }
};

const createStore = (rootReducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = action => {
        state = rootReducer(state, action);
        listeners.forEach(listener => listener(state));
    };

    const subscribe = (listener) => {
        listeners.push(listener);

        return () => {
            listeners = listeners.filter(l => l !== listener)
        }
    };

    return {
        getState,
        dispatch,
        subscribe
    }
};

const storeInstance = createStore(reducer);

console.log(storeInstance.getState());

storeInstance.subscribe(() => console.log('subscriber shots:', + storeInstance.getState().shots))

storeInstance.dispatch({type: 'SHOT'});
storeInstance.dispatch({type: 'SHOT'});
storeInstance.dispatch({type: 'SHOT'});

console.log(storeInstance.getState());

After running this code we will see console log similar to this one:

"shot"
"subscriber shots:" 1
"shot"
"subscriber shots:" 2
"shot"
"subscriber shots:" 3
[object Object] {
  shots: 3
}

Everytime "dispatch" function is ran it gives us information about sum of shots. Additionally we can see that reducer function is ran ("shot" log).

State management - Isn't it easy? :D

Share this article

TwitterLinkedInFacebook

Tags:

  • #redux

  • #state-machine

  • #state-machine-in-javascript

  • #state-management

Categories

after-hours(1)AI(7)ai-en(1)angular(4)automatic-tests(1)Automation(2)cryptography(1)css(8)CyberSecurity(2)Development(6)DevOps(1)events(3)javascript(11)n8n(10)ollama(1)security(2)seo(1)

Recent Posts

Testing Kimi Code: First Impressions from Web and CLI

Development

Testing Kimi Code: First Impressions from Web and CLI

Why You Shouldn't Cram Multiple Webhooks Into One n8n Workflow

Automation

Why You Shouldn't Cram Multiple Webhooks Into One n8n Workflow

DRY, WET, AHA: Finding the Right Balance in Code Reuse

Development

DRY, WET, AHA: Finding the Right Balance in Code Reuse

API vs Webhook: Understanding the Difference

Development

API vs Webhook: Understanding the Difference

RTCROS Framework: Structure Your Prompts for Better AI Results

AI

RTCROS Framework: Structure Your Prompts for Better AI Results

About Me

Piotr Sikora - Process Automation | AI | n8n | Python | JavaScript

Piotr Sikora

Process Automation Specialist

I implement automation that saves time and money, streamlines operations, and increases the predictability of results. Specializing in process automation, AI implementation, and workflow optimization using n8n, Python, and JavaScript.

n8n Workflows

n8n workflow automation templates

Explore my workflow templates on n8n. Ready-to-use automations for blog management, data collection, and AI-powered content processing.

3Workflow Templates
View Templates

• Auto-Categorize Blog Posts with AI

• Collect LinkedIn Profiles

• Export WordPress Posts for SEO

Tags

activepiecesafter-hoursahrefsaiAI cost reductionai-agentsai-automationangularantigravityapiAqua Securityarcade-gamesarchitectureautomationbackendbest-practicescadillacs-and-dinosaurschatbotchatgptCI/CD
“The man who follows the crowd will usually get no further than the crowd. The man who walks alone is likely to find himself in places no one has ever been.”
Anonymous
View more quotes

Similar Articles

Discover more related content

State Management: Prepare Environment Properly

State Management: Prepare Environment Properly

To start project we will need to create node project. I assume that you have installed Node.js on your machine.

Angular Side Effects with @Effect & NgRx CRUD

Angular Side Effects with @Effect & NgRx CRUD

Essential CRUD Snippets. Angular is giving great tools to build application and NgRx gives you opportunity to manage you app with state.

Unleash the Power of Autoexecuted Objects in JavaScript

Unleash the Power of Autoexecuted Objects in JavaScript

Sometimes you will need to create autoexecuted object (for example in case of load/document ready events)

31 January 2014
Piotr Sikora | ai | n8n | javascript | python

Let's get to know each other!

Get in touch with me
Piotr Sikora | Process Automation  | AI Implementation 🤖 | Technology Consulting
Quick links
  • Home
  • Blog
  • Contact
Contact
  • piotr.sikora.ck@gmail.com
  • +48 505 684 661

© Piotr Sikora 2026 | All Rights Reserved