Edit A Variable Within An Array
I'm attempting to create a Choose Your Own Adventure type of game, and I'm currently trying to write a 'battle' script. What I've got so far is: var name = 'Anon'; var health = 100
Solution 1:
Hope this isn't too much code:
varAttack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
returnthis.message;
};
};
varCharacter = function(name,health){
this.name = name;
this.health = health;
};
hero = newCharacter('Anon',100);
orc = newCharacter('Orc',150);
attack1 = newAttack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = newAttack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = newAttack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = newAttack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
Solution 2:
I can tell you first hand that trying to write this type of code uses a lot of if/else and more statements, regardless of what language you're using. You can use an array to hold the values of your attack patterns:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
functionyouAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
But, without seeing exactly what you're doing I cannot say how you should do your attacks and damages. I can only assume. You will need a system of evaluating attacks, misses, etc. that does use IF/ELSE Statements at least somewhere.
Post a Comment for "Edit A Variable Within An Array"