Tag Archives: props

React Tips: 4 – Propagating State

One thing that’s worth remembering about React is that when you’re updating state, only the Render method gets re-executed.

It’s easy (as I did) to fall into the trap of doing something like this:

    const myStyle = {
        background: this.props.backgroundFlag == 1 ? "blue" : "yellow",
        display: 'inline-block',
        height: '100%',
    }

    public render() {
        return <>
            <div className="myDiv" style={myStyle}>
        </>
    }

Imagine that this.props.backgroundFlag is actually the state of the containing component; when you change it, you would expect your component to reflect your change. However, in the case above, what will actually happen is nothing – because only the render method is re-evaluated when the virtual DOM changes.

To correct this, you need whatever needs to be re-evaluated inside the render method; for example:

    public render() {
	    const myStyle = {
	        background: this.props.backgroundFlag == 1 ? "blue" : "yellow",
	        display: 'inline-block',
	        height: '100%',
	    }

        return <>
            <div className="myDiv" style={myStyle}>
        </>
    }

Creating a Car Game in React – Part 5 – Levels and Time

This is the fifth part of a series (that began here).

In the last post, we added the concept of score. The car now can collect cups while avoiding trees; however, we don’t have any concept of what happens when there are no cups left.

In this post, we’ll add levels to the game, so that when you’ve collected all the cups, you move up. We’ll also introduce a time limit to make it progressively harder (as it currently stands, it’s not much of a challenge to collect the cups because you can take all day).

The source for this post is here. Again, not everything is in the post, so please refer to the repository.

Levels

Because we are creating levels, we’ll need to track the level that we’re on, so a new state property is in order:

this.state = {
	playerX: 100,
	playerY: 100,
	windowWidth: window.innerWidth,
	windowHeight: window.innerHeight,
	playerMomentum: 0,
	playerRotation: 0,
	playerVelocityX: 0,
	playerVelocityY: 0,
	playerLives: 3,
	playerCrashed: false,
	gameLoopActive: false,
	message: "",
	score: 0,
	level: 1,
	cupCount: 1, 
	remainingTime: 0
};

If you’ve followed this through from this first post, you may be asking yourself: “Is he ever going to refactor and clean this up!?”

To which I confidently respond:

“Probably!”

Anyway, you’ll notice that we have the level, the score, the time and the cup count. Advancing through the levels is conceptually just a number; here’s the code that completes a level:

completedLevel() {
	if (this.state.level >= 10) {
		this.updateMessage("Congratulations, you've completed the game");
	} 
	this.startLevel(this.state.level + 1);
}

startLevel is a slight refactor, which essentially sets the cup count and level to the new value – we’ll come back to that shortly.

You can only complete a level by collecting enough cups, so the trigger should be in the cup collection:

collectedCup(key) {
	this.setState({ 
		score: this.state.score + 1 
	});
	this.cups = this.cups.filter(cup => cup.key != key);
	this.updateMessage("Collected cup");
	if (this.cups.length == 0) {
		this.completedLevel();
	} 
}

As soon as we’re down to 0 cups, we call completedLevel.

Time

Now it’s time to have a look at the startLevel code:

startLevel(level) { 
	this.setState({
		level: level,
		cupCount: level * 2 
	}); 
	this.obstacles = this.buildObstacles(); 
	this.cups = this.placeCups();
	this.resetCarPosition();
	this.totalLevelTimeMS = (this.TOPLEVEL - (this.state.level - 1)) * 60 * 1000
	let startLevelTimeMS = (new Date()).getTime();
	this.endLevelTimeMS = startLevelTimeMS + this.totalLevelTimeMS; 
}

We’re working out when the user is out of time, and storing that in endLevelTime. Note that none of these are in state variables – the only state variable is in updated in the game loop:

let remaining = (this.endLevelTimeMS - (new Date()).getTime()) / 1000;
if (remaining <= 0) {
	this.updateMessage("Out of time!");
	this.playerDies();
}
this.setState({
	remainingTime: Math.round(remaining)
}); 

This is at the end of the game loop: we’re updating the remainingTime state variable, but first, we calculate it and, if it’s zero, the player dies (loses a life).

We need to tweak the code for the player dying, because otherwise the timer will never get reset:

playerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.startLevel(this.state.level);
	}
	this.repositionPlayer();
	this.setState({ 
		playerCrashed: false,
		gameLoopActive: true
	});
}

The last part is to make the time look a bit better with another of my patented icons. GameStatus.jsx should now return the following:

    return (      
        <div className="flex-container" style={flexStyle}>
            <label style={labelStyle}>
                Lives Remaining: {props.Lives}
            </label>
            <label style={labelStyle}>
                Score: {props.Score}
            </label>
            <label style={labelStyle}>
                Level: {props.Level}
            </label>            
            
            <div style={containerStyle}>  
                <img src={clockImg} style={imgStyle} />
                <div style={textDivStyle}>{props.RemainingTime}</div>
            </div>

            <label style={labelStyle}>
                {props.Message}
            </label>
        </div>  
    );

There are some new styles here so that the time appears over the clock icon:

    const containerStyle = {
        position: 'relative',
        textAlign: 'center',
        color: 'red'
    }

    const textDivStyle = {        
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: 1,
        fontWeight: 'bold'
    }

    const imgStyle = {
        width: '100%',
        zIndex: 0
    }

In the next part, we’ll implement a high score table.

Creating a Car Game in React – Part 3 – Collision

In this, the third post of this series, we’re going to add collision to the game. For a full list of the code, please see here.

If you’re wondering about earlier posts, please start here.

Since we’re introducing collision, we’ll also need to introduce the age old game concept of “Lives”. The premise here is that when you crash into something, you lose a life.

The first step is to add a new state variable to hold the player’s remaining lives:

this.state = {
	playerX: 100,
	playerY: 100,
	windowWidth: 1500,
	windowHeight: 1500,
	playerMomentum: 0,
	playerRotation: 0,
	playerVelocityX: 0,
	playerVelocityY: 0,
	playerLives: 3,
	gameLoopActive: false,
	message: ""
};

If you have a look in the repository, there’s a bit of refactoring, where I’ve taken some of the setState code and separated it into logical functions. I won’t list that here.

Collision Detection

At the end of the game loop, we now have a call to check if we’ve collided with anything:

if (this.detectAnyCollision()) {
	this.PlayerDies(); 
}

The collision detection code is quite straight forward, and is based on the simplistic idea that all objects can be considered rectangles. Whilst this is not precise, it’s sufficient for our purpose:

detectAnyCollision() { 
        const halfWidth = this.spriteWidth / 2;
        const halfHeight = this.spriteHeight / 2;

        let rect1 = {x: this.state.playerX - halfWidth, y: this.state.playerY - halfHeight, 
            width: this.spriteWidth, height: this.spriteHeight}

        if (this.detectOutScreen(rect1)) {
            return true;
        }

        return this.obstacles.some(a => {
            var rect2 = {x: a.props.centreX - halfWidth, y: a.props.centreY - halfHeight, 
                width: this.spriteWidth, height: this.spriteHeight}
            
            if (this.detectCollision(rect1, rect2)) {
                return true;
            } else {
                return false;
            }
        });
}

detectCollision(rect1, rect2) {
	if (rect1.x < rect2.x + rect2.width &&
	rect1.x + rect1.width > rect2.x &&
	rect1.y < rect2.y + rect2.height &&
	rect1.y + rect1.height > rect2.y) {
		return true;
	}
	return false;
}

detectOutScreen(rect1) {
	if (rect1.x < 0 || rect1.x + rect1.width > this.state.windowWidth
	|| rect1.y < 0 || rect1.y + rect1.height > this.state.windowHeight) {
		return true;
	}
	return false;
}

The collision detection code itself was pilfered from here. As you can see, all we’re doing is translating our objects into rectangles, and then seeing if they intersect each other, or if the player has left the game area.

Quick note about forEach and some

I had originally used .forEach for the detectAnyCollision() code. Whilst it would, initially make sense to a C# programmer, in fact the Javascript version of this does exactly what it says on the tin; that is, it executes for each element, and there is no way to exit early!

Player Dies and Score

Now that we have introduced collision, we should consider what to do when it happens. The usual thing in a game is that the player either “dies”, or they lose “health”. Since this is inspired by a spectrum game, we’ll go with “dies”. You saw earlier that we introduced the concept of “lives” and, because it was a spectrum, it has to be 3!

The code to deal with the player death is:

PlayerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.resetCarPosition();
	}
	this.repositionPlayer();
	this.setState({ 
		gameLoopActive: true
	});
}

Just a quick reminder that this isn’t a comprehensive listing of code – please see the GitHub repository for that; however, apart from the reduction in lives, the most important thing here is the gameLoopActive code.

The idea here is that we only execute the game loop while this state variable is set; which means we can stop the game loop while we’re dealing with the player’s collision.

The change in the game loop code for this is very simple:

gameLoop() {
	if (!this.state.gameLoopActive) return;

 . . . 

Crashed Car

All well and good, but as it stands, this simply results in the car stopping when it hits a tree, and then being re-positioned. We can address this by adding a small “animation” to indicate a crash. If you have a look here, you’ll see why I’ve won several awards for my graphics*!

In order to plug this in, we’re going to change the car graphic binding:

render() { 
return <div onKeyDown={this.onKeyDown} tabIndex="0">
	<GameStatus Lives={this.state.playerLives} Message={this.state.message}/>
	<Background backgroundImage={backgroundImg}
	windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> 
	
	<Car carImage={this.state.playerCrashed ? brokenCarImg : carImg} 
	centreX={this.state.playerX} centreY={this.state.playerY} 
	width={this.spriteWidth} height={this.spriteHeight} 
	rotation={this.state.playerRotation} /> 
	
	{this.obstacles} 
</div>
}

So, where the crashed flag is set, we’re binding to brokenCarImg; otherwise to carImg; they are defined at the top:

import carImg from '../Assets/Car.png';
import brokenCarImg from '../Assets/Crash.png';

We also split the playerDies() function into two:

playerDying(tillDeath) {
	this.setState({
		playerCrashed: true,
		gameLoopActive: false
	});
	this.stopCar();
	setTimeout(this.playerDies.bind(this), tillDeath);
}

playerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.resetCarPosition();
	}
	this.repositionPlayer();
	this.setState({ 
		playerCrashed: false,
		gameLoopActive: true
	});
}

All we’re doing here is calling the first function, which effectively just changes the image and then calls the second function on a timeout. Again, don’t forget the `.bind()` when you call timeout, otherwise, you won’t be able to access `this`!

Footnotes

* I haven’t actually won any awards for graphics – I had you fooled, though!

References

https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection

https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650

https://medium.com/@benjamincherion/how-to-break-an-array-in-javascript-6d3a55bd06f6