javascript - 无法在基于 JavaScript 的游戏中初始化全局变量

标签 javascript variables global-variables phaser-framework

我有一个基于 flappybird 的克隆游戏,我需要为其制作一个高分功能。高分瞬间消失,因为游戏重新加载,我不知道如何将高分设置为全局变量。如果您想查看的话,这是链接。 (警告:降低耳机音量)

http://www.theindependentwolf.com/game/flappyWolf.html

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');

// Creates a new 'main' state that will contain the game
var mainState = {


// Function called first to load all the assets
preload: function() { 
    // Change the background color of the game
//         game.stage.backgroundColor = '#71c5cf';
    //background Image
    game.load.image('woods', 'woods.jpg');      

    // Load the bird sprite
    game.load.image('bird', 'whiteWolf2.png');  

    // Load the pipe sprite
    game.load.image('pipe', 'pipe.png');    


},

// Fuction called after 'preload' to setup the game 
create: function() { 
    // Set the physics system
    game.physics.startSystem(Phaser.Physics.ARCADE);

    game.add.tileSprite(0, 0, 400, 490, 'woods');


    // Display the bird on the screen
    this.bird = this.game.add.sprite(100, 245, 'bird');

    // Add gravity to the bird to make it fall
    game.physics.arcade.enable(this.bird);
    this.bird.body.gravity.y = 1000; 

    // Call the 'jump' function when the spacekey is hit
    var spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spaceKey.onDown.add(this.jump, this); 

    // Create a group of 20 pipes
    this.pipes = game.add.group();
    this.pipes.enableBody = true;
    this.pipes.createMultiple(20, 'pipe');  

    // Timer that calls 'addRowOfPipes' ever 1.5 seconds
    this.timer = this.game.time.events.loop(1500, this.addRowOfPipes, this);           

    // Add a score label on the top left of the screen
    this.score = 0;
    this.hiScore = 0;

    this.scoreLabel = this.game.add.text(20, 20, "Score: ", { font: "30px Arial", fill: "#ffffff" }); 
    this.labelScore = this.game.add.text(120, 20, "0", { font: "30px Arial", fill: "#ffffff" }); 

    this.hiScoreLabel = this.game.add.text(200, 20, "Hi Score: ", { font: "30px Arial", fill: "#ffffff" }); 
    labelHiScore = this.game.add.text(340, 20, "0", { font: "30px Arial", fill: "#ffffff" });   




        /*
    Code for the pause menu
*/




},

// This function is called 60 times per second
update: function() {
    // If the bird is out of the world (too high or too low), call the 'restartGame' function
    if (this.bird.inWorld == false)
        this.restartGame(); 

    // If the bird overlap any pipes, call 'restartGame'
    game.physics.arcade.overlap(this.bird, this.pipes, this.restartGame, null, this);              
},

// Make the bird jump 
jump: function() {
    // Add a vertical velocity to the bird
    this.bird.body.velocity.y = -350;
},

// Restart the game
restartGame: function() {
    // Start the 'main' state, which restarts the game

    if(this.score > this.hiScore ){
            labelHiScore.text = this.score;  
    }                

    game.state.start('main');
},

// Add a pipe on the screen
addOnePipe: function(x, y) {
    // Get the first dead pipe of our group
    var pipe = this.pipes.getFirstDead();

    // Set the new position of the pipe
    pipe.reset(x, y);

    // Add velocity to the pipe to make it move left
    pipe.body.velocity.x = -200; 

    // Kill the pipe when it's no longer visible 
    pipe.checkWorldBounds = true;
    pipe.outOfBoundsKill = true;
},

// Add a row of 6 pipes with a hole somewhere in the middle
addRowOfPipes: function() {
    var hole = Math.floor(Math.random()*5)+1;

    for (var i = 0; i < 8; i++)
        if (i != hole && i != hole +1) 
            this.addOnePipe(400, i*60+10);   

    this.score += 1;
    this.labelScore.text = this.score;  
},


};

// Add and start the 'main' state to start the game

    game.state.add('main', mainState);  
// document.getElementById("#startButton").onclick(function(){
//  alert("Hi");
    labelHiScore = 0;
    game.state.start('main'); 
// }); 

最佳答案

尝试进行以下更改:

在restartGame方法中:

restartGame: function() {
    if(this.score > localStorage.getItem("hiScore") ){
            localStorage.setItem("hiScore", this.score); 
            this.labelHiScore.text = localStorage.getItem("hiScore");  
    }        
    game.state.start('main');
},

在“labelHiScore”变量声明中:

this.labelHiScore = this.game.add.text(340, 20, ("hiScore" in localStorage ? localStorage.getItem("hiScore") : "0"), { font: "30px Arial", fill: "#ffffff" });  

简而言之,我希望您明白问题是什么

在 restartGame 方法中,您尝试将分数分配给窗口作用域变量而不是函数作用域。 加上“这个”。将在当前对象中查找变量。

还将分数添加到本地存储以保留高分,并在游戏重新加载时从本地存储中选取值。

关于javascript - 无法在基于 JavaScript 的游戏中初始化全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715892/

相关文章:

在任何情况下都运行代码的Javascript switch case?

c - 在 C 中的变量上使用 'printf'

javascript - 为什么我的 Controller 中的保存功能不起作用?

javascript - Javascript 中 DOM 的 onchange 不起作用

c - C 编程中的 p 符号是什么?

c++ - 将全局常量作为 'this' 参数传递会丢弃限定符

Node.js:将标准输出捕获到字符串变量中的最简单方法

python - 在python中使用多处理时全局列表不更新

javascript - 为生产、开发、发布设置单独的变量值

c - 从c中的控制台窗口读取变量