I am trying to create a world boss system using PHP. But I am having a problem with how to account for all the damage while updating the health of the boss in real-time.
The current damage process is as follows:
- Get boss' current HP from database.
- Reduce the HP based on the calculated damage.
- Update the boss' HP to database.
Example:
- Player 1 (P1) attacks the boss. Calculated damage is 10.
- The boss' current HP is saved to variable $boss_hp which is 100.
- It will now be $boss_hp -= 10. Which is 90.
- The boss' HP in database is then updated.
Now, imagine two player attack the boss simultaneously...
- P1 attacks the boss. Calculated damage is 10.
- The boss' current HP is saved to variable $boss_hp which is 100.
- It will now be $boss_hp -= 10. Which is 90.
- Before P1 updates the boss_hp in database, P2 also damages the boss.
- P2 saved the boss' current HP to his/her own $boss_hp variable which is 100 at the moment.
- P2 also performs step 2. $boss_hp -= 10. Which is also 90.
- P1 now updates the boss_hp in database (=90).
- P2 also updates the boss_hp in database (=90).
The boss_hp should be 80 but the damage of P1 has been neglected since P2 updates the boss_hp last.
How to avoid this problem?