设置变量时游戏代码中断

时间:2016-05-09 11:22:04

标签: javascript variables

这个游戏代码看起来不错,但它不起作用:

//Get canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

//Capture keypresses
var keys = [];
document.onKeyDown = function (e) {keys[e.keyCode] = true;};
document.onKeyUp = function (e) {keys[e.keyCode] = false;};

//Set game variables
var characters;
characters.charList = [];
var player = {};

//Character constructor
function Character (Name, Strength, Speed, Intelligence, Reflexes, Age, Height, Weight, Weapon, UsesMagic, MagicType, Armor, Hair, Eyes, Skin, Clothes, Species, Type, Accessories) {
        this.name = Name;
        this.strength = Strength;
    this.speed = Speed;
    this.intelligence = Intelligence;
    this.reflexes = Reflexes;
    this.age = Age;
    this.height = Height;
    this.weight = Weight;
    this.weapon = Weapon;
    this.usesMagic = UsesMagic;
    this.magicType = MagicType;
    this.armor = Armor;
    this.hair = Hair;
    this.eyes = Eyes;
    this.skin = Skin;
    this.clothes = Clothes;
    this.species = Species;
    this.type = Type;
    if (Accessories) {
            this.accessories = Accessories;
    }
    characters.charList[characters.charList.length] = Name;
}

characters.Xantar = new Character('Xantar', 1, 1, 1, 1, 1, 1, 1, 'sword', true, 'derp', [], 'hair is brown\?', 'duh', 'foo', [], 'animale', 'wolf', []);
alert(characters.Xantar.weapon + '   ' + characters[0].type);

//Activate mainloop and get value for pausing purposes
var mainloopInterval = setInterval(mainloop, 5);
//Main game loop
function mainloop(){

}

该计划似乎停在:

characters.charList = [];

我根本就没有在这里看到问题。这是相关的HTML:

<canvas id='canvas' style='border:1px solid black;'>Your browser does not support canvas. Please update your browser.</canvas>

注意:我在JSFiddle上运行它。 如果有人能在这里帮助我,我将非常感激。 以下是链接:https://jsfiddle.net/q6vdph1p/14/

3 个答案:

答案 0 :(得分:2)

需要将其设置为对象var characters = {};

答案 1 :(得分:2)

  1. 变量&#34;字符&#34;必须是一个对象。 var characters = {};
  2. charList不应该用&#34; var&#34;初始化。关键字,因为它不是新变量,因此它只是characters.charList = [];
  3. 在第42行,它不是characters[0].type,而是characters.Xantar.type JSFiddle

答案 2 :(得分:1)

如前所述,您需要先为characters变量指定一个对象,然后才能访问其中的属性。

只需使用var characters;声明它就会为其分配undefined的值并尝试访问undefined.charList并为其分配一个空数组将失败。

更正确,失败和可读的方式来声明它将构建空数据结构,如下所示:

var characters = {
    charList: []
};

此外,使用array.push()添加到数组末尾比使用array.length索引更安全,即

characters.charList.push(Name);

而不是

characters.charList[characters.charList.length] = Name;