我正在开发一个基于文本的游戏,我有一个函数(turn()
),可以根据用户按下的按钮来确定用户的操作。
但每次按下3个按钮中的一个时,控制台会显示TypeError: number is not a function
。
我尝试了很多操作(例如将我的所有脚本移动到一个文件中,全局定义游戏变量,以及更改函数的顺序),但它仍然不起作用!
任何帮助?
JavaScript代码:
console.log("Resetting resources...");
var turn = 1;
var player = {
damage: Math.floor(Math.random() * 4 + 2), //Deals 2 to 5 damage
healing: Math.floor(Math.random() * 4 + 3), //Heals 3 to 6 health
health: null,
maxHP: 25, //Maximum health (not recommended to change)
special: true,
alive: true
};
var dragon = {
damage: Math.floor(Math.random() * 6 + 1), //Deals 1 to 6 damage
health: null,
maxHP: 28, //Maximum health (not recommended to change)
alive: true
};
player.health = player.maxHP;
dragon.health = dragon.maxHP;
console.log("Resources ready!");
function turn() {
if (player.alive) {
/*Player turn*/
console.log("---------------TURN " + turn + " : PLAYER---------------");
alert("The dragon is still alive!");
console.log("Player HP: " + player.health + "/" + player.maxHP);
switch (action) {
case '1':
console.log("Dealt " + player.damage + " damage!");
dragon.health -= player.damage;
if (dragon.health <= 0) {
alert("The dragon has been slain!");
console.log("---------------DRAGON SLAIN---------------");
dragon.alive = false;
player.alive = false;
}
break;
case '2':
console.log("Recovered " + player.healing + " health!");
player.health += player.healing;
break;
case '3':
alert("Scared of dying, you ditch the scene before you become human toast.");
console.log("---------------PLAYER SURRENDERS---------------");
player.alive = false;
break;
default:
console.error("Random error occured.");
break;
}
/*Reset RNG*/
player.damage = Math.floor(Math.random() * 4 + 2);
player.healing = Math.floor(Math.random() * 4 + 3);
/*Dragon turn*/
console.log("---------------TURN " + turn + " : DRAGON---------------");
console.log("Dragon HP: " + dragon.health + "/" + dragon.maxHP);
console.log("Dealt " + dragon.damage + " damage!");
player.health -= dragon.damage;
if (player.health <= 0) {
alert("You have died!");
console.log("---------------PLAYER DIES---------------");
player.alive = false;
}
/*Reset RNG*/
dragon.damage = Math.floor(Math.random() * 6 + 1);
turn++;
} else if (!player.alive && dragon.alive) {
alert("You have died!\nGAME OVER\nReset the game to play again.");
} else if (!dragon.alive) {
alert("You have slain the dragon!\nGAME OVER\nReset the game to play again.");
}
}
function attack() {
turn('1'); //Error occurs here
}
function heal() {
turn('2'); //and here
}
function flee() {
turn('3'); // and here
}
<button onclick="attack()">Attack</button>
<button onclick="heal()">Heal</button>
<button onclick="flee()">Flee!</button>
答案 0 :(得分:1)
您将turn
定义为脚本开头的变量:var turn = 1;
。
然后您尝试将其重新定义为函数:function turn() { ... }
。
“问题”是JavaScript将函数定义放在块的开头,在变量定义之后但在变量赋值之前,所以实际上你的JavaScript代码将被解释为:
var turn;
function turn() { ... }
turn = 1;
最终结果是turn
是一个数字(1
)而且这不是一个函数,因此您无法使用turn('1')
调用它。