I'm trying to create a browser game. The game state is stored in an object with multiple layers.
let State = {
points: 0,
health: 50,
currentLocation: {x: 5, y: 55},
inventory: { bread: 8, water: 33, money: 20 }
abilities:
charisma:5,
perseverance: 3,
speed: 8
}
buildings {
bakery: { location: {x: 23, y: 41}, unlocked: 1, visited: 1},
homestead: { location: {x: 3, y: 59}, unlocked: 0, visited: 0},
forge: { location: {x: 56, y: 11}, unlocked: 1, visited: 0}
}
}
I want to be able to control the game logic based on the current values of State.
Some cases are very simple
if(State.health == 0) { Game.die(); }
Most cases are much more complex
if(State.buildings.bakery.unlocked == 1) {
// calculate player's distance to bakery
let dX = Math.abs(State.buildings.bakery.location.x - State.currentLocation.x)
let dY = Math.abs(State.buildings.bakery.location.y - State.currentLocation.y)
let d = DX + dY;
if(State.inventory.bread == 0 && d < State.inventory.abilities.speed) {
Game.die();
}
}
What is the best way to achieve something like this? Looping over all the conditions seems to be a needless use of resources. I've looked into getters, setters and Proxy but don't really know what I'm doing! Ideally I'd only want to only check the logic when a relevant part of State changes.