Javascript循环在访问原型函数时中途终止
我正在用JavaScript写一场战斗。程序有时运行,有时不运行。有时它会在抛出错误之前循环5-6次 功能包括玩家、武器、敌人和作战模拟。 原型上的函数有applyDamage、isAlive、attackWith、attack、Create仇敌、CreatePlayer、run 我正在练习使用原型,但我不太清楚如何使用它们。有5名玩家和20名敌人 在一些循环迭代之后,我得到了这个错误:Javascript循环在访问原型函数时中途终止,javascript,function,loops,prototype,javascript-objects,Javascript,Function,Loops,Prototype,Javascript Objects,我正在用JavaScript写一场战斗。程序有时运行,有时不运行。有时它会在抛出错误之前循环5-6次 功能包括玩家、武器、敌人和作战模拟。 原型上的函数有applyDamage、isAlive、attackWith、attack、Create仇敌、CreatePlayer、run 我正在练习使用原型,但我不太清楚如何使用它们。有5名玩家和20名敌人 在一些循环迭代之后,我得到了这个错误: console.log("Your fighter is: " + myPlayer.name);
console.log("Your fighter is: " + myPlayer.name);
^
“TypeError:无法读取未定义的属性'name'”
有时错误出现在代码的不同部分。我想在把玩家送上战场之前检查一下他们是否还活着。一旦他们死了,我不希望他们回到战场上,所以我使用Player.prototype中定义的函数检查他们是否还活着
while (myPlayer.isAlive == false) {
myPlayer = players[Math.ceil(Math.random() * 5)];
}
我有时会遇到TypeError:无法读取未定义的属性“isAlive”
你能帮我找出这个原型吗?如果我做得对的话?谢谢你
守则:
function Player(name, weapons) {
// Each player has a name, an initial health of 10, an
// initial strength of 2, and an array of weapons objects
this.name = name;
this.health = 10;
this.strength = 2;
this.weapons = weapons;
}
// applyDamage deals damage to the Player - takes an integer
// input and subtracts that from the player's health
Player.prototype.applyDamage = function(damage) {
console.log(damage + " damage applied!");
// Subtract damage received from the player's health
this.health -= damage;
console.log(this.name + "\'s health is now " + this.health);
};
// isAlive checks if the player's health is >0. Returns true
// if it is and false if not.
Player.prototype.isAlive = function() {
if (this.health > 0) {
return true;
} else {
return false;
}
};
// attackWith uses a random number between 7 and 0, selects
// the weapon at that index, and returns the weapon
Player.prototype.attackWith = function() {
let choice = Math.ceil(Math.random() * (7));
return this.weapons[choice];
};
function Weapon(name) {
// Each weapon has an assigned name and random damage level
this.name = name;
this.damage = Math.ceil(Math.random() * 5);
//random number between 1 and 5
}
// attack checks if the fighters are dead, then applies damage
// based on strength and weapon
Weapon.prototype.attack = function(player, enemy) {
while (player.isAlive && enemy.isAlive) {
// Calculate actual damage =
// strength of player * damage value of weapon
let actualDamage = player.strength * this.damage;
console.log("\n" + player.name + " attacks " + enemy.name
+ "!");
// Call the applyDamage function of the Enemy object and
// pass the actual damage value calculated
enemy.applyDamage(actualDamage);
console.log("Enemy health is " + enemy.health);
// Call the isAlive function of the Enemy object. If the
// enemy is dead, exit.
// If the enemy is not dead, call the attack function and
// pass it the player object.
if (enemy.isAlive) {
console.log("\n" + enemy.name + " attacks "
+ player.name + "!");
enemy.attack(player);
} else {
return "enemyDead";
}
}
};
function Enemy() {
// The default enemy has a name of Enemy, health of 5, and
// strength of 2
this.name = "Enemy";
this.health = 5;
this.strength = 2;
}
// applyDamage takes an integer input and subtracts that from
// the enemy's health
Enemy.prototype.applyDamage = function(damage) {
console.log(this.name + " is hit with " + damage
+ " damage.");
this.health -= damage;
};
// isAlive checks if the enemy's health is greater than 0.
// Returns true if it is and false if not.
Enemy.prototype.isAlive = function() {
if (this.health > 0) {
return true;
} else {
return false;
}
};
// attack takes a player input and calls the applyDamage of
// the player using enemy's strength as input
Enemy.prototype.attack = function(player) {
//console.log("\n" + this.name + " attacks!");
player.applyDamage(this.strength);
};
function BattleSimulation() {
// The battle simulation has an array of players and enemies
this.players = [];
this.enemies = [];
}
// createEnemies uses a loop to create 20 Enemy instances and
// populate the Enemies array property
BattleSimulation.prototype.createEnemies = function() {
for (var i = 0; i < 20; i++) {
this.enemies.push(new Enemy());
}
};
// createPlayers creates 8 weapons objects and 5 player
// instances.
BattleSimulation.prototype.createPlayers = function() {
// Create 8 weapons objects in weaponsCache
var w1 = new Weapon('Marshmallows');
var w2 = new Weapon('Snowflakes');
var w3 = new Weapon('The love you didn\'t get as a child');
var w4 = new Weapon('Machine guns');
var w5 = new Weapon('Paper cuts');
var w6 = new Weapon('A really tough personal trainer');
var w7 = new Weapon('Stepping on a lego');
var w8 = new Weapon('Very short vampires');
var weaponsCache = [w1, w2, w3, w4, w5, w6, w7, w8];
// Create 5 player instances and add to the players array
var p1 = new Player('Kate', weaponsCache);
var p2 = new Player('Charming Male Companion', weaponsCache);
var p3 = new Player('Iron Professor', weaponsCache);
var p4 = new Player('Golden Army Captain', weaponsCache);
var p5 = new Player('Lieutenant Hadrian', weaponsCache);
this.players = [p1, p2, p3, p4, p5];
return this.players;
};
// run the battle
BattleSimulation.prototype.run = function() {
console.log("Simulating Battle");
// Create enemies
var enemies = this.createEnemies();
// Create players
var players = this.createPlayers();
var enemyBodyCount = 0;
var playerBodyCount = 0;
// Until all the players are dead or all the enemies die
do {
// Select random player
var myPlayer = players[Math.ceil(Math.random() * 5)];
// Pick a new player if dead
while (myPlayer.isAlive) {
myPlayer = players[Math.ceil(Math.random() * 5)];
}
console.log("\nNew fight!");
console.log("Your fighter is: " + myPlayer.name);
// Select a random enemy
var myEnemy = this.enemies[Math.ceil(Math.random() * 20)];
// Check if the enemy selected is alive. Pick a new enemy if dead.
while (myEnemy.isAlive==false) {
myEnemy = this.enemies[Math.ceil(Math.random() * 20)];
}
console.log("Your enemy is: " + myEnemy.name + ", with " + myEnemy.health + " health");
// Call the attackWith method on the player to get a weapon to attack with
var myWeapon = myPlayer.attackWith();
console.log("Your weapon is: " + myWeapon.name);
// Call the attack method on the weapon and pass it the current player and current enemy
var whosDead = myWeapon.attack(myPlayer, myEnemy);
if (whosDead == "enemyDead") {
enemyBodyCount++;
} else {
playerBodyCount++;
}
// let enemyBodyCount = 0;
// for (let i = 0; i < 20; i++) {
// if (enemies[i].isAlive <= 0) {
// enemyBodyCount++;
// console.log(enemyBodyCount);
// }
// }
// let playerBodyCount = 0;
// for (let i = 0; i < 5; i++) {
// if (this.players[i].isAlive <= 0) {
// console.log(players[i]);
// playerBodyCount++;
// console.log(playerBodyCount);
// }
// }*/
if (playerBodyCount >= 6) {
console.log("\nSorry, Scarlett Byte has defeated you and conquered the free world.");
}
if (enemyBodyCount >=20) {
console.log("\nCongratulations, you have defeated Scarlett Byte");
}
else {
continue;
}
} while (playerBodyCount < 6 || enemyBodyCount < 21);
//console.log(players);
//console.log(enemies);
};
// Test program
var simulator = new BattleSimulation();
simulator.run();
功能播放器(姓名、武器){
//每个玩家都有一个名字,初始生命值为10,一个
//初始强度为2,以及一系列武器对象
this.name=名称;
这个健康指数=10;
这个强度=2;
这个。武器=武器;
}
//applyDamage对玩家造成伤害-取整数
//输入并从玩家的健康状况中减去
Player.prototype.applyDamage=功能(损坏){
console.log(伤害+“应用伤害!”);
//从玩家的健康中减去伤害
这是健康-=损害;
log(this.name+“\”的运行状况现在是“+this.health”);
};
//isAlive检查玩家的健康状况是否>0。返回true
//如果是,如果不是,则为假。
Player.prototype.isAlive=函数(){
如果(this.health>0){
返回true;
}否则{
返回false;
}
};
//attackWith使用介于7和0之间的随机数,选择
//武器在该索引处,并返回武器
Player.prototype.attackWith=函数(){
让choice=Math.ceil(Math.random()*(7));
归还这个。武器[选择];
};
功能武器(名称){
//每种武器都有一个指定的名称和随机伤害等级
this.name=名称;
this.damage=Math.ceil(Math.random()*5);
//介于1和5之间的随机数
}
//攻击检查战斗机是否死亡,然后施加伤害
//以实力和武器为基础
武器.prototype.attack=功能(玩家、敌人){
while(player.isAlive&&friend.isAlive){
//计算实际损失=
//玩家力量*武器伤害值
让actualDamage=player.strength*this.damage;
console.log(“\n”+player.name+“攻击”+敌人.name
+ "!");
//调用敌方对象的applyDamage函数并
//通过计算的实际损坏值
敌人。应用伤害(实际伤害);
console.log(“敌方生命值为”+敌方生命值);
//调用敌方对象的isAlive函数。如果
//敌人死了,退出。
//如果敌人没有死亡,调用攻击功能并
//将其传递给玩家对象。
如果(敌方现场){
console.log(“\n”+敌方.name+”攻击”
+player.name+“!”;
敌人。攻击(玩家);
}否则{
返回“enemyDead”;
}
}
};
功能敌人(){
//默认敌人的名称为敌人,生命值为5,和
//强度2
this.name=“敌人”;
这意味着健康=5;
这个强度=2;
}
//applyDamage接受整数输入并从中减去
//敌人的健康
敌方.prototype.applyDamage=功能(损害){
console.log(this.name+)被“+伤害”击中
+“损害。”);
这是健康-=损害;
};
//isAlive检查敌人的生命值是否大于0。
//如果是,则返回true;如果不是,则返回false。
defey.prototype.isAlive=函数(){
如果(this.health>0){
返回true;
}否则{
返回false;
}
};
//攻击接受玩家输入并调用的applyDamage
//使用敌人力量作为输入的玩家
敌方.prototype.attack=功能(玩家){
//console.log(“\n”+this.name+“攻击!”);
玩家。应用伤害(这个。力量);
};
功能模拟(){
//战斗模拟有一系列玩家和敌人
这个.players=[];
此参数为[1];
}
//CreateEquires使用循环创建20个敌人实例和
//填充数组属性
BattleSimulation.prototype.CreateEquires=函数(){
对于(变量i=0;i<20;i++){
这个。敌人。推(新敌人());
}
};
//CreatePlayer创建8个武器对象和5个玩家
//实例。
BattleSimulation.prototype.createPlayers=函数(){
//在武器装备库中创建8个武器对象
var w1=新武器(“棉花糖”);
var w2=新武器(“雪花”);
var w3=新武器(“你小时候没有得到的爱”);
var w4=新武器(“机枪”);
var w5=新武器(“剪纸”);
var w6=新武器(“一个非常强硬的私人教练”);
var w7=新武器(“踩在乐高上”);
var w8=新武器(“极短吸血鬼”);
var weaponsCache=[w1,w2,w3,w4,w5,w6,w7,w8];
//创建5个玩家实例并添加到玩家阵列
变量p1=新玩家(“凯特”,武器装备);
变量p2=新玩家(“迷人的男性伴侣”,武器装备);
var p3=新玩家(“铁教授”,武器装备);
var p4=新玩家(“金军队长”,武器装备);
var p5=新玩家(“哈德良中尉”,武器装备);
this.players=[p1,p2,p3,p4,p5];
归还这个。玩家;
};
//作战
BattleSimulation.prototype.run=函数(){
控制台日志(“模拟战斗”);
//树敌
var-friends=this.createfriends();
//创建玩家
var players=this.createPlayers();
var enemyBodyCount=0;
var playerBodyCount=0;
//直到所有玩家死亡或所有敌人死亡
做{
//选择随机游戏者
var myPlayer=players[Math.ceil(Math.random()