Skip to content
Advertisement

How can I keep track of game data that is changing without using global variables? [webpack]

I had a simple Rock Paper Scissors game where I used global variables to keep track of game data like player score, computer score, the state of the game (ongoing = true/false), etc.

I recently learned how to use webpack so I bundled up my code into modules to practice in this format, and now I’m unable to access the variables or objects that I declare in my dist/index.js file.

I think I understand why I’m unable to access them, but my question is: how am I supposed to update the state of the game without that data being stored anywhere in memory? Or am I wrong, and is that data actually stored somewhere? If you could give me a high-level overview of how I would achieve this, or if there is some example code I can review that uses bundling, that would be nice.

Sorry if this is a newbie question, I tried Googling for hours and couldn’t find exactly what I was looking for.

Advertisement

Answer

There are quite a few ways to do this. One approach is to have a module that manages state that the whole project needs access to. You can have:

// state.js
let state = { playerWinCount: 0 }; // you can add desired properties here
export const getState = () => state;
export const setState = (newState) => {
  state = newState;
};

Whenever you need to set something, either import and call setState, or call getState and mutate the state.

export const handlePlayerWin = () => {
  const state = getState();
  setState({ ...state, playerWinCount: state.playerWinCount + 1 });
};
// or
export const handlePlayerWin = () => {
  const state = getState();
  state.playerWinCount++;
};

Another approach is to, from somewhere around your entry point, continually pass down an object that’s shared among your app’s modules.

// index.js
const state = { playerWinCount: 0 };
doSomething(state);
doSomethingElse(state);

and then just access the state argument in those functions, and keep passing it down to other functions if needed.

const doSomething = (state) => {
  // ...
  state.playerWinCount++;
};
const doSomethingElse = (state) => {
  // ...
  console.log(state.playerWinCount);
};

Another way (which I wouldn’t recommend) would be to explicitly create a global variable:

// index.js
window.state = { playerWinCount: 0 };

// in other modules, you can now reference window.state

But that defeats the purpose of using modules.

Advertisement