JavaScript Tutorial - Create a Card Game ๐Ÿƒ

freeCodeCamp.org ยท Beginner ยท๐ŸŒ Frontend Engineering ยท3y ago

Key Takeaways

This video tutorial demonstrates how to create a basic card game using vanilla JavaScript, HTML, and CSS, covering topics such as dynamic user interaction, animation effects, and responsive layout design. The tutorial uses tools like Visual Studio Code, GitHub, and Chrome browser, and covers concepts like retrieval augmented generation, fine-tuning, and client-side web behavior functionality.

Full Transcript

in this course you will learn how to improve your JavaScript skills by building a card game Gavin long teaches this course Gavin is a freeco camp team member and popular instructor hi and welcome I'm Gavin long I've been a professional software developer for many years and over the years I've written in a variety of different programming languages depending on the relevant project c-sharp is my main programming language but in spite of what your main programming language may be be a Java python c-sharp Etc there is always this one other programming language that is almost a mandatory programming language for every developer to learn that programming language is of course JavaScript so why is it so essential to learn JavaScript well JavaScript is a great language that can run both on the client and server side but it is also along with HTML and CSS a core technology on the world wide web according to Wikipedia 98 of websites use JavaScript on the client's side for web page Behavior sure this may change moving forward due to Technologies like webassembly which enables developers to leverage programming languages like for example C sharp for client-side web Behavior functionality but I think it's safe to say that for the foreseeable future JavaScript is still going to be the dominant technology for this client-side where Behavior functionality so in this video we'll exercise our JavaScript skills to create a browser-based basic card game by going through this video you'll hopefully learn a few things about JavaScript HTML CSS and visual studio code although you'll only create a basic card game you can use the concepts you'll learn to create more sophisticated card games like for example blackjack or poker so please feel free to make the application your own and use the code as the basis for your own card games at the very least this video provides you with a great JavaScript exercise I hope you enjoyed this video and learn a few things along the way so this tutorial demonstrates how to build a basic card game using vanilla JavaScript basic CSS and HTML code this tutorial not only covers creating a basic card game using JavaScript but also covers how to create Dynamic user interactive code using vanilla JavaScript we'll cover creating some animation effects responsive layout design using CSS grid CSS flexbox and media queries how to dynamically change the positions of grid cells so as to randomize the positions of the cards contained in a CSS grid using JavaScript local storage and much more I would say that the code is accessible to Learners at most levels I've kept the code quite simple if however you get lost at any point the code can be downloaded from GitHub please see a link below in the description to the relevant GitHub repository in this video we are going to develop a basic card game using vanilla JavaScript I'll use vs code as my code editor even though I'll develop the game on my Mac you of course can use vs code for Windows or Linux and the coding experience will be very much the same vs code is of course free open source software I'll be using the Chrome browser for testing purposes so the game that we'll develop is very basic I've called it hunt the ace here's a brief description of the game so we have four different cards one of which is the Ace of Spades the user clicks the play game button to start the game the cards are flipped over so that the user can no longer see the face of the cards our game then randomizes the positions of the cards so the cards are in effect shuffled the cards are then positioned at random locations in a grid layout each location corresponds to a random whole number between one and four the user can then guess where the user thinks the Ace of Spades is by clicking on the relevant card once the user has clicked The Chosen card the card then flips over and of course the user is made aware of whether the user has guessed the correct position of the Ace of Spades each game consists of four rounds in each round the user attempts to guess the location of the Ace of Spades if the user fails to guess the position of the Ace of Spades the user will not be awarded any points for that round if the user however guesses the correct location of the Ace of Spades the user is awarded points based on the round number so yes it's a simple game but I thought this might be a good JavaScript coding exercise this code is fairly simple and therefore this tutorial should be accessible to a wide audience interested in programming if you like this video please hit the like button for Content like this and much more please consider subscribing and please ring the bell so that you'll be notified of future content please note that I've included links Below in the description to additional information for more detail on certain Concepts discussed in this tutorial let's create the project so let's get started so all we need to do is open an empty folder from within Visual Studio code this folder is of course where our project files will reside so I've created a folder which I have aptly named hunt the ace to house the files for this project on my computer let's create three files within Visual Studio code let's create a file named index.html of course for our HTML code let's create a file named index.js of course for our JavaScript code let's create a file named style.css of course for our layout and styling code our CSS code let's create a folder to house the images that will be used to represent our cards as well as a card that will be used for our game's image logo you can download the relevant images from GitHub at this location great the live server extension let's start by coding basic HTML code So within Visual Studio code you can generate boilerplate HTML code for example the doctype tag that indicates that we are using HTML5 the HTML tag head and body tags along with relevant meta Tags by simply typing in the exclamation mark character followed by pressing the Tab Key like this so I'm going to use semantic HTML to create a tag named header which will house header related HTML code in our layout by semantic HTML I mean the tag name is descriptive as to the purpose of the tag rather than for example simply using a div tag semantic HTML elements are those that clearly describe their meaning in a human readable and machine readable way so we can type the tag name and then press the tab key and the code for the HTML element is generated for us by Visual Studio code let's include a div element that contains a CSS class named header Dash title Dash container so a quick way to generate the HTML code for the relevant tag that includes a specific class attribute within Visual Studio code is to type the tag name so div then type in a DOT followed by the class name you wish to include within the element then simply press the Tab Key and visual studio code automatically generates the desired HTML code let's include a H1 element for our game's header so we want our header to reflect the name of the game we are creating so punt the ace you may be familiar with a visual studio code extension named live server if you're not familiar with this extension it is very useful for monitoring the effects of changes made to your code in real time you can install the live server extension from this location so once the live server extension has been installed we can launch our application through Visual Studio code using live Server Like This we can then tile our code Editor to the left of our screens and our browser to the right of our screens and in this way we can easily monitor the effects of changes to our code without the need to refresh the browser window every time we make a change to our code so for example let's change our header text to hunt the Ace of Spades and once we have saved our code we can immediately see the effects of our code change within the browser window create cards statically with card 3D CSS effects so we are first going to create a card statically then later we'll dynamically generate the cards through JavaScript code we'll appropriately use the document object model to build our cards and add them to the Dom document object model let's first create the card statically through basic HTML and CSS code let's create a div tag that contains a class named card Dash container within this div tag let's create a child div element that contains a class named card within the card div element let's create a child div element that contains a class named card Dash inner within the card Dash in a div element let's create a child development that contains a class named card Dash front let's also create a child development that contains a class named card Dash back let's add an image element as a child element to the dev element that contains the class named card Dash front as you may have guessed this image will represent the front of the card so let's assign the image elements Source tag the path of the image that depicts the Jack of Clubs so each card will contain the same back image so we can ensure this by adding the appropriate image element as a child element to the div tag that contains the card dashback class like this so we have built our card statically using HTML code as you can see there's not much to look at at present so the next step is to style the card using CSS code so that we can create our card to look three-dimensional and create the desired flip effect our CSS code will create the illusion that the card is a three-dimensional object let's first reference our style.css file from within the index.html file I'm not going to go into too much detail explaining the CSS code because this tutorial is more about JavaScript please follow along with the code so that your CSS code is consistent with mine let's create the styling for the cards Dash container element by card container element I am of course referring to the element that contains a reference to the card Dash container CSS class let's create the styling for the card element let's create CSS variables to store the dimensions of our cards so basically the car dash inner element contains the child elements card Dash back and card Dash front the CSS code we are creating facilitates a flip effect between the front of the card and the back of the card we can test the flip effect by implementing CSS code so that when we hover our Mouse pointers over the relevant card that the flip effect occurs so we are writing code so that the inner Dash card element rotates 180 degrees on its y-axis when a mouse pointer is hovered over the relevant card and we can now test this excellent before we create our cards dynamically through JavaScript code and appropriately add the cards to the document object model let's create a grid for the game area if you like where the cards will be placed so firstly let's create four placeholders denoting the positions of each of the cards in the gameplay area so card Dash pause Dash a card Dash pause Dash B cards Dash pause Dash C and card Dash pause Dash D so you can see here in the CSS code I've given the body element a height of 100 VH this simply means the height of the body of the HTML document will take up a hundred percent of the viewport height of the screen so I want the gameplay area to be aligned centrally within the main element and take up an area based on the width of the cards so let's write the code for this so I'm using flexbox functionality for the display to centrally align the gameplay area I.E the area that will contain our cards so I'm going to use the calc CSS function to calculate the width of the gameplay area two cards will reside side by side on each row the card Dash container style essentially denotes the gameplay area then to display the cards in a grid that will have two cards on each row we can use the grid functionality provided in CSS we can control where each individual card will reside by allocating each card position element a position in the grid by using the grid Dash template Dash areas property like this so to get a clear picture of our layout let's add border styles to the relevant HTML elements great let's give each of the grid cells different background colors so that we can get a clear picture of the layout of the grid note that each of the four cards used in this game will be placed in a specific cell within the grid great and we can see the grid cells clearly so we have now created the grid within the gameplay area create cards dynamically through JavaScript we have created our cards statically through HTML and CSS let's create the cards dynamically using JavaScript let's go to our index.js file let's create an array of objects each object within the array denotes a card or a card definition each object has an ID property and an image Path property the first item is the king of hearts and has an ID of one the second item is a jack of clubs and has an ID of two the third item is the Queen of Diamonds and has an idea of three the fourth item is the Ace of Spades and has an ID of four let's create a function named create card of course this function is responsible for creating a card dynamically through JavaScript code firstly let's create a reusable function responsible for creating a HTML element let's name this function create element we can create a HTML element and code through this line of code let's use our create element method to create the div tags that make up a card so here we can see the static HTML code that we created earlier to represent a card so that we can see what we are creating here in code dynamically so basically we have a card element an inner card element within the card element a front and back element within the inner card element we can use the create element method to create our image elements that contain the back card image and the front card image let's create a reusable method that adds a class to a HTML element let's write code to add the card class to the card element let's write a method that adds an ID to a HTML element so each card will be assigned a unique ID the ID will come from the array of card object definitions that we created earlier I'll create card method accepts one argument this argument will be an item from the card object definitions array let's write code to add the inner card class to the inner card element let's write code to add the appropriate class to the front dash card element and the back card element let's write a reusable method that assigns a path for the relevant image to the SRC attribute of an image element okay before we assign the image path properties for the card to the appropriate image elements let's create a const to store the path for the image that represents the back of a card right let's assign the image paths appropriately let's write code to assign the card Dash image class to the image elements so now that we have our basic elements created in code let's assign the child elements appropriately to their parent elements so let's create a reusable method named ADD child element the code within this method simply adds the child element passed in as an argument to the second parameter to the parent element passed in as an argument to the first parameter so let's write code to add the image elements to their appropriate parent elements let's write codes to add the front dash card element and the back dash card element to the inner Dash card element let's write code to add the inner Dash card element to the card element let's create a global const and store a reference to the card Dash container element we are not going to add the card elements directly to this element but we will use this element constant a bit later when we write code to alter the positions of the grid cells each grid cell will contain one of our cards the cells of the grid are child elements of the card container element we are using the CSS grid system for the grid functionality which represents the gameplay area I.E where our cards will be displayed let's write code to appropriately add each card element as a child element to their appropriate grid cell each grid cell is denoted by a div element we are going to map each card to its initial position by mapping the card element's ID to the appropriate element that represents a grid cell this is how our code will know as it were which card must be assigned to which positional parent div element so let's create a method named add card to grid cell let's create a method named Map Card ID to grid cell this method will be called within the add card to grid cell method so if the card ID is one we want this card to be added as a child element to the first position in the grid which is denoted by a div element with the cart Dash pause Dash a CSS class if card ID is 2 we want this card to be added as a child element to the second position in the grid which is denoted by a div element with the card Dash pause Dash B CSS class if card ID is three we want this card to be added as a child element to the third position in the grid which is denoted by a div element with the card Dash pause Dash C CSS class if card ID is four we want this card to be added as a child element to the fourth position in the grid which is denoted by a div element with the card Dash pause Dash D CSS class then within the add card to grid cell method let's write the code that finds the appropriate parent element for the child card element using the map grid ID to grid cell method and then adds the childcard element to its designated parent element then within the create card method let's write code to appropriately call the add card to grid cell method so let's write a method that will Loop through each of the objects stored within the card object definitions array create the relevant cards and add the cards to their appropriate grid positions so let's create a method named create cards then all we need to do is write code that calls the create card method within the for each Loop that Loops through each card definition to create the cards dynamically and add the cards to their appropriate position within the grid Let's test the code okay so we have an issue let's press F12 within our Chrome browsers and card is not defined okay and it's because I forgot to include an appropriate parameter that expects a card element as an argument within the map card ID to grid cell method definition okay and it's still not adding the cards to the grid if we press F12 and inspect the elements it's definitely adding the cards to the grid cells ah but the IMG element is not built correctly okay so the code is currently adding the images to the front and back div elements whereas the code should be adding the images to the front and back image elements so let's fix this issue oh and I can see that the card Dash image class is being added to the div elements rather than the image Elements which is of course incorrect this class should be added to the appropriate image elements not the div elements great so let's modify the CSS code so that the cards align centrally within the grid cells and let's use the CSS flexbox functionality to align the card centrally within their parent elements great so we have now created our cards dynamically through JavaScript code and positioned the cards appropriately within their grid cells let's write a method named load game the method is called when the game is first launched so we want our cards to be created dynamically when the game is first launched so let's call the create cards method from within the load game method let's write a method named start game this method will be called when a user clicks a button used for starting a game the gameplay button if you like let's go to our HTML file and include a button element that the user can click to start the game let's first write layout related code for our button and then let's code the button element itself let's write code to create a global variable that will store a reference to an array of the card elements then let's write code to assign the results of a query for all card elements to our card's Global array variable within the load game method let's write code to wire up a click event to the start game button element that we just created within our HTML code let's first write code to store a reference to our start game button element in a global const within the load game method let's use the JavaScript method add event listener to add a click event handler to the start game button when a user clicks the start game button we want the start game function to be called so let's test whether our event listener is working great let's write a definition for a method that will be called to initialize a new game let's write a definition for a method that will be called when a new round is started let's write a definition for a method that will initialize a new round let's call the start round method from within the start game method so when the user clicks the start game button and before the cards are shuffled I.E their positions are randomized we want the user to see the cards stacked one on top of the other and positioned centrally within the gameplay area I.E the grid so to achieve this we are going to first collapse the grid as it were the collapse grid functionality simply involves modifying the grid area template property so the grid consists of just one cell then our code will add the cards to this one cell so to achieve this let's first create a method named collect cards let's create a constant to store the grid area template's value that will be assigned to the grid area templates property to cause the grid to collapse as it were let's create a global constant that stores the class of the div element that represents the grid cell that will be the only cell in the grid once we modify the grid area templates property appropriately so we are choosing the first cell in the grid to contain our Stacked Cards as it were So within the collect cards method let's call a method named transform grid area and pass the appropriate Global constant we have just declared as an argument to the transform grid area method let's write the transform grid area method so using the card container LM element that contains the grid cells this element has been designated through appropriate CSS code as our grid let's change its grid template areas property through implementing the appropriate JavaScript code like this then let's write a method to add the cards to the cell that at this point takes up the entire grid so the grid now consists of only one cell let's call our add cards to grid area cell method from within the collect cards method let's call the collect cards method from within the start round method Let's test the code excellent so before the shuffle cards process begins we want to flip the cards so that the backs of the cards are facing the user so firstly let's update the CSS code so that when the inner card div element also contains a card named flipit that the UI responds by rotating the card on its y-axis by 180 degrees I.E the flipped class being present in the relevant cards in a card element results in the card flipping from front to back as it were so let's go to our JavaScript code and create a method named flip cards this method contains one parameter if the card is on its front and the flip to back argument is true our code will flip the card so that its back is facing the user so let's create a method named flip card this method accepts two arguments the first argument will store the relevant card element the second argument will contain the Boolean flip to back value so as we know at this stage the inner card element is the element that is used for creating the flip effect so the inner element is the first child contained within the card element so we can use the relevant card elements first child property to reference the inner card element the logic for this method is as follows if the flip to back argument is true and the inner card element doesn't contain the flipped class then add the flippet class to the inner card element so if the card is already back facing we don't want to flip the card so that it is front-facing flip to back is true so we want the card to have its back facing the user else if the inner card element contains the flip it class we want to remove it the result of this will mean that the card is flipped so that the card's front is facing the user if the card is already facing front side up it will not contain the flipped class which is what we want in this case within the flipped cards method let's call the flip card method appropriately so that all cards are traversed and flipped as it were if appropriate let's use the JavaScript set timeout method so that each card is flipped at a different time this is done just to create a simple animation effect so each flip will occur at an interval measured in milliseconds which will be the index a sequential value from one to four incremented with each iteration of the loop multiplied by 100. so let's call the flip cards method from within the start round method after the collect cards method we want the cards flipped on their backs so the flip to back argument passed to the flip cards method is set to true Let's test the code excellent so now we want to randomize the positions of the cards so let's create a method named shuffle cards we are going to use JavaScript set interval method to run a function that we'll create in a bit named Shuffle so every 12 milliseconds the shuffle method will execute let's use a variable named Shuffle count to count the amount of times the shuffle method is called when the shuffle count variable is equal to 500 we can use javascript's Clear interval method to stop the shuffle method being called the shuffle count variable is incremented every time the shuffle function is called we are going to create a method to randomize the positions of the cards within the shuffle function let's call a method named randomize card positions right so let's write the randomized card positions method so let's use javascript's math.random functionality appropriately so that we generate a random whole number between 1 and 4. we want two random numbers generated let's create a global variable that stores an array of card positions within the grid then we can use these two random numbers to swap the position values for the relevant cards within the card positions array this creates a shuffle-like effect for our four cards this randomized card positions method will continuously be called until the clear interval JavaScript method is executed from within the shuffle method at this point the positions of the cards should be unpredictable to the user okay let's write a method named initialize card positions that contains the code to store the initial positions of the cards in the grid the gameplay area within the card positions array let's call the initialize card positions method from within the create card method so each initial position of the card is established when the game is first loaded through the relevant card elements ID I want to create a method named deal cards that will execute when Shuffle count equals 500. and therefore the deal cards method will be called after the shuffling or randomization of the card positions is complete the deal cards method will in effect restore the grid to contain four grid cells and add each card back to their original positions in the grid the div elements that make up the grid I.E the grid cells will then have their positions within the grid altered in accordance with the random positions stored in the card positions array this randomization of their positions was of course caused through the randomization functionality executed within the randomized card positions method so let's create the deal cards method let's create a method named add cards to appropriate so within this method let's call the add card to grid cell method and pass in each card element to the add card to grid cell method within a loop that traverses all of the card elements from within the deal cards method let's call the add cards to appropriate self method so this will in effect restore the grid back to its original state with four cells and each cell containing a card element the grid cells will at this point be in their original order so now let's call a method named return grid areas mapped to card pause this method will return a grid area template value containing a new positional configuration of the grid cells based on the randomized positions now stored in the card positions array this randomization of positions was caused through the execution of the randomized card positions method called from within the shuffle method let's create the return grid areas mapped to codpos method this method simply generates a grid area template that contains a new position configuration for the cells in the grid based on the random positions generated through our Shuffle functionality stored within the card positions array we can then transform the grid as it were to change the positions of the grid cells by assigning the grid the new grid area template value returned from The Returned grid areas mapped to card parse method note that I'm using the back tick characters to envelop the value returned from the return grid areas mapped to codpos method these characters allow us to interpolate a string by appropriately using the dollar symbol and curly brackets to wrap the relevant variables I've included a link in the description for more detail on string interpolation in JavaScript let's comment out the call to the flip cards method so that we can see if the positions of the cards are being randomized by our Shuffle functionality great let's uncomment the call to the flip cards method so let's first remove all the borders and let's also remove the background colors from the grid cells and see what our game looks like great okay so let's create functionality so that when a user makes a choice and clicks on the back of the card that the user believes to be the Ace of Spades that the card that is chosen flips to the front and the user is made aware of whether the user's choice is correct or not if the user's choice is correct the user is awarded points depending on the relevant round number if the user's choice is incorrect the user is awarded no points so we are now going to write the code that executes as a result of the user making a choice as to the card that the user believes to be the Ace of Spades let's first create a method named choose card let's create a method named can choose card which will be called from within the choose card method there are certain states that the game will be in where we don't want the user to click on the back of the cards for example when the cards are being shuffled so we don't want the choose card functionality executed while the shuffle process is in motion as it were so they can choose card method will return a Boolean value to the calling code to indicate to the calling code as to whether the game is in the right state where the choose card functionality can run this expression is basically saying that if the game is in process and the shuffling process is not in progress and the cards are not in the process of being revealed the expression returns true when the expression returns true the user is able to choose a card when the expression returns false the functionality in the choose card method will not be executed if a card is clicked let's declare and initialize the variables involved in the expression we'll set the relevant values for these variables appropriately as we develop the game the next functionality we want to express in code is the evaluation functionality so the code we are about to write evaluates the user's choice so let's write a method named evaluate card choice this method is responsible for evaluating whether the card that the user chooses is the Ace of Spades or not so let's first declare a global const and set its value to the ID of the Ace of Spades which is four let's write an if statement in order to evaluate whether the ID of the chosen card is equal to the ID of the Ace of Spades in both cases we want to Output appropriate feedback to the user if the user's choice is correct we also want to update the score appropriately we'll write the code for the update score method in a bit so let's write a reusable method to Output feedback to the user so if the user hits the target as it were outputs an appropriate message for a winning Choice else output an appropriate message for a losing choice let's declare a global const that references the current status element this is the element that is updated with status information dynamically through our code at appropriate points during a game so let's go to our HTML code and create the current status element if the user guesses the correct card we want to Output text in a green color if the user guesses an incorrect card we want to Output text in a red color let's create a method named update status element at times we only want to make the current status element visible or invisible without updating the relevant elements text so if the calling code passes in only two arguments we can set the display appropriately however if the calling code passes in more than two arguments this indicates that the calling code wishes to update the text of the relevant element and possibly update the color of the element 2. so this is a technique that we can use in JavaScript for method overloading and of course the choose card method and the evaluate card method must include a card parameter so let's write the code for the update score method the update score method calls the calculate score method the calculate score method discovers as it were the number of points to add to the user's score through a call to the calculate score to add method the number of points to add to the score depends on the round number so if the round num variable is 1 add 100 points if the round num variable is 2 add 50 points if the round num variable is 3 add 25 points else add 10 points let's declare and initialize three Global variables round num Max rounds although I think this should in fact be a const and score in the initialize new game method let's set score to zero round num to zero and Shuffle in progress to false in the initialized new round method let's increment the round nump variable by 1. let's disable the gameplay button let's set the game and progress variable to true and let's set the card's revealed variable to false if you are not sure about the purpose of all these variables at the moment this will become clear as we develop the game so when around is started we want to update the status of the game in Black text let's call the update status element and pass in the text shuffling dot dot dot when a new round Begins the first thing that happens is the cards are shuffled let's go to our HTML file and add those elements responsible for outputting the score and round number to the user I'm also including a logo image for the game in the same row as the score and round elements which is just a stylistic choice let's create a global const to store the container element for the score let's create a global const to store the score element let's create a global const to store the container element for the round element let's create a global const to store the round element when a new game is started we want to make the score and round container elements visible and we want to update the score and round elements with the appropriate values when a new round is started we want to update the round element appropriately when a card is chosen by the user we want the relevant card to flip to the front so let's call the flip card method from within the choose card method then three seconds later we want all of the cards to be revealed to the user so that the user can see where the Ace of Spades is if the user did not guess where the Ace of Spades was correctly so we are using javascript's set timeout method to ensure that all the cards are flipped front side up three thousand milliseconds or three seconds after the user makes a guess so in order for the choose card method to be executed in response to a user clicking the back of a card we need to attach an appropriate event listener to each card element let's use javascript's add event listener method to ensure that our choose card method is called whenever a card is clicked let's run the code so don't worry about the layout I know the game logo here is huge we'll address the layout and styling issues a little bit later okay there seems to be a bug let's investigate so the issue here is that I've referred to round as opposed to the correct variable name which is round num so this is an easy fix so I need to make a few further modifications to the code to ensure that the choose card functionality works as expected we need to set the shuffle and progress variable to false at this point in the code IE this code executes once the shuffle process is completed at this point we also want appropriate output text shown to the user let's run the code great so to complete the choose card functionality we need to execute appropriate code that tests to see if the final round the fourth round has been reached by the user so let's write a method named end round so let's use the set timeout function to ensure that if the game is not yet over that the next round begins in three seconds or if the game is over that appropriate output text is presented to the user and a new round is not started so if the maximum round has been reached it's game over all rounds of the game have completed let's write a method named game over so when it's game over we want the score and the round number to be hidden and an appropriate game over output message to be displayed to the user notice how we are enveloping the relevant output in bactic characters the backtech characters allow us to include what is known as template literals in our JavaScript code if you'd like to read more about template literals please see an appropriate link that I've included Below in the description let's run the code okay I guessed where the Ace of Spades is correctly but the score hasn't been updated so let's update the code so that when the score changes the score element reflects this to the user excellent so when the game is first loaded we don't want the score and the round number elements displayed to the user so let's update the code accordingly great so we have pretty much completed the mechanics if you like for our game but the layout and style certainly needs attention so let's split our screen so that we can see our code editor next to our browser window let's go to our CSS file so let's update the header element so that the display is flex and the flex direction is set to column this positions its child elements one on top of the other as opposed to the default Direction which presents the elements next to each other on the same row and let's give the margin bottom property a value of 10 pixels let's style the header Dash title Dash container element and use the flexbox CSS functionality to Center our heading text great so let's use the flexgrid functionality for the display of the header Dash round Dash info Dash container element so that the image logo the score the round number are spaced evenly on the same row we'll see the effect of this styling code a little bit later so let's give all elements contained within the header Dash round Dash info Dash container element a width of 150 pixels so let's horizontally and vertically Center all of the elements contained within these elements by using the flexbox functionality so that Ace of Spades image you are currently seeing is of course way too big so let's give it a height of 75 pixels great let's round the corners of the image logo by setting its border radius property appropriately let's add in a border great and let's give the image a box shadow excellent lastly let's rotate the image minus three degrees great that looks pretty good let's add some color related variables to our CSS file let's style the badge class so that our score and round number text stands out excellent that play button really needs to be styled so let's go to this URL where we have a selection of button styles to choose from I like this one so let's press the relevant button to copy the relevant CSS style code to our clipboards let's paste the code into our style.css file and update the code appropriately so that the relevant code relates to our play game button great I want to use a particular Google font for this application so let's go to this URL here and let's copy the sample code for importing a font into our application from within our CSS stylesheet file then let's appropriately update the relevant import code so that we are importing the quicksand font let's create a variable to reference the relevant font family value let's set the font family property of our body element to the variable that we have just created great let's make the font size for the current status element bigger great let's align the text for the current status element centrally great the first animation I'd like to create is the shuffle animation at the moment during the shuffle process the cards are stacked one on top of the other and are motionless let's create the illusion through our Shuffle animation that the cards are literally being shuffled let's create a method named animate Shuffle that contains a parameter a numeric argument will be passed to this parameter which will be a numeric value that is incremented for every time the shuffle function is called let's create code to generate two random numbers between one and four let's reference two cards of our four cards randomly through the two random numbers that we are generating in this method then we can modify the positions of the cards and the relevant card elements Z index properties through code like this the mod function represented by the percentage character that I'm using in the first if statement means that when the result of the shuffle count value divided by 4 does not have a remainder then code will execute to toggle the shuffle left class for the relevant card element the mod function I'm using in the second if statement means that when the result of the shuffle count value divided by 10 does not have a remainder then code will execute to toggle the shuffle right class for the relevant card element the card elements are of course selected by our code at random this will create the illusion that the computer is shuffling the cards let's write the code that calls the animate Shuffle method from within the shuffle method let's create the CSS code for the shuffle left class and the shuffle right class and you can see that we are simply altering the positions of the cards through the shuffle left class and the shuffle right class you can of course play around with the various settings related to the shuffle animation until you are happy with the animation effect once shuffling is completed we want to make sure that none of the card elements contain the shuffle left clasp or the shuffle right class and that shuffle effect is not happening right so the reason is we need to include transition code for our card elements in the CSS file like this and I think that is a pretty good Shuffle effect but please play around with the relevant values and see if you can create an even better Shuffle effect the next animation effect that I want to create is for when the game is first loaded I want the cards to fly in from the top left hand side of the screen to their positions on the grid let's create a CSS class named flyian that will position the card elements appropriately off screen when the fly-in class is removed through our JavaScript code the card will move to its original position on the grid which ultimately results in a sort of fire and effect let's create a method named cardfly and effect that removes the fly in class from the card elements add controlled time intervals we are using the JavaScript set interval method to call the fly-in method at a predefined interval then we are further controlling when the fly and class is removed from the relevant card element through the use of an if statement we want to fly an effect to be executed when our game is first launched so let's call the fly and effect method from within the load game method let's add code so that the fly in CSS class is added to each card when each card is first created so to do this we can call code to add the fly and CSS class to the card element from within the create card method excellent the last animation effect I'd like to create is I want the gameplay button to not be visible when the game first loads but then slowly fade in once the fly-in animation effect has completed let's include keyframe functionality within our CSS file that controls the opacity of the relevant element let's then add this animation to our play game button element like this let's initialize the gameplay button to be invisible when the game is first launched then let's set its display CSS property to inline block after the fly and animation effect completes great but I want the height of the container to be static so let's set the height of the gameplay button container element within our CSS file I've also given this element a set width excellent so I've created our game so that it looks pretty good on desktop screens but what does our game look like on smaller screens like for example what would our game look like on an iPhone 12 it looks pretty good as it is on smaller screens because we are using CSS flexbox and grid functionality for the layout of our game but we could improve our layout for smaller screens so to make our application layout responsive for smaller screens let's include an appropriate media query within our CSS file so we want certain CSS classes to be dynamically modified in response to a smaller screen size so let's say that when our screen size is 600 pixels or less we want our layout to respond in a certain way at this smaller screen size we can for example make our cards smaller like this we can also adapt our card container element to respond appropriately to smaller screens with code like this let's make the height of the main element a bit smaller let's make the current status element a bit smaller let's make the gameplay button a bit smaller and let's also make our game logo image a bit smaller let's check the responsiveness of our application through our Chrome browsers excellent so our game is pretty much complete but I'd like to include functionality so that if a user closes the browser for some reason before the user has completed a game that the user is able to resume the same game when the game is launched at a later point in time the way we are able to create this functionality is by using local storage this allows us to persist data to our browser through our JavaScript code when the browser is closed the data stored in local storage is not lost and can't be retrieved from local storage through JavaScript code at a later time when the relevant game or application is launched in the user's browser so firstly let's write a few reusable methods to abstract common local storage related functionality so let's create a method named get serialized object as Json so we are going to persist an object to local storage in Json format so when we pass an object to this method it will return a string value in Json format that represents the object passed into this method we will then be able to save the return to string to local storage let's create a method named get object from Json when we read the Json formatted string from local storage we are going to want to convert the Json string back into a JavaScript object so that we can use the object in our JavaScript code let's create a method named update local storage this method saves a key value pair to local storage you can see the first parameter is the key which is the unique identifier for the value that will be passed into the second parameter which will of course be a string in Json format representing a JavaScript object let's create a method named remove local storage item this method of course is used for removing a local storage item let's write a method named update game object the object that we are going to persist to local storage contains the score and the round number pertaining to the relevant game this method can be used to update the relevant game object the game object object where the score and the round number will be stored will have Global scope then let's create a method that will handle saving the game object to local storage let's create a unique key to identify an incomplete game in local storage let's create a method named check for incomplete game the this method checks local storage for a unique key if the relevant key exists in local storage that means the user has data for an incomplete game saved to local storage oops I forgot to create a helper method let's create a method that returns a value from local storage based on the key argument passed into this method if the relevant local storage item exists we want to ask the user if the user wishes to continue with the relevant unfinished game so we are going to use the confirm JavaScript dialog for this purpose if the user presses the OK button then our code will update the game with the score and round number from the previous incomplete game saved to local storage else the score and round number will be initialized to zero which means the user has chosen to start a new game so let's call the check for incomplete game method from within the initia

Original Description

Improve your JavaScript skills by creating a basic card game with HTML and CSS. โ™ฃ๏ธโ™ฅ๏ธโ™ ๏ธโ™ฆ๏ธ This tutorial not only covers creating a basic card game using JavaScript but also: - how to create dynamic user interactive code using vanilla JavaScript - Creating some animation effects - Responsive layout design using CSS grid, CSS FlexBox and media queries - How to dynamically change the positions of grid cells, so as to randomize the positions of the cards contained in a css grid using JavaScript, - localStorage functionality - And much Moreโ€ฆ ๐Ÿ’ป Code: https://github.com/GavinLonDigital/HuntTheAceJSGame โœ๏ธ Gavin Lon created this tutorial. Check out his channel: https://www.youtube.com/@GavinLon โค๏ธ Try interactive JavaScript courses we love, right in your browser: https://scrimba.com/freeCodeCamp-JavaScript (Made possible by a grant from our friends at Scrimba) โญ๏ธ Contents โญ๏ธ โŒจ๏ธ (0:00:00) Introduction โŒจ๏ธ (0:05:26) Getting Started โŒจ๏ธ (0:07:00) Live Server Extension โŒจ๏ธ (0:09:50) Create Cards - HTML โŒจ๏ธ (0:14:44) Create the Game Play Grid โŒจ๏ธ (0:19:55) Create Cards Dynamically - JS Code โŒจ๏ธ (0:28:46) Initialise Card Positions โŒจ๏ธ (0:34:39) Load Game and Start Game โŒจ๏ธ (0:38:43) Stack Cards โŒจ๏ธ (0:41:53) Flip Cards โŒจ๏ธ (0:45:14) Shuffle Cards โŒจ๏ธ (0:49:28) Deal Cards โŒจ๏ธ (0:54:37) Choose Card โŒจ๏ธ (1:16:56) Styling and Layout โŒจ๏ธ (1:24:28) Animation โŒจ๏ธ (1:32:39) Responsive Layout โŒจ๏ธ (1:36:43) Local Storage ๐ŸŽ‰ Thanks to our Champion and Sponsor supporters: ๐Ÿ‘พ Nattira Maneerat ๐Ÿ‘พ Heather Wcislo ๐Ÿ‘พ Serhiy Kalinets ๐Ÿ‘พ Erdeniz Unvan ๐Ÿ‘พ Justin Hual ๐Ÿ‘พ Agustรญn Kussrow ๐Ÿ‘พ Otis Morgan -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news
Watch on YouTube โ†— (saves to browser)
Sign in to unlock AI tutor explanation ยท โšก30

Playlist

Uploads from freeCodeCamp.org ยท freeCodeCamp.org ยท 0 of 60

โ† Previous Next โ†’
1 React: Production Server Setup Part 2 - Live Coding with Jesse
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
2 cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
3 Browser history tutorial - Beau teaches JavaScript
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
4 Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
5 React: Parameterized Routing with Next.js - Live Coding with Jesse
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
6 React: Dealing with jQuery Issues - Live Coding with Jesse
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
7 setInterval and setTimeout: timing events - Beau teaches JavaScript
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
8 Browser and Device Testing - Live Coding with Jesse
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
9 Last Minute Updates - Live Coding with Jesse
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
10 Post Launch Updates - Live Coding with Jesse
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
11 React: Setting Up Google Analytics - Live Coding with Jesse
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
12 React: Masonry Layout - Live Coding with Jesse
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
13 Load Balancing Digital Ocean Droplets - Live Coding with Jesse
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
14 try, catch, finally, throw - error handling in JavaScript
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
15 Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
16 Graphs: breadth-first search - Beau teaches JavaScript
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
17 React: Masonry Layout Part 2 - Live Coding with Jesse
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
18 React: WordPress API Live Search - Live Coding with Jesse
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
19 Creating WordPress Custom Post Types - Live Coding With Jesse
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
20 Dates - Beau teaches JavaScript
Dates - Beau teaches JavaScript
freeCodeCamp.org
21 Miscellaneous Front End Updates - Live Coding with Jesse
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
22 Merging a Pull Request from GitHub - Live Coding with Jesse
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
23 React + Prettier + Standard JS - Live Coding with Jesse
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
24 React: Sortable Responsive Table - Live Coding with Jesse
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
25 Geolocation Sorting by Distance - Live Coding with Jesse
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
26 Tradeoff Matrix - Agile Software Development
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
27 The Definition of Ready - Agile Software Development
The Definition of Ready - Agile Software Development
freeCodeCamp.org
28 Getting first React job without experience - Ask Preethi
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
29 React: Google Analytics Click Tracking - Live Coding with Jesse
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
30 Submitting a PR to an Open Source Project - Live Coding with Jesse
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
31 Should I go back to school to get CS degree? - Ask Preethi
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
32 Hero Section CSS Changes - Live Coding with Jesse
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
33 Working Agreement - Agile Software Development
Working Agreement - Agile Software Development
freeCodeCamp.org
34 A day at Pennybox with Co-Founder Reji Eapen
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
35 React: Sorting and Filtering Data - Live Coding with Jesse
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
36 React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
37 React: Building a New UI - Live Coding with Jesse
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
38 Definition of Done - Agile Software Development
Definition of Done - Agile Software Development
freeCodeCamp.org
39 Getting started with jQuery (tutorial) - Beau teaches JavaScript
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
40 Making a React Blog with WordPress Content - Live Coding with Jesse
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
41 React, NextJS, CSS - Live Coding with Jesse
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
42 jQuery events - Beau teaches JavaScript
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
43 React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
44 React: Working with API Data - Live Coding with Jesse
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
45 React: Refactoring Components - Live Streaming with Jesse
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
46 jQuery effects - Beau teaches JavaScript
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
47 More React Refactoring - Live Coding with Jesse
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
48 animate in jQuery - Beau teaches JavaScript
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
49 "Finishing" My React Site - Live Coding with Jesse
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
50 Starting a New React Project (P2D1) - Live Coding with Jesse
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
51 React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
52 The Agile Manifesto - Agile Software Development
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
53 jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
54 React Project 2 Day 3 - Live Coding with Jesse
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
55 The INVEST approach to product backlog items
The INVEST approach to product backlog items
freeCodeCamp.org
56 React Project 2 Day 4 - Live Coding with Jesse
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
57 Chickens and Pigs - Agile Software Development
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
58 React Project 2 Day 5 - Live Coding with Jesse
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
59 jQuery: add and remove DOM elements - Beau teaches JavaScript
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
60 React Project 2 Day 6 - Live Coding with Jesse
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org

This video tutorial teaches how to create a basic card game using vanilla JavaScript, HTML, and CSS, covering topics such as dynamic user interaction, animation effects, and responsive layout design. The tutorial provides a comprehensive guide on how to develop a card game, including game logic, user interaction, and animation effects.

Key Takeaways
  1. Create a new folder for the project
  2. Create three files: index.html, index.js, and style.css
  3. Create a folder for images
  4. Use semantic HTML to create a header tag
  5. Use the Live Server extension to launch the application
  6. Install Live Server extension
  7. Launch application using Live Server
  8. Tile code editor and browser
  9. Create card statically using HTML and CSS
  10. Style card using CSS
๐Ÿ’ก The tutorial demonstrates how to use JavaScript to create dynamic user interactive code and develop a basic card game, highlighting the importance of responsive layout design and animation effects in game development.
๐Ÿ”’ Pro feature: Ask AI to explain this lesson โ†’

Related Reads

๐Ÿ“ฐ
Using the Publishโ€“Subscribe Pattern in React with Native Browser Events
Learn to simplify component communication in React using the publish-subscribe pattern with native browser events
Medium ยท JavaScript
๐Ÿ“ฐ
I built a small js library to enhance native html attributes instead of using a heavy UI component or writing tons of js
Enhance native HTML attributes with a lightweight JS library, reducing dependency on heavy UI components or extensive JS code
Reddit r/webdev
๐Ÿ“ฐ
Part 5A โ€” React Props Explained: Pass Data Between Components Like a Pro
Learn how to pass data between React components using props like a pro
Medium ยท Programming
๐Ÿ“ฐ
Why I built a CV maker with 0 dependencies, 0 backend, and 0 signups published: true
Learn how to build a CV maker with zero dependencies, backend, or signups, and why this approach matters for users' privacy and convenience
Dev.to ยท Belkacem Halim
Up next
Elementor Angie Ai Plugin Tutorial
Quick Tips - Web Desiign & Ai Tools
Watch โ†’