Redux Hero
by Timatnet
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.min.js"></script>
<script src="https://npmcdn.com/[email protected]/lib/createAction.js"></script>
Babel + JSX
const { createStore, combineReducers } = Redux;
const initialState = {
xp: 0,
level: 1,
position: {
x: 0,
y: 0,
},
stats: {
health: 50,
maxHealth: 50,
},
inventory: {
potions: 1,
}
};
//
// Actions
//
const Actions = {
GAIN_XP: 'GAIN_XP',
LEVEL_UP: 'LEVEL_UP',
MOVE: 'MOVE',
DRINK_POTION: 'DRINK_POTION',
TAKE_DAMAGE: 'TAKE_DAMAGE',
};
//
// Action Creators
//
const createActions = (actions) => actions.map(x => createAction(x));
const [gainXp, levelUp, drinkPotion, takeDamage] = createActions([Actions.GAIN_XP, Actions.LEVEL_UP, Actions.DRINK_POTION, Actions.TAKE_DAMAGE]);
const move = createAction(Actions.MOVE, (x, y) => ({ x, y }));
//
// Reducers
//
const xpReducer = (state = 0, action) => {
switch (action.type) {
case Actions.GAIN_XP:
return state + action.payload;
}
return state;
};
const levelReducer = (state = 1, action) => {
switch (action.type) {
case Actions.LEVEL_UP:
return state +1;
}
return state;
};
const positionReducer = (state = initialState.position, action) => {
switch (action.type) {
case Actions.MOVE:
let { x, y } = action.payload;
x += state.x;
y += state.y;
return { x, y };
}
return state;
};
const statsReducer = (state = initialState.stats, action) => {
let { health, maxHealth } = state;
switch (action.type) {
case Actions.DRINK_POTION:
health = Math.min(health + 20, maxHealth);
return { ...state, health, maxHealth };
case Actions.TAKE_DAMAGE:
health = Math.max(0, health - action.payload);
return { ...state, health };
}
return state;
};
const inventoryReducer = (state = initialState.inventory, action) => {
let { potions } = state;
switch (action.type) {
case Actions.DRINK_POTION:
potions = Math.max(0, potions - 1);
return { ...state, potions };
}
return state;
};
//
// Bootstrapping
//
const reducer = combineReducers({
xp: xpReducer,
level: levelReducer,
...