This is just an exercise in modeling the objects you want to represent your game.
At the very least, you need a concept of the battling entities (players and creatures) and individual battles.
The Creature / Player will be objects that have attributes like HP and Attack power.
The Battle class will track things like turn count, whose turn it is, etc.
When the player initiates the battle, you should create a new battle object to track the turns.
In the following example code, I'm using javascript functions as examples, but you can map them to REST endpoints or whatever. for example, POST /battles/new
with data attacker_id=2&target_id=1
for function initiateBattle
.
// Starts a Battle -- could throw an exception if either combatant is already in combat.
function initiateBattle(attacker, target) {
var battle = new Battle(attacker, target);
game.globalBattlesList.add(battle);
return {battle: {
id: battle.id,
current_turn: {
owner: attacker,
number: 1,
}}};
}
// Send an attack in a battle
function attack(battle, attacker, target) {
if (battle.current_turn.owner != attack) {
return {result: "error", message: "It's not your turn!"};
}
target.HP -= attacker.ATK;
if (target.HP <= 0) {
...
game.end_battle(battle);
return {
status: "OK",
winner: attacker,
message: "${attacker.name} wins in ${battle.current_turn.number} turns!"
};
}
// change turn
battle.current_turn = {owner: target, number: battle.current_turn.number + 1};
// does the AI have a delay?
setTimeout(function() {
// do_enemy_turn will choose an action for the AI
// and set battle.current_turn back to
do_enemy_turn(battle, target, attacker);
}, target.attack_delay);
return {
result: "continue",
message: `target is at ${target.HP} HP`
};
}