Building a simple game with React (Part 1)

The inspiration for this tutorial (and many many rage quits)Building a simple game with React (Part 1)Juan QuinteroBlockedUnblockFollowFollowingApr 15Hello guys and girls, in this two-part tutorial I am going to show you how to build a simple flappy bird clone using React JS and HTML canvas.

Setting up the environmentThe first thing that you are going to need, apart from a code editor will be the node and the node package manager(npm) installed in your machine.

This will allow you to run Javascript in your machine and do all sorts of wonky things using the thousands of packages npm offers.

You can find instructions on how to install node here: https://nodejs.

org/en/download/package-manager/create-react-appcreate-react-app is a utility that has been provided by the React developers in order to simplify the set up when, well…, creating a react app.

Having npm installed, navigate to the folder where you want the app to live and create it using:npx create-react-app flappy-ballhot-reloadingOne of the best things that have been done for us inside the create-react-app tool is hot reloading.

For those of you unfamiliar with this term, it means that every time you save changes into your files, what you see in your browser gets reloaded almost instantly.

To experiment with this, before changing anything, we are going to run the default react app.

This will also allow us to check if everything is working well till now.

cd flappy-ballnpm startThis will launch your browser and you should see something like this:default create-react-appIf your browser didn’t launch automatically, you can open it up yourself and navigate to http://localhost:3000/To test hot reloading you need to make a change.

Most of the code inside a react app lives inside the .

/src folder so we are going to go there to make our change.

Inside this folder, we are going to open the file App.

js which is our main Component.

We change the content inside the paragraph tag to be whatever we want, save, and see the magic.

class App extends Component {render() { return ( <div className=”App”> <header className=”App-header”> <img src={logo} className=”App-logo” alt=”logo” /> <p> Am about to delete all this files and make game </p> <a className=”App-link” href=”https://reactjs.

org" target=”_blank” rel=”noopener noreferrer” > Learn React </a> </header> </div> ); }}Hot-reloading testRight after saving, you must have seen the page reload on its own, exposing your changes.

Setting up the filesWe are going to get rid of all the contents of the .

/src folder apart from the index.

js and App.

js files.

This will give us an error in the console because inside those files, there are still references to the deleted files.

Go on an delete them.

After deleting, your index.

js should look like this:import React from 'react';import ReactDOM from 'react-dom';import App from '.

/App';ReactDOM.

render(<App />, document.

getElementById('root'));And the App.

js (we deleted line 2):import React, { Component } from 'react';import '.

/App.

css';class App extends Component { render() { return ( <div className="App"> </div> ); }}export default App;Ok, now that the error is gone we can actually start coding…App.

js will be the root of most of your React apps and it will be the place where other components are put together.

We are then going to create a file where the game is going to live.

touch src/Game.

jsNow inside Game.

js, we want to create a class that will hold the component.

import React, { Component } from 'react';class Game extends Component { render() { return ( <div> <h1>Testing.

</h1> </div> ); }}export default Game;We add a <h1>, for now, to check everything is working fine.

Now in App.

js, we need to import the newly created component in order to be able to render it.

import React, { Component } from 'react';import '.

/App.

css';import Game from '.

/Game';class App extends Component { render() { return ( <div className="App"> <Game/> </div> ); }}export default App;Now we should see in the browser this:Testing componentsThis is coming from the Game.

js component which means our components are now connected.

CanvasNow we are going to add the canvas so we can draw on it later on.

In Game.

js add:class Game extends Component { render() { return ( <div> <canvas ref="canvas" width={450} height={650} /> </div> ); }}StateWe are going to keep the entire state of the game inside this Game.

js component.

To begin with, we are going to add the bird, which in our game will be a circle.

Above the render function we add:.

state = { bird: { x: 50, y: this.

refs.

canvas.

height/2, radius: 20 } }.

The x and y are the coordinates for the centre of the circle which will have a radius of 20.

Drawing in the CanvasTo draw in the canvas we are going to create a function which will be called at every update step and will redraw in the canvas all the changes.

This will make more sense when we implement updates, for now, let’s just draw our “bird” on the canvas.

Outside of the render function, we create a new function which draws for us:draw = () => { const ctx = this.

refs.

canvas.

getContext("2d"); // change this colour to change the colour of your // "pen" in the canvas ctx.

fillStyle = "green"; ctx.

beginPath(); ctx.

arc(this.

state.

bird.

x, this.

state.

bird.

y, this.

state.

bird.

radius, 0, 2 * Math.

PI); ctx.

fill(); ctx.

stroke(); }This function won’t draw until it is called so we use one of the inbuilt React functions componentDidMount( ) to call this function as soon as the component gets rendered.

Putting it all together, our Game.

js should be looking like this.

import React, { Component } from 'react';class Game extends Component { state = { bird: { x: 50, y: 100, radius: 20 } }draw = () => { const ctx = this.

refs.

canvas.

getContext("2d"); ctx.

fillStyle = "green"; ctx.

beginPath(); ctx.

arc(this.

state.

bird.

x, this.

state.

bird.

y, this.

state.

bird.

radius, 0, 2 * Math.

PI); ctx.

fill(); ctx.

stroke(); }componentDidMount() { this.

draw() }render() { return ( <div> <canvas ref="canvas" width={450} height={650} /> </div> ); }}export default Game;And should result in this a green circle drawn inside the canvas:rendered circle in canvasYou can play with the size of the radius, colours or add more shapes into this image to get yourself more familiar with the canvas API.

The official documentation can be found here: https://developer.

mozilla.

org/en-US/docs/Web/API/Canvas_API and also something good here: https://www.

w3schools.

com/html/html5_canvas.

aspThe end… of Part 1I hope this Part 1 has served you as an introduction to using React with HTML and the Canvas API.

In the next part, we are going to get that ball jumping as we introduce the update function and some physics into our game.

See you soon!.

. More details

Leave a Reply