Category Archives: ReactJs

React Tips: 1 – Starting React on a Different Port

I came up with an idea to start a series of posts on React that offers small tips on things you can do, errors that you might get, and anything else that future me might find useful.

I started by creating a new react app. The intention being that I would have a reference repository on GitHub.

The first part of this concerns starting react on a different port.

Why?

There are a couple of reasons that you may choose to do this, but one is to get around the issue when running:

npm start

Something is already running on port 3000

How

Have a look in your project for a file called package.json. In there, you should see something like this:

{ 
"name": "react-demos",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},

In the start section, you can add the port:

{ 
"name": "react-demos",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "set PORT=3005 && react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},

The default port is 3000, so if you don’t specify a port, it will always try to start on 3000.

What if I don’t want to change the port / Why won’t react die?

You could try the following command is bash:

taskkill -F -IM node.exe

It should kill all of your React processes.

References

https://github.com/facebook/create-react-app/issues/1083

https://stackoverflow.com/questions/45544145/how-stop-after-running-react-scripts-start

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 4 – Score

This is the fourth part of a series (that began here). So far, we have a game where you can whizz around the screen avoiding trees. This effectively encompasses most aspects of a game of this type; that is, you can move, and there is a something preventing you.

The next step is to introduce something for the player to try to do, and give a score based on that. In our case, our player is going to try and collect cups – as per the original game. The asset I’ve created for the cup is here. For anyone following this series, you may have noticed that my artwork is a little… crap.

The source for this post is here.

Cups

The first thing that we’ve done here is added some code to place a few cups around the screen; the code for this was essentially the same as build obstacles:

placeCups() {
	let cups = [];
	const cupCount = 1;
	for (let i = 1; i <= cupCount; i++) {
		const centreX = Math.floor(Math.random() * this.state.windowWidth) + 1;
		const centreY = Math.floor(Math.random() * this.state.windowHeight) + 1; 
		cups.push(<GameItem key={i} image={cupImg} centreX={centreX} centreY={centreY} width={this.spriteWidth} height={this.spriteHeight} itemType={2} />);
	}
	return cups;
}

In a later post, I hope to do a full refactor, but for now, we have a separate function. This is rendered in the same way as the obstacles:

render() { 
	return <div onKeyDown={this.onKeyDown} tabIndex="0">
		<GameStatus Lives={this.state.playerLives} Message={this.state.message} Score={this.state.score} />
		
		<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} 
		
		{this.cups} 
	</div>
}

Collecting cups

In order to collect something, the player must collide with it. We need to change the collision code slightly to make it a little more re-usable:

detectAnyCollision(rect1) { 
	// Have we crashed or left the screen
	if (this.detectOutScreen(rect1)) {
		return true;
	}
	let collided = this.detectGameItemCollision(this.halfWidth, this.halfHeight, rect1, this.obstacles);
	if (collided !== undefined) {
		return true;
	}
	return false;
}

detectGameItemCollision(halfWidth, halfHeight, rect1, gameItemList) {
	const collided = gameItemList.find(a => {
		var rect2 = {
			x: a.props.centreX - halfWidth, y: a.props.centreY - halfHeight,
			width: this.spriteWidth, height: this.spriteHeight
		};
		return (this.detectCollision(rect1, rect2));
	}); 
	return collided;
}

As you can see, we now have a function that returns the item that we collided with, rather than a simple boolean. We then use this at the end of the game loop to determine whether we collided with a cup:

// Check for collected cup
const item = this.detectGameItemCollision(this.halfWidth, this.halfHeight, rect1, this.cups);
if (item !== undefined) {
	this.collectedCup(item.key);
} 

Score

There’s little point in zooming around collecting cups, if there’s no permanent record, so we need to add a score. Let’s start with a state variable in game.jsx:

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

And here’s the collectedCup function we mentioned a second ago:

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

All we’re doing here is simply updating the score and then removing that cup from the list.

The final part is to display the score on the screen; let’s have a look at our updated GameStatus.jsx:

function GameStatus(props) {
	const flexStyle = {
		display: 'flex',
		position: 'absolute',
		zIndex: 1,
		margin: 20,
		justifyContent: 'center',
		alignItems: 'center',
		width: '100%'
	};
	const labelStyle = { 
		zIndex: 1,
		margin: 50
	};
	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}>
				{props.Message}
			</label>
		</div> 
	);
}

As you can see, we’re just displaying the score as part of the status.

In the next post, we’ll have a look at the concept of levels, and introduce a time limit.

Reference

https://www.w3schools.com/css/css3_flexbox.asp

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

Creating a Car Game in React – Part 2 – Steering and Obstacles

In the second part of this series, we’re going to add some steering to our car, and introduce a concept of obstacles. If you’re wondering what this is the second part of, please start here.

The GitHub repo for this post can be found here.

In the first post of the series, we added a car, and allowed the user to move it around the screen in a very crude fashion; here, we’re going to change the controls to feel a little more like a car. As with the previous post, not every single change will be here, but it will be in the GitHub repo above.

Steering and Acceleration

Let’s have a look at the controls in the Game component:

onKeyDown now looks a little different:

onKeyDown(e) {
	switch (e.which) {
		case 37: // Left
			this.playerSteer(-10);
			break;
		case 38: // Up
			this.playerAccelerate(0.3);
			break;
		case 39: // Right
			this.playerSteer(10);
			break;
		case 40: // Down
			this.playerDecelerate(-0.5);
			break;
		default:
			break;
	}
} 

So, we’re no longer simply repositioning the car, but applying forces to it. Initially, I had Down as simply a negative acceleration, meaning that if you break too hard, you go backwards! Here’s the three functions referenced above:

playerAccelerate(speed) {
	this.setState({
		playerMomentum: this.state.playerMomentum + speed
	});
}

playerDecelerate(speed) {
	if (this.state.playerMomentum > 0) {
		this.setState({
			playerMomentum: this.state.playerMomentum + speed
		});
	} else if (this.state.playerMomentum < 0) {
		this.setState({
			playerMomentum: this.state.playerMomentum - speed
		});
	}

}

playerSteer(direction) {
	this.setState({
		playerRotation: this.state.playerRotation + direction
	});
}

There are a number of new state variables, which I won’t list here. However, because we are no longer repositioning the car based on the user action, we need to apply the forces that we are changing; that is, we need a game loop.

Game Loop

The game loop code is relatively complex. Looking at this should make you seriously consider using a a game engine of some description:

gameLoop() { 
	const radians = (this.state.playerRotation - 90) * Math.PI / 180; 
	const aX = (this.state.playerMomentum * Math.cos(radians));
	const aY = (this.state.playerMomentum * Math.sin(radians));
	const velocityX = this.state.playerVelocityX;
	const velocityY = this.state.playerVelocityY;
	const velocitySq = Math.pow(velocityX, 2) + Math.pow(velocityY, 2);
	const posSq = Math.pow(aX, 2) + Math.pow(aY, 2);
	const velocityPosSq = Math.pow(velocityX * aX + velocityY * aY, 2);
	let skidFactor = (posSq == 0 || velocitySq == 0) ? 0 : 1 - (velocityPosSq / posSq / velocitySq);
	
	if (skidFactor <= 0) skidFactor = 0; 
	
	this.setState({
		playerVelocityX: (skidFactor * velocityX) + ((1 - skidFactor) * aX),
		playerVelocityY: (skidFactor * velocityY) + ((1 - skidFactor) * aY)
	}); 
	this.playerMove(
		this.state.playerX + this.state.playerVelocityX,
		this.state.playerY + this.state.playerVelocityY 
	);
	this.playerDecelerate(-(0.1 + skidFactor));
}

If you’re wondering where this brain-melting maths comes from, have a look here.

I’ve split it up in an effort to make it slightly more understandable, but the premise is that if you’re travelling fast and change direction suddenly, it doesn’t immediately turn. Again, if you’re thinking you don’t want to be messing around with this kind of thing then a lot of game engines take care of this for you.

Obstacles

Finally, we have our obstacles. There is no collision just yet, but this basically puts pictures of trees around the screen (incidentally, I did all the artwork myself, which I assume the reader to be suitably impressed by!) We’ll come back to this later to make the collision work:

buildObstacles() {
	let obstacles = [];
	const obstacleCount = Math.floor(Math.random() * 10) + 1;
	console.log('Obstacle count ' + obstacleCount);
	for (let i = 1; i <= obstacleCount; i++) {
		const centreX = Math.floor(Math.random() * this.state.windowWidth) + 1;
		const centreY = Math.floor(Math.random() * this.state.windowHeight) + 1;
		
		obstacles.push(<Obstacle key={i} image={treeImg} centreX={centreX} centreY={centreY} width={this.spriteWidth} height={this.spriteHeight} />);
	}
	return obstacles;
}

All this function does is build up an array of HTML; we then feed that into a class variable in the constructor:

constructor(props) {
	super(props);
	document.body.style.overflow = "hidden";
	this.state = {
		playerX: 100,
		playerY: 100,
		windowWidth: 1500,
		windowHeight: 1500,
		playerMomentum: 0,
		playerRotation: 0,
		playerVelocityX: 0,
		playerVelocityY: 0
	};
	this.spriteWidth = 25;
	this.spriteHeight = 25;
	this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
	this.onKeyDown = this.onKeyDown.bind(this); 
	this.obstacles = this.buildObstacles(); 
}

(It’s worth noting, as an aside, that we are preventing scrolling here by setting document.body.style.overflow)

Finally, we’ll display it in the render method:

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

This technique allows you to build an array of HTML objects dynamically. The thing to notice here is the ‘key’ that we’re passing through; if you don’t pass this, you’ll start getting the following error:

Each child in a list should have a unique “key” prop.

In the next post, we’ll introduce collision.

References

https://stackoverflow.com/questions/5192983/calculating-x-y-movement-based-on-rotation-angle

https://gamedev.stackexchange.com/questions/172571/how-to-implement-a-slight-skid-in-a-car-game

https://stackoverflow.com/questions/39962757/prevent-scrolling-using-css-on-react-rendered-components

Creating a Car Game in React – Part 1 – Drawing and Moving

Since I started looking at React, I’ve wondered whether it would be possible to create a multi-user game. The game would look a little like a Spectrum game that I used to play called: Trans-Am. I’m guessing most people reading this are not going to be old enough to remember this. Essentially, it marks the peak of car game development, and everything has been down hill ever since.

If you have no idea what I’m talking about then there’s a demo of the game here.

I’m not going to try and emulate this exactly, I thought I’d use it as a basis to make a multi-player car game.

The GitHub repository for this post can be found here.

Create a React Application

We’ll start by creating a new React Application (see here for details):

Now we have the application, we’ll need some game assets. If you want to use the same assets as me then feel free to pull my repository. However, at this stage, all you’ll need is a square box and a green screen.

Game Layout

The next stage is to design the game layout; because this is React, we’ll start with App.js. We’ll delegate all of our game logic to a component called Game:

import React from 'react';
import './App.css';
import Game from './Components/Game';
function App() {
	return (
		<div className="App">
			<Game />
		</div>
		);
}
export default App;

If you want to see, comprehensively what Game.Jsx looks like, then have a look at the latest version on GitHub. However, some of the highlights are the render method:

render() { 
	return <div onKeyDown={this.onKeyDown} tabIndex="0">
		<Background backgroundImage={backgroundImg}
		windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> 
	<Car carImage={carImg} centreX={this.state.playerX} 
		centreY={this.state.playerY} width={this.playerWidth}
		height={this.playerHeight} /> 
	</div>
}

This will probably change as to game progresses, but at the minute, it just renders to two constituent components. We’re also responding to KeyDown here, so let’s have a look at onKeyDown:

onKeyDown(e) {
	switch (e.which) {
		case 37: // Left
			this.playerMove(this.state.playerX - this.SPEED, this.state.playerY); 
			break;
		case 38: // Up
			this.playerMove(this.state.playerX, this.state.playerY - this.SPEED);
			break;
		case 39: // Right
			this.playerMove(this.state.playerX + this.SPEED, this.state.playerY); 
			break;
		case 40: // Down
			this.playerMove(this.state.playerX, this.state.playerY + this.SPEED);
			break;
		default:
			break;
	}
} 

playerMove(x, y) {
	this.setState({
		playerX: x,
		playerY: y
	}); 
}

We’re storing the players position in state; as I detailed here, this enables us to update the state and have React update the screen as it detects a change in the Virtual DOM.

Game Components

In an effort to stay as close as possible to React’s preferred architecture, the components of the game (the background and the cars for now) will be, well, components. Background is easy:

import React from 'react';
function Background(props) {
	const bgStyle = { 
		width: `calc(${props.windowWidth}px)`, 
		height: `calc(${props.windowHeight}px)`, 
		top: 0,
		left: 0,
		position: 'absolute' 
	};
	return (
		<img src={props.backgroundImage} style={bgStyle} />
	);
}
export default Background;

We’re basically just displaying an image here. One thing that’s worth noting is that the windowWidth and windowHeight are properties, not state. They do exist as state in the Game component and, when they change, are updated there, and so updated here. The React guys call this Lifting State.

The car component is exactly the same idea:

import React from 'react';
function Car(props) {
	const left = Math.round(props.centreX - (props.width / 2));
	const top = Math.round(props.centreY - (props.height / 2));
	const carStyle = { 
		width: `calc(${props.width}px)`, 
		height: `calc(${props.height}px)`, 
		top: `calc(${top}px)`,
		left: `calc(${left}px)`, 
		position: 'absolute',
		zIndex: 1 
	};
	return (
		<img src={props.carImage} style={carStyle} />
	);
}
export default Car;

There are a number of advantages to this idea of maintaining the state in a higher component; for example, this way, you can share a single state between components; however, the biggest advantage for us is that, while the components are, effectively, intelligent sprites, you can easily create an “EnemyCar” version of the Car component.

It’s worth bearing in mind that, because the position of the car doesn’t exist in this component as state, we wouldn’t be able to change it here, even if we wanted to. The strategy to get around this is to have an update function passed in as a property (effectively a function pointer that you can call from within the child component).

In the next post, I’m going to update the movement so it’s a little more car-like, and introduce some obstacles.

References

https://reactjs.org/docs/components-and-props.html

https://stackoverflow.com/questions/43503964/onkeydown-event-not-working-on-divs-in-react

https://stackoverflow.com/questions/37440408/how-to-detect-esc-key-press-in-react-and-how-to-handle-it/46123962

https://reactjs.org/docs/lifting-state-up.html

https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs

A C# Developer’s Guide to: ReactJS – Part 3 – Conditionally Rendering HTML in React

This is the third in a series of posts on interesting things I’ve discovered about React; the first of these can be found here.

One of the things that tripped me up early on while I was learning React (not that I’m a fully-fledged expert now or anything) was how to display HTML elements based on a given criteria. For example, say you only want to display a label while the form is loading, or you want to display a message based on other information on the screen.

If you were using a desktop binding architecture, say MVVM, you would bind the visibility to a visible property. Likewise in HTML, you may have a conditional style based on the bound model property. Let’s see how you might do that in React.

Create a new React Application

Let’s start by creating a new React application (using bash here):

This isn’t a particularly fast process, so maybe it’s time to get a brew.

Once it’s done, and assuming you have VS Code installed (if you don’t then go and install it from here), type:

code testreactapp

And as if by magic, VS Code appears!

You should be able to run this straight out of the box. Start a new terminal in VS Code, and type npm start:

The displayed screen is of a little animated spiragraph. Let’s add a button and, where the user presses the button, hide or show the spinning spiragraph.

State

As I have previously written about here state is one of the key concepts in React. Let’s create a state object that will determine the visibility of our animation.

In order to introduce state, we need to change the default app.js to be a class, as functions cannot have state. Note that, were this a real application, you would probably move this out into a separate component; but let’s change our app.js to be a class:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

export default class App extends Component {
	render() {
		return (
			<div className="App">
				<header className="App-header">
					<img src={logo} className="App-logo" alt="logo" />
					<p>
						Edit <code>src/App.js</code> and save to reload.
					</p>
					<a
					className="App-link"
					href="https://reactjs.org"
					target="_blank"
					rel="noopener noreferrer"
					>
						Learn React
					</a>
				</header>
			</div>
		);
	}
}

All I’ve done here is change the function to a class, and added `import {Component}`.

Now let’s add some state. At the top of the class, add a constructor:

constructor(props) {
	super(props)
	this.state = {
		showSpiragraph: true
	}
}

Let’s now add the button, so we can change the value of the state; first, we’ll need the button itself:

. . .
	<a
		className="App-link"
		href="https://reactjs.org"
		target="_blank"
		rel="noopener noreferrer"
	>
		Learn React
	</a>
	<button onClick={this.toggleShow}>Hide/Show</button>
</header>
. . .

Then the function that we’re calling (toggleShow):

toggleShow = () => {
  this.setState(state => ({showSpiragraph: !state.showSpiragraph}));
}

If you run this now, it will allow you to press the button until your finger aches, but it won’t actually do anything.

Conditionally Displaying an Element

Okay, so we come to the crux of the entire post; we can conditionally render our image by using the following syntax:

. . .
<header className="App-header">
  {this.state.showSpiragraph &&
    <img src={logo} className="App-logo" alt="logo" />
  }
. . .

You should now be able to click the button and have the Spiragraph show and hide at will.

References

https://medium.freecodecamp.org/quick-guide-to-understanding-and-creating-reactjs-apps-8457ee8f7123

https://reactjs.org/docs/handling-events.html

A C# Developer’s Guide to: ReactJS – Part 2 – Moving Controls

Following on from my previous post, I’m going to extend our ReactJS application by adding some boxes, and allowing the user to re-arrange them on the screen.

Concepts

There are two key concepts to consider when working with React, and we’ll cover one of them in this post; that is: state.

React has a special property of each component known as state. If you use that to bind any of the UI to, then React will refresh that component when the state changes.

Moving a UI Element

Okay – that sounds great, but how would we do this in practice?

Imagine that you have a HTML box drawn on the screen; you might have something like this:

<div style="height:100px; width:200px; background:#0000FF" />

We can draw a box. If you use this code, then your box will be on the top left of the screen; so we can tell it not to be by specifying the left and top; let’s try defining a CSS style:

<div style="left:10px; top:20px;height:100px; width:200px; background:#0000FF" />

With React, we can set those values to a value derived from the state; for example:

render() {
    const top = this.state.newY;
    const left = this.state.newX;

    const myStyle = {
        height: '100px',
        width: '200px', 
        top: `calc(${top}px)`,
        left: `calc(${left}px)`, 
        borderStyle: 'solid',
        borderColor: 'blue', 
        position: 'absolute',
        zIndex: 1,
        background: 'blue'
    };

    return ( 
        <div> 
            <div style={myStyle}>source</div>
        </div>
    );
}

What this means is that every time I change the state values, the values in the style will update.

To illustrate this, if we write a React application like this (only the timeout function is new):

render() {
    const top = this.state.newY;
    const left = this.state.newX;
    const myStyle = {
        height: '100px',
        width: '200px', 
        top: `calc(${top}px)`,
        left: `calc(${left}px)`, 
        borderStyle: 'solid',
        borderColor: 'blue', 
        position: 'absolute',
        zIndex: 1,
        background: 'blue'
    };

    setTimeout(() => {
        this.setState({newX: this.state.newX + 1, newY: this.state.newY + 1});
    }, 50);

    return ( 
        <div> 
            <div style={myStyle}></div>
        </div>
    );
}

We can make out box move diagonally across the screen:

Screenshot included because you couldn’t possibly imaging what a blue rectangle looks like.

Start the app using VS Code

A quick note on VS Code. If you select Terminal -> New from the menu, you can run the React application directly from the IDE; and the best part is that if there’s something already running on the port, VS Code will just give you a new one:

A C# Developer’s Guide to: ReactJS – Part 1 – Create & Run

I thought it might be time for another of my patented “C# Developer’s Guide to…”. Basically, a guide to React for someone that understands programming (C# ideally), but doesn’t know anything about ReactJs.

There are a couple of VS templates for React; however, after working with it for a while, you realise that most of the React people live in the command line; there’s a tool called create-react-app:

You can use Powershell or Bash as your command line of choice. Start by installing the tool:

npm i -g create-react-app

This assumes that you have installed npm.

Create

To create a new application, navigate to the directory that you wish to create the application in and type:

create-react-app [app-name]

For example:

create-react-app context-menu-test

Once created, it tells you how you can start the app:

Run

First navigate into the directory that it’s just created (otherwise you’ll get errors when you run).

npm start

Will launch the server, and navigate to the Url with the default browser:

cd context-menu-test
npm start

This runs on port 3000 by default, so if you run a couple of instances then you might get the error:

Something is already running on Port 3000

To fix this, in VS Code, open the folder:

node_modules/react-scripts/scripts/start.js

Find the following line (at the time of writing):

const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;

You can change the port 3000 to something that’s free.

Edit App.js:

class App extends Component {
  render() {
    return (
      <div className="App">
        <div>
          <p>Test</p>
        </div>
      </div>
    );
  }
}

Save and see the updated screen appear (which I think you’ll agree is much better than the default screen).

Short Walks – Navigating in ReactJs

When you start using the React sample templates, one thing that you’ll notice is the navigation menu; it tends to look like this:

<div className='navbar-collapse collapse'>
    <ul className='nav navbar-nav'>
        <li>
            <NavLink to={ '/' } exact activeClassName='active'>
                <span className='glyphicon glyphicon-home'></span> Home
            </NavLink>
        </li>

After messing around for a while, you’ll probably think: now I need to navigate somewhere from within the code of the tsx/jsx file. Turns out you need to use `.push()`:

import { NavLink } from 'react-router-dom';

. . .

doSomething()
.then(output => {
    this.props.history.push('/timbuktu');
});

Not exactly intuitive. And even less intuitive is if you want to go back. You’re thinking it must be `.pop()`? So was I; it’s actually:

import { NavLink } from 'react-router-dom';

. . .

doSomething()
.then(output => {
    this.props.history.goBack();
});