Create a Card Game in Canvas with React Components

Create a Card Game in Canvas with React Components

What’s a website without a little fun and games now and then?  Even if you’ve never made a game before, or have no experience with game engines like Unity, that’s okay! Instead, you can channel the power of React Components and put your web development knowledge to work adding some fun aspects to your website.

This tutorial’s project will revolve around utilizing React, Canvas, and the create-react-app in React to create a simple card game called War. It’s recommended that you have some basic beginner experience with Canvas and React before delving in. As in additional note, I will be using Visual Studio Code throughout this whole project, and you can utilize that as a reference for the rest of the code and images below.

The source code is for the project can be found here! If you have any questions about the tutorials please be sure to leave a comment!

Overview of the Game Setup

If you’ve never played War as a child, it is a simple game with a simple objective: win all the cards. The deck is divided evenly amongst the players, given to them with the card facing down. Each player will reveal their top card at the same time. The player who has the highest card takes both cards and moves them to the bottom of their stack. If two cards are played of equal value, then both players will keep playing cards down until one of the players has a higher card then the other. Then that winner takes all the cards again and places them at the bottom of his stack. The player with no cards left loses. We will use one big React component with methods and functions to create it.

Quick Overview: What is Canvas?

HTML canvas is an HTML element that is utilized to draw graphics and animate them. This can be used for anything from cartoon animation, video game design and/or graphical user interface animation.

Quick Overview: What is create-react-app?

Create-react-app is a tool that will give you a prebuild react workspace. It helps you utilize your time more efficiently by giving you a foundation to work with. You import the foundation that you will be working with one simple command.

Installing Create React App

Open your terminal window. You can do this by clicking Terminal at the top and then New Terminal. Then type:

npm install create-react-app

This will install the create-react-app tool and all its dependencies. Once it’s installed you will go ahead and run the following command to create a new React project and the name the project:

Create-react-app war-game

In the above code, war-game would be the name of the project we will be making but it can be named anything you would like but I named it war-game for this project as the game is based on the card game called War.

Now let’s move into the project folder by typing:

Now you can start the live development server that will automatically update anytime you make changes by using the following command:

Editing your folder structure.

We are going to need to make a few changes in your folder structure. Open up src in the war-game folder and create a images folder.

Images folder as seen in src folder

Here is where we will be uploading the three images we will be using for our project.

Various war game card images in images folder

Let’s go into our App.css folder which will be out main CSS for our main component and change a few of the standard settings that have been put in place for us with the create react app. Your current folder should look like the following:

Let’s go over some of the CSS properties used in the class above. The property animation is being used with the @keyframes keyword to create rules and define how the animation will act. It’s a very useful property to help allow yourself to create CSS animations.

Pointer events property controls how the internal HTML will react to the cursor interacting with it. For instance in the property above its defined as none, which means that it will prevent all types of clicks and cursor option associated with that specific class.

Remove everything under the App class brackets and create a new class called App-body. It should like this now:

Once you have done that let’s go ahead and save it. We will use that App-body class later on. Now one more quick change that must be made is with the App.js file. Your current file  should look like the following:

Let’s open that up and just quickly replace the original imports at the top with the following:

We do this because we don’t need the logo and won’t be using it and we will be importing a new component that we will be making, which will hold the main game called WarGame.

Now let’s restructure the function App by just having it contain two div containers. One with the App class and the other with the App-body class that we recently made. In between those two, we will put our WarGame component.

The main component WarGame:

Create a new JavaScript file named WarGame and create a new CSS file named WarGame. We will add the styling of the WarGame CSS and then finish it up with the JavaScript component.

Open up the WarGame.css file and create the following classes:

  • CardTable
  • CardTableHeader
  • HeaderText
  • CardTableMainArea
  • CardTableFooter
  • TableCanvas
  • HiddenImage

All these classes will have simple stylings.

What does it do?

CardTable will be the class that will be in the div encapsulating the game.

What does it do?

CardTableHeader will be associated with the Card Count for the AI and the player, as well as the button.

What does it do?

HeaderText will be the class styling of the Player and AI text stating how many cards they have.

What does it do?

CardTableMainArea will be the main class that will reside in the outer div incapsulating the canvas.

What does it do?

CardTable will be the class that will be in the div encapsulating the game.

What does it do?

TableCanvas will be the main styling for the actual canvas.

What does it do?

Hidden Image will not display anything.

Next, we have the WarGameButton and its pseudo-classes for hover and active.

If you look at the properties in the classes above you might be asking yourself what all these -moz and -webkit properties are for the classes. Well, they are called vendor prefixes but also referred to as browser prefixes at times. Prefixes were and still are used when a certain browser doesn’t support the full functionality of certain CSS modules. You can use those capabilities and support them right away with the use of prefixes and not have to worry about different browser not working or waiting on browser manufacturers to catch up.

The major browsers use the following prefixes:

  • -webkit-(Chrome, Safari, newer versions of Opera, almost all iOS browsers)
  • -moz-(Firefox)
  • -o-(Old versions of Opera)
  • -ms-(Internet Explorer/Microsoft Edge)

Open up WarGame.js and in the imports import React Component, WarGame.css and two different images, deck and cover.

Create a class for the file named WarGame and it will extend Component. Remember that the main class name will always be the same as the file it is in.

Quick Overview: Constructors?

A constructor is a method that gets called during the creation of the class, for this project it would be the WarGame class. It would automatically get called before the component is mounted.

Quick Overview: Super()?

Super refers to its parent class, the constructor class. You also can’t use this in a constructor until after you’ve called it. So if you want to use this.state you need to specify super and pass the props to it.

Create a constructor, super and then we will need to create a few different states.  You’ll need a few states associated with the players, the AI, the Cards themselves and the game state. You will also need to set a few binding states.

Now we will need to create the animation to this meat and bones of this program, thankfully that’s what javascript is for. We will write up the rest of the javascript methods, the methods that will be running the cogs for us and that will make sense of all these binding and set states. It’s good to get a broad understanding of the structure and functionality of the project we are working on before moving forward with it. The following is a break down of methods that we will be making and what they will be doing:

  • GetOneCardFromDeck: Will get a card from the deck.
  • MoveDeck: Removes one card from the deck.
  • GetCardCount: Get’s the card count of the cards in the deck at the time of running.
  • StartNewGame: This will initialize the program and start a new game, as well as clearing and randomizing the AI & player decks.
  • DoOneMove: DoOneMove will be our card check state management system.  It will control whether the cards match, they don’t match or neutral.
  • EndMove: In end move, we will check the scores between the AI and the player to see who wins.
  • componentDidUpdate: This will update all the canvas content on the screen
  • draw_card: This will move the cards that are drawn to the middle of the screen.
  • BtnOnMoveClick: This will handle the event handler and call the method DoOneMove and changes the sate of MoveCount by one. Then we return everything in their appropriate divs.

Let’s move onto making the first three methods of the card game. Use GetOneCardFrom deck and create an anonymous function that will either return a random number with 52 being maxed or return a count of the cards if no card is present/state that there is no card left.

Moving onto MoveDeck we will create an anonymous function with an argument of the deck that will remove one card from the deck.

GetCardCount will take a parameter of the deck like above but will return the number of cards in the deck.

StartNewGame will initialize the game and fill both decks for AI and the player. It will then set the state of MoveState and AppMode.

DoOneMove will be a method with a switch case for the MoveState.

EndMove will decide whether we have a winner or loser or if our cards are the same as the ai.

ComponentDidUpdate will update our canvas and draw it with images of the cards.

draw_card will move the card on the canvas and draw it.

BtnOnMoveClick will be an anonymous function that will handle our event handling for MoveCount state.

Render will render everything back into the DOM.

Now just type npm start in your terminal if you don’t have it up and you should have the project up and working perfectly!

War card game built with Canvas and React

And there you have it!  You now have your very own war card game built only with Canvas and React Components.  Though you can certainly improve upon it, it’s a great start to adding more spice to your websites (or to pass the time).

Share this article

Leave a Reply

avatar
  Subscribe  
Notify of