-
-
Save plasticrake/db55268a86421307d9d29a62e16c6787 to your computer and use it in GitHub Desktop.
dicerollerV3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const myCharOne = { | |
name: "Zolda", | |
class: "Wizard", | |
maxHp: 90, | |
currentHp: 75, | |
armorClass: 16, | |
atkBonus: 7, | |
magicBonus: 10, | |
}; | |
const myCharTwo = { | |
name: "Rollo", | |
class: "Sorcerer", | |
maxHp: 100, | |
currentHp: 85, | |
armorClass: 15, | |
atkBonus: 6, | |
magicBonus: 11, | |
}; | |
// Version 3 | |
function diceRoll(min, max) { | |
// no need for a variable | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
function atkRoll(diceResult) { | |
// orig: return (diceResult += myCharOne.atkBonus); | |
// immediately using the result of an incremented variable can be confusing to work with | |
// In addition this is incrementing the parameter itself, which can have side effects | |
// There aren't side effects for primitives such as string/number, but if it were an object | |
// it would be modifying the object. Some style guides say to just never mess with modifying | |
// parameters | |
// Here is an example not using the "side-effect" of the addition. | |
// diceResult += myCharOne.atkBonus; | |
// return diceResult; | |
// even better, no need to modify any variables at all: | |
return diceResult + myCharOne.atkBonus; | |
} | |
function makeAtk(minimum, maximum) { | |
const theRoll = diceRoll(minimum, maximum); | |
const addingBonus = atkRoll(theRoll); | |
const printedStatement = `You rolled a ${theRoll} for a total of ${addingBonus}.`; | |
if (theRoll == 20) { | |
return `Critical Hit!! ${printedStatement} ${myCharOne.name}'s attack hit ${myCharTwo.name} for 4 damage!!`; | |
} else if (theRoll == 1) { | |
return `Critical Miss!! ${printedStatement} Your sword flew right in the trash!!`; | |
} else if (addingBonus >= myCharTwo.armorClass) { | |
return `${printedStatement} ${myCharOne.name}'s attack hit ${myCharTwo.name} for 2 damage!`; | |
} else { | |
return `${printedStatement} ${myCharOne.name}'s attack missed!`; | |
} | |
} | |
console.log(makeAtk(1, 20)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment