简体   繁体   English

Javascript游戏,数组和对象文字

[英]Javascript game, array and object literals

I'm working on a game for Windows 8 in HTML5 and JavaScript. 我正在使用HTML5和JavaScript开发适用于Windows 8的游戏。 I have a working version of the game that stores "roach" objects in an array. 我有一个可以在阵列中存储“蟑螂”对象的游戏的工作版本。 I am trying to put the game code i have into a sample from Microsoft ( linked here ). 我试图将我拥有的游戏代码放入Microsoft的示例中( 链接到此处 )。 In this example they decalere a set of object literals for the game state that are saved and used in various classes: 在此示例中,它们对游戏状态的一组对象常量进行了十进制处理,并在各个类中进行了保存和使用:

internal: {
    gamePaused: false,
    gamePhase: "ready",
    speed: 5,
    score: 0,
}

In there I would like to put the array for my roach objects. 在这里,我想为我的蟑螂对象放置数组。 I thought I could do: 我以为我可以:

roaches: [],

but when I call: 但是当我打电话时:

this.state.roaches.push(new Roach());
this.state.roaches.length;

I get a: 我得到:

JavaScript runtime error: Unable to get property 'length' of undefined or null reference

What am I doing wrong and how can I fix it? 我在做什么错,我该如何解决?

Nat 纳特

additional info: 附加信息:

alright so here is my roach class: 好了,这是我的蟑螂课:

var Roach = WinJS.Class.define( function () {
    this.position.x = Math.random() * gameCanvas.width + 1;
    this.position.y = Math.random() * gameCanvas.height + 1;
    this.squished = false;
    this.image = GameManager.assetManager.assets.roachImage;
},
{
    move: function (speed) {
        // changes position
    },
    squish: function() {

    }
});

this is in a file called game.js which contains another class: 这在一个名为game.js的文件中,该文件包含另一个类:

var Game = WinJS.Class.define(
    null,
{
// other functions
// Called when the game is being prepared to start
    ready: function () {
        // TODO: Replace with your own new game initialization logic
        if (this.isSnapped()) {
            this.state.gamePaused = true;
        } else {
            this.state.gamePaused = false;
        }
        this.state.gamePhase = "ready";
        switch (this.settings.skillLevel) {
            case 0:
                this.state.speed = 3;
                break;
            case 1:
                this.state.speed = 5;
                break;
            case 2:
                this.state.speed = 10;
                break;
        }
        this.state.roaches.push(new Roach());
        this.state.score = 0;
    },
// Main game render loop
    draw: function () {
        this.gameContext.clearRect(0, 0, gameCanvas.width, gameCanvas.height);

        // TODO: Sample game rendering to be replaced

        // Draw the current score
        this.gameContext.fillStyle = "#FFFF99";
        this.gameContext.font = "bold 48px Segoe UI";
        this.gameContext.textBaseline = "middle";
        this.gameContext.textAlign = "right";
        this.gameContext.fillText(this.state.score, gameCanvas.width - 5, 20);

        // update image positions
        // THROWS ERROR HERE
        for (var i = 0; i < this.state.roaches.length; i++) {
            if (!this.state.roaches[i].squished) {

            }
        }

        // Draw a ready or game over or paused indicator
        if (this.state.gamePhase === "ready") {
            this.gameContext.textAlign = "center";
            this.gameContext.fillText("READY", gameCanvas.width / 2, gameCanvas.height / 2);
        } else if (this.state.gamePhase === "ended") {
            this.gameContext.textAlign = "center";
            this.gameContext.fillText("GAME OVER", gameCanvas.width / 2, gameCanvas.height / 2);
        } else if (this.state.gamePaused) {
            this.gameContext.textAlign = "center";
            this.gameContext.fillText("PAUSED", gameCanvas.width / 2, gameCanvas.height / 2);
        }
    }

Now in a file called gameState.js a gameState class is defined that holds the variables that I referenced earlier. 现在,在名为gameState.js的文件中,定义了一个gameState类,该类包含我之前引用的变量。

var GameState = WinJS.Class.define(
    null,
{
    config: {
    // TODO: Adjust these values to configure the template itself
        frameRate: 20, // Set to 0 to have no update loop at all
        minSquished: 20,
        currentPage: "/html/homePage.html",
        gameName: "SDK Game Sample", // Used by share contract on scores page
    },

    // TODO: Replace these public settings exposed on the settings panel
    external: {
        playerName: "Player",
        soundVolume: 100,
        skillLevel: 0,
    },

    // TODO: Replace these values with state variables relevant for your game
    internal: {
        gamePaused: false,
        gamePhase: "ready",
        roaches: [],
        speed: 5,
        score: 0,
    },

These files are assembled under the GameManager namespace which calls each class from the files and creates them under that namespace. 这些文件在GameManager命名空间下进行组装,该命名空间从文件中调用每个类并在该命名空间下创建它们。 So when the user starts the game the ready function is called by the GameManager and then the draw function is called to update the screen. 因此,当用户启动游戏时,GameManager将调用ready函数,然后调用draw函数以更新屏幕。 Hopefully this helps clarify. 希望这有助于澄清。

the namespace is defined here: 命名空间在这里定义:

 var game = new Game();
 var touchPanel = new TouchPanel();
 var state = new GameState();
 state.load();

WinJS.Namespace.define("GameManager", {
        navigateHome: navigateHome,
        navigateGame: navigateGame,
        navigateRules: navigateRules,
        navigateScores: navigateScores,
        navigateCredits: navigateCredits,
        showPreferences: showPreferences,
        onBeforeShow: onBeforeShow,
        onAfterHide: onAfterHide,
        game: game,
        state: state,
        assetManager: assetManager,
        scoreHelper: scoreHelper,
        gameId: gameId,
        touchPanel: touchPanel
    });

I had a similar issue with writing to object literals then reading back the data and getting an error. 在写入对象文字然后读取数据并得到错误时,我遇到了类似的问题。 Apparently, this is a gray area in two instances: 显然,这是两个实例中的灰色区域:

  1. The key/value pair is added using dot notation 键/值对使用点表示法添加
  2. The object literal is accessed asynchronously 对象文字可以异步访问

In the first case, the spec doesn't guarantee that the read operation will work. 在第一种情况下,规范不能保证读取操作会起作用。 In the second case, you have to handle the access via: 在第二种情况下,您必须通过以下方式处理访问:

  • multiple callbacks 多个回调
  • a callback which handles multiple data types 处理多种数据类型的回调

You can test it with a simple one liner: 您可以使用一个简单的衬纸进行测试:

  var foo = {}; foo["bar"] = []; setTimeout(function(){foo.bar.push(new Date); console.log('Hi ' + foo.bar.length)}, 5000); 

References 参考文献

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM