我正在尝试学习后端语言和前端语言。
最近,我一直在努力实施Derek Banas' " OOPGame [C#教程第8号]"在JavaScript中。但是,代码返回' GetAttackResult未定义'当我使用节点解释器运行它时。
我该如何解决?
这是我的代码:
class Warrior
{
constructor(name, health)
{
this.name = name;
this.health = health;
}
Attack()
{
let attackValue = Math.round(Math.random * 50);
return attackValue;
}
Block()
{
let blockValue = Math.round(Math.random * 10);
return blockValue;
}
}
class Battle
{
StartFight(warrior1 , warrior2)
{
while (true)
{
if (GetAttackResult(warrior1, warrior2) == "Game Over")
{
console.log("Game Over");
break;
}
if (GetAttackResult(warrior2, warrior1) == "Game Over")
{
console.log("Game Over");
break;
}
}
}
GetAttackResult(warriorA, warriorB)
{
let warA_attack = warriorA.Attack();
let warB_block = warriorB.Block();
let dmg2warB = warA_attack - warB_block;
warriorB.health = warriorB.health - dmg2warB;
if (dmg2warB > 0)
{
console.log(`${warriorA.name} attacks ${warriorB.name} and deals ${dmg2warB} damage.`);
console.log(`${warriorB.name} has ${warriorB.health} health.\n`);
if (warriorB.health <= 0)
{
console.log(`${warriorB.name} has died and ${warriorA.name} is victorius`);
return "Game Over";
}
else return "Fight Again!";
}
}
}
Main();
function Main()
{
let apple = new Warrior("Apple", 3000);
let microsoft = new Warrior("Microsoft", 3000);
let hi = new Battle();
hi.StartFight(apple, microsoft);
}
运行它的输出:
[Running] node "i:\JSPractise\tempCodeRunnerFile.js"
i:\JSPractise\tempCodeRunnerFile.js:4
let apple = new Warrior("Apple", 3000);
^
ReferenceError: Warrior is not defined
at Main (i:\JSPractise\tempCodeRunnerFile.js:4:17)
at Object.<anonymous> (i:\JSPractise\tempCodeRunnerFile.js:1:63)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
[Done] exited with code=1 in 0.42 seconds
注意:我正在学习“Eloquent JavaScript”中的JS&#39;书,我密切关注它。另外,我使用&#39; Main()&#39;定义入口点b&#39;因为我来自C / C ++背景,我发现它很方便。
答案 0 :(得分:0)
在您的代码中,GetAttackResult
是方法。这意味着您可以将其作为通过new Battle
创建的实例的属性进行访问(通常为this
)。它不是一个独立的功能。
例如(见评论):
StartFight(warrior1 , warrior2)
{
while (true)
{
if (this.GetAttackResult(warrior1, warrior2) == "Game Over")
// ^^^^^
{
console.log("Game Over");
break;
}
if (this.GetAttackResult(warrior2, warrior1) == "Game Over")
// ^^^^^
{
console.log("Game Over");
break;
}
}
}
某些语言允许您离开this.
对字段和方法(Java,C#)的引用。 JavaScript没有。