mana(mp: number = 0) => ManaComp
Handles mana/magic related logic and events.
const player = add([
mana(10),
])
onKeyPress("1", () => {
if player.tryCast(6) {
debug.log("Player casted \"fireball\"!");
}
})
onKeyPress("2", () => {
player.gain(3);
})
Docs
mana(mp: number = 0) => ManaComp
mp() => number
setMP(mp: number = 0)
maxMP() => number
setMaxMP(mp: number = 0)
gain(mp: number = 1)
cast(mp: number = 1)
canCast(mp: number = 1) => bool
tryCast(mp: number = 1) => bool
onGain((amt: number) => void)
(orobj.on("gain", (amt: number) => void)
)onCast((amt: number) => void)
(orobj.on("cast", (amt: number) => void)
)inspect() => string
The Code
function mana(max_mana=0) {
let val = 0
let max_val = max_mana
return {
id: "mana",
add() {
val = max_val;
},
mp() {
return val;
},
setMP(mp=0) {
val = mp;
if (val > max_val) {
val = max_val;
}
if (val < 0) {
val = 0;
}
},
maxMP() {
return max_val;
},
setMaxMP(mp=0) {
max_val = mp;
if (max_val < 0) {
max_val = 0;
}
if (val > max_val) {
val = max_val;
}
},
gain(mp=1) {
if (this.mp() >= this.maxMP()) {
return;
} else if (this.mp() + mp <= this.maxMP()) {
this.setMP(this.mp()+mp);
this.trigger("gain", mp);
} else {
let diff = this.maxMP() - (this.mp()+mp);
this.setMP(this.mp()+mp);
this.trigger("gain", diff);
}
},
cast(mp=1) {
if (this.mp() - mp >= 0) {
this.setMP(this.mp()-mp);
this.trigger("cast", mp);
}
},
canCast(mp=1) {
return (this.mp() >= mp);
},
tryCast(mp=1) {
if (this.canCast(mp)) {
this.cast(mp);
return true;
} else {
return false;
}
},
onGain(func) {
this.on("gain", func);
},
onCast(func) {
this.on("cast", func);
},
inspect() {
return "" + this.mp() + "/" + this.maxMP();
}
}
}