Skip to content

Instantly share code, notes, and snippets.

@painedpineapple
Last active December 8, 2022 18:55
Show Gist options
  • Save painedpineapple/251cc12ba310b94b26c47c0679bea300 to your computer and use it in GitHub Desktop.
Save painedpineapple/251cc12ba310b94b26c47c0679bea300 to your computer and use it in GitHub Desktop.
const initialState = {
// The current state of the battle
currentState: 'SELECT_MOVE',
// The active Pokemon on each side
activePokemon: [null, null],
// The remaining health of each Pokemon
health: [0, 0],
// The moves available to each Pokemon
moves: [[], []],
// The current move being used by each Pokemon
currentMove: [null, null],
// The effect of each Pokemon's current move
moveEffect: [null, null],
// The status effect of each Pokemon
statusEffect: [null, null],
// The stats of each Pokemon
stats: [[], []]
};
function pokemonBattleReducer(state = initialState, action) {
switch (action.type) {
case 'SELECT_MOVE':
// Set the current move for the active Pokemon
const currentMove = state.currentMove.slice();
currentMove[action.side] = action.move;
// Calculate the effect of the move based on the Pokemon's stats
const moveEffect = state.moveEffect.slice();
moveEffect[action.side] = calculateMoveEffect(
action.move,
state.stats[action.side]
);
return {
...state,
currentState: 'APPLY_MOVE',
currentMove,
moveEffect
};
case 'APPLY_MOVE':
// Check if the move has a chance to cause a critical hit
let criticalHit = false;
if (Math.random() < action.move.criticalHitChance) {
criticalHit = true;
}
// Calculate the effect of the move on the opposing Pokemon's health
const health = state.health.slice();
let damage = moveEffect[action.side];
if (criticalHit) {
damage *= 2;
}
health[action.opposingSide] -= damage;
// Check if the move has a chance to cause a status effect
let statusEffect = state.statusEffect.slice();
if (Math.random() < action.move.statusEffectChance) {
statusEffect[action.opposingSide] = action.move.statusEffect;
}
return {
...state,
currentState: 'CHECK_VICTORY',
health,
statusEffect
};
case 'CHECK_VICTORY':
// Check if either Pokemon has been defeated
if (state.health[0] <= 0 || state.health[1] <= 0) {
return {
...state,
currentState: 'BATTLE_OVER'
};
} else {
return {
...state,
currentState: 'SELECT_MOVE'
};
}
default:
return state;
}
}
function calculateMoveEffect(move, stats) {
// Calculate the effect of the move based on the Pokemon's stats
let effect = move.baseEffect;
effect = effect * stats.attack / stats.defense;
return effect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment