Garage-Collective / Dark-And-Under

Dark & Under game for Arduboy.
BSD 3-Clause "New" or "Revised" License
32 stars 16 forks source link

Variable overflow in battle code #23

Closed Pharap closed 6 years ago

Pharap commented 6 years ago

Reported here:

https://community.arduboy.com/t/dark-under-a-dungeon-crawler/4637/167

The problem is here:

https://github.com/Garage-Collective/Dark-And-Under/blob/6562e7b9df40806d59ff40ed993a995e69d8a099/Dark-And-Under/DarkUnder_Battle.ino#L187

uint8_t maxHP = enemies[attackingEnemyIdx].getAttackPower() - myHero.getDefence();
if (maxHP < 2) maxHP = 2;
if (maxHP > 10) maxHP = 10;
uint8_t hpLoss = random(0, maxHP);
Pharap commented 6 years ago

Proposed solution:

const uint8_t enemyAttack = enemies[attackingEnemyIdx].getAttackPower();
const uint8_t playerDefence = myHero.getDefence();

uint8_t maxHP = (enemyAttack > playerDefence) ? (enemyAttack - playerDefence) : 2;
if(maxHP < 2) maxHP = 2;
if(maxHP > 10) maxHP = 10;
const uint8_t hpLoss = random(0, maxHP);

Adds only 4 bytes of progmem, which is oddly better than many other solutions.

Pharap commented 6 years ago

Sovled by #25.