Day 5: Managing Game State and Scoring #GameState #PhaserScoring

Game state and scoring systems are essential for tracking player progress and making the gameplay engaging. On Day 5, we’ll build a basic game state to manage player lives and scores, and we’ll display them dynamically on the game screen.


1. Understanding Game State in Phaser

A game state tracks information like:

  • Player properties: Lives, health, or energy.
  • Game progress: Level, score, or achievements.
  • Dynamic events: Timers, enemies spawned, or power-ups.

Phaser allows you to use global or scene-specific variables to maintain this data.


2. Setting Up the Game State

Step 1: Define the State Variables

In Game.js, initialize the state variables in the create method:

create() {
    this.playerScore = 0;
    this.playerLives = 3;

    // Display score and lives
    this.scoreText = this.add.text(10, 10, `Score: ${this.playerScore}`, {
        fontSize: '20px',
        color: '#ffffff',
    });

    this.livesText = this.add.text(10, 40, `Lives: ${this.playerLives}`, {
        fontSize: '20px',
        color: '#ffffff',
    });
}

3. Updating the Score

Step 1: Add a Method to Update the Score

Create a reusable method to update the score:

updateScore(points) {
    this.playerScore += points;
    this.scoreText.setText(`Score: ${this.playerScore}`);
}

Step 2: Trigger Score Updates

Simulate scoring events, like collecting an item:

create() {
    this.playerScore = 0;
    this.scoreText = this.add.text(10, 10, `Score: ${this.playerScore}`, {
        fontSize: '20px',
        color: '#ffffff',
    });

    // Add a collectible object
    this.item = this.add.circle(400, 300, 10, 0xff0000).setInteractive();

    this.item.on('pointerdown', () => {
        this.updateScore(10); // Increment score by 10
        this.item.destroy(); // Remove the collectible
    });
}

4. Managing Player Lives

Step 1: Add a Method to Update Lives

Create a reusable method to decrement lives:

updateLives(change) {
    this.playerLives += change;
    this.livesText.setText(`Lives: ${this.playerLives}`);

    if (this.playerLives <= 0) {
        this.endGame();
    }
}

Step 2: Simulate Losing Lives

Simulate events where the player loses a life:

create() {
    this.playerLives = 3;
    this.livesText = this.add.text(10, 40, `Lives: ${this.playerLives}`, {
        fontSize: '20px',
        color: '#ffffff',
    });

    // Simulate losing a life after 5 seconds
    this.time.delayedCall(5000, () => {
        this.updateLives(-1); // Decrement lives by 1
    });
}

Step 3: Handle Game Over

Define the endGame method:

endGame() {
    this.add.text(400, 300, 'Game Over', {
        fontSize: '48px',
        color: '#ff0000',
    }).setOrigin(0.5);

    this.scene.pause(); // Pause the game
}

5. Integrating with React Native

Update the WebView in App.js:

Modify the phaserHTML to include the game state logic:

const phaserHTML = `
    <html>
        <head>
            <script src="https://cdn.jsdelivr.net/npm/phaser@3/dist/phaser.min.js"></script>
            <script>
                const config = {
                    type: Phaser.AUTO,
                    width: 800,
                    height: 600,
                    backgroundColor: '#2d2d2d',
                    scene: {
                        preload: function () {},
                        create: function () {
                            this.playerScore = 0;
                            this.playerLives = 3;

                            // Display score and lives
                            this.add.text(10, 10, 'Score: 0', { fontSize: '20px', color: '#fff' });
                            this.add.text(10, 40, 'Lives: 3', { fontSize: '20px', color: '#fff' });

                            // Add collectible
                            const item = this.add.circle(400, 300, 10, 0xff0000).setInteractive();
                            item.on('pointerdown', () => {
                                console.log('Score +10');
                                item.destroy();
                            });
                        },
                        update: function () {}
                    },
                };
                new Phaser.Game(config);
            </script>
        </head>
        <body></body>
    </html>
`;

6. Running the Game

Step 1: Start the Development Server

npm start

Step 2: Test on a Mobile Device

  • Test scoring by interacting with objects.
  • Verify that the lives counter decreases and triggers a game-over state.
See also  Day 10: Deploying a Machine Learning-Powered App

7. Key Concepts Covered

  • Managing game state with global variables.
  • Updating text objects dynamically for scores and lives.
  • Handling game-over conditions with scene.pause().

Next Steps

On Day 6, we’ll expand the game by adding levels and game progression to make the gameplay more challenging and engaging.

References and Links:

SEO Keywords: Phaser game state, scoring in Phaser, managing player lives, React Native game integration, game-over logic in Phaser.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.