자바 스크립트 기반 게임에서 전역 변수를 초기화 할 수 없습니다.

user3525357

나는 flappy bird 기반 복제 게임을 가지고 있으며 그것에 대한 높은 점수 기능을 만들어야합니다. 게임이 다시로드되고 High Score를 전역 변수로 설정하는 방법을 모르기 때문에 최고 점수는 순식간에 사라집니다. 당신이 그것을보고 싶다면 여기에 링크가 있습니다. (경고 : 헤드폰 볼륨 낮추기)

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'); 
// }); 
ngChaitanya

다음 변경 사항을 시도하십시오.

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 메서드에서 기능 범위 대신 창 범위 변수에 점수를 할당하려고합니다. "이"를 추가합니다. 현재 개체에서 변수를 찾습니다.

또한 최고 점수를 유지하고 게임이 다시로드 될 때 로컬 저장소에서 값을 선택하기 위해 로컬 저장소에 점수를 추가했습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

자바 스크립트 전역 배열을 기록 할 수 없습니다.

분류에서Dev

자바 스크립트와 함께 Firebase를 사용할 때 '초기화 전에'firebase '에 액세스 할 수 없습니다.'오류가 발생합니다.

분류에서Dev

자바 스크립트에서 기능을 반복 할 수 없습니다.

분류에서Dev

자바 스크립트 런타임 오류 : 초기화 전에 대화 상자에서 메서드를 호출 할 수 없습니다. '닫기'를 호출하려고했습니다.

분류에서Dev

자바 스크립트는 전역 변수를 호출 할 수 없습니다.

분류에서Dev

초기화되지 않은 함수의 전역 변수 값에 액세스 할 수 없습니다.

분류에서Dev

i3 exec 스크립트에 대한 환경 변수를 초기화 할 수 없습니다.

분류에서Dev

자바 스크립트 기능에 액세스 할 수 없습니다.

분류에서Dev

자바 스크립트는 함수 내에서 전역 개체를 재정의 할 수 없습니다.

분류에서Dev

eslint는 자바 스크립트의 #include 전 처리기 지시문에 대처할 수 없습니다.

분류에서Dev

ssh를 통해 원격 호스트에서 초기화 스크립트를 실행할 수 없습니다.

분류에서Dev

SSH를 통해 원격 호스트에서 초기화 스크립트를 실행할 수 없습니다.

분류에서Dev

초기화 전에 'X'에 액세스 할 수 없습니다.

분류에서Dev

초기화 전에 'variableName'에 액세스 할 수 없습니다.

분류에서Dev

페이지가로드 될 때마다 전역 자바 스크립트 변수가 초기화되지 않도록하려면 어떻게해야합니까?

분류에서Dev

전역 개체를 초기화 할 수 없습니다.

분류에서Dev

연결하기 전에 자바 스크립트 문자열 변수를 초기화해야하는 이유

분류에서Dev

자바 스크립트의 기본 클래스에 초기화 매개 변수를 전달하는 방법

분류에서Dev

자바 스크립트는 함수간에 매개 변수를 전달할 수 없습니다.

분류에서Dev

자바 스크립트가 요소에서 찾기를 적용 할 수 없습니다.

분류에서Dev

자바 스크립트 조회 테이블이 초기화 전후에 함수를 실행합니까?

분류에서Dev

Django-Django 양식의 ID를 자바 스크립트 변수에 전달할 수 없습니다.

분류에서Dev

자바 스크립트에 서식을 전달할 수 없습니다.

분류에서Dev

Firefox에서 초기화 스크립트를로드 할 수 있습니까?

분류에서Dev

Matlab 스크립트는 다른 열의 값을 기반으로 범주 형 변수를 올바르게 계산할 수 없습니다.

분류에서Dev

어떻게 매개 변수로 자바 스크립트 ES6 화살표 기능을 전달할 수 있습니다

분류에서Dev

전역 변수는 항상 자바 스크립트 함수를 호출하기 전에 생성 되나요?

분류에서Dev

이 자바 스크립트 계산기에 줄 바꿈을 추가 할 수 없습니다.

분류에서Dev

소파베이스의 자바 스크립트보기 기능에 매개 변수 (Java로 작업 중)를 전달할 수 있습니까?

Related 관련 기사

  1. 1

    자바 스크립트 전역 배열을 기록 할 수 없습니다.

  2. 2

    자바 스크립트와 함께 Firebase를 사용할 때 '초기화 전에'firebase '에 액세스 할 수 없습니다.'오류가 발생합니다.

  3. 3

    자바 스크립트에서 기능을 반복 할 수 없습니다.

  4. 4

    자바 스크립트 런타임 오류 : 초기화 전에 대화 상자에서 메서드를 호출 할 수 없습니다. '닫기'를 호출하려고했습니다.

  5. 5

    자바 스크립트는 전역 변수를 호출 할 수 없습니다.

  6. 6

    초기화되지 않은 함수의 전역 변수 값에 액세스 할 수 없습니다.

  7. 7

    i3 exec 스크립트에 대한 환경 변수를 초기화 할 수 없습니다.

  8. 8

    자바 스크립트 기능에 액세스 할 수 없습니다.

  9. 9

    자바 스크립트는 함수 내에서 전역 개체를 재정의 할 수 없습니다.

  10. 10

    eslint는 자바 스크립트의 #include 전 처리기 지시문에 대처할 수 없습니다.

  11. 11

    ssh를 통해 원격 호스트에서 초기화 스크립트를 실행할 수 없습니다.

  12. 12

    SSH를 통해 원격 호스트에서 초기화 스크립트를 실행할 수 없습니다.

  13. 13

    초기화 전에 'X'에 액세스 할 수 없습니다.

  14. 14

    초기화 전에 'variableName'에 액세스 할 수 없습니다.

  15. 15

    페이지가로드 될 때마다 전역 자바 스크립트 변수가 초기화되지 않도록하려면 어떻게해야합니까?

  16. 16

    전역 개체를 초기화 할 수 없습니다.

  17. 17

    연결하기 전에 자바 스크립트 문자열 변수를 초기화해야하는 이유

  18. 18

    자바 스크립트의 기본 클래스에 초기화 매개 변수를 전달하는 방법

  19. 19

    자바 스크립트는 함수간에 매개 변수를 전달할 수 없습니다.

  20. 20

    자바 스크립트가 요소에서 찾기를 적용 할 수 없습니다.

  21. 21

    자바 스크립트 조회 테이블이 초기화 전후에 함수를 실행합니까?

  22. 22

    Django-Django 양식의 ID를 자바 스크립트 변수에 전달할 수 없습니다.

  23. 23

    자바 스크립트에 서식을 전달할 수 없습니다.

  24. 24

    Firefox에서 초기화 스크립트를로드 할 수 있습니까?

  25. 25

    Matlab 스크립트는 다른 열의 값을 기반으로 범주 형 변수를 올바르게 계산할 수 없습니다.

  26. 26

    어떻게 매개 변수로 자바 스크립트 ES6 화살표 기능을 전달할 수 있습니다

  27. 27

    전역 변수는 항상 자바 스크립트 함수를 호출하기 전에 생성 되나요?

  28. 28

    이 자바 스크립트 계산기에 줄 바꿈을 추가 할 수 없습니다.

  29. 29

    소파베이스의 자바 스크립트보기 기능에 매개 변수 (Java로 작업 중)를 전달할 수 있습니까?

뜨겁다태그

보관