How to Create Websites with HTML, CSS and Javascript

Building a minesweeper game using Javascript, HTML and CSS

Building a minesweeper game using Javascript, HTML and CSS

In this article, you'll learn how to build minesweeper using JavaScript, HTML and CSS. I also used jQuery, a JavaScript library that is helpful for interacting with html. Whenever you see a function call with a leading dollar sign, that is jQuery at work

In this article, you'll learn how to build minesweeper using JavaScript, HTML and CSS. I also used jQuery, a JavaScript library that is helpful for interacting with html. Whenever you see a function call with a leading dollar sign, that is jQuery at work

If you want to learn how to build minesweeper with JavaScript, the first step is understanding how the game works. Let’s jump right in and talk about the rules.

Rules of the Game
  1. The minesweeper board is a 10 x 10 square. We could make it other sizes, like the classic Windows version, but for demonstration purposes we will stick to the smaller, “beginner” version of the game.
  2. The board has a predetermined number of randomly placed mines. The player cannot see them.
  3. Cells can exist in one of two states: opened or closed. Clicking on a cell opens it. If a mine was lurking there, the game ends in failure. If there is no mine in the cell, but there are mines in one or more of its neighboring cells, then the opened cell shows the neighboring mine count. When none of the cell’s neighbors are mined, each one of those cells is opened automatically.
  4. Right clicking on a cell marks it with a flag. The flag indicates that the player knows there is a mine lurking there.
  5. Holding down the ctrl button while clicking on an opened cell has some slightly complicated rules. If the number of flags surrounding the cell match its neighbor mine count, and each flagged cell actually contains a mine, then all closed, unflagged neighboring cells are opened automatically. However, if even one of these flags was placed on the wrong cell, the game ends in failure.
  6. The player wins the game if he/she opens all cells without mines.
Data Structures

Cell

JavaScript code representing a minesweeper cell.

Each cell is an object that has several properties:

  • id: A string containing the row and column. This unique identifier makes it easier to find cells quickly when needed. If you pay close attention you will notice that there are some shortcuts I take related to the ids. I can get away with these shortcuts because of the small board size, but these techniques will not scale to larger boards. See if you can spot them. If you do, point them out in the comments!
  • row: An integer representing the horizontal position of the cell within the board.
  • column: An integer representing the vertical position of the cell within the board.
  • opened: This is a boolean property indicating whether the cell has been opened.
  • flagged: Another boolean property indicating whether a flag has been placed on the cell.
  • mined: Yet another boolean property indicating whether the cell has been mined.
  • neighborMineCount: An integer indicating the number of neighboring cells containing a mine.

Board

JavaScript code representing our game board.

Our board is a collection of cells. We could represent our board in many different ways. I chose to represent it as an object with key value pairs. As we saw earlier, each cell has an id. The board is just a mapping between these unique keys and their corresponding cells.

After creating the board we have to do two more tasks: randomly assign the mines and calculate the neighboring mine counts. We’ll talk more about these tasks in the next section.

Algorithms

Randomly Assign Mines

JavaScript code for randomly assigning mines to cells.

One of the first things we have to do before a game of minesweeper can be played is assign mines to cells. For this, I created a function that takes the board and the desired mine count as parameters.

For every mine we place, we must generate a random row and column. Furthermore, the same row and column combination should never appear more than once. Otherwise we would end up with less than our desired number of mines. We must repeat the random number generation if a duplicate appears.

As each random cell coordinate is generated we set the *mined *property to true of the corresponding cell in our board.

I created a helper function in order to help with the task of generating random numbers within our desired range. See below:

Helper function for generating random integers.

Calculate Neighbor Mine Count

JavaScript code for calculating the neighboring mine count of each cell.

Now let’s look at what it takes to calculate the neighboring mine count of each cell in our board.

You’ll notice that we start by looping through each row and column on the board, a very common pattern. This will allow us to execute the same code on each of our cells.

We first check if each cell is mined. If it is, there is no need to check the neighboring mine count. After all, if the player clicks on it he/she will lose the game!

If the cell is not mined then we need to see how many mines are surrounding it. The first thing we do is call our **getNeighbors **helper function, which returns a list of ids of the neighboring cells. Then we loop through this list, add up the number of mines, and update the cell’s *neighborMineCount *property appropriately.

Won’t you be my neighbor?

Let’s take a closer look at that **getNeighbors **function, as it will be used several more times throughout the code. I mentioned earlier that some of my design choices won’t scale to larger board sizes. Now would be a good time to try and spot them.

JavaScript code for getting all of the neighboring ids of a minesweeper cell.

The function takes a cell id as a parameter. Then we immediately split it into two pieces so that we have variables for the row and the column. We use the **parseInt **function, which is built into the JavaScript language, to turn these variables into integers. Now we can perform math operations on them.

Next, we use the row and column to calculate potential ids of each neighboring cell and push them onto a list. Our list should have eight ids in it before cleaning it up to handle special scenarios.

A minesweeper cell and its neighbors.

While this is fine for the general case, there are some special cases we have to worry about. Namely, cells along the borders of our game board. These cells will have less than eight neighbors.

In order to take care of this, we loop through our list of neighbor ids and remove any id that is greater than 2 in length. All invalid neighbors will either be -1 or 10, so this little check solves the problem nicely.

We also have to decrement our index variable whenever we remove an id from our list in order to keep it in sync.

Is it mined?

Okay, we have one last function to talk about in this section: isMined.

JavaScript function that checks if a cell is mined.

The **isMined **function is pretty simple. It just checks if the cell is mined or not. The function returns a 1 if it is mined, and a 0 if it is not mined. This feature allows us to sum up the function’s return values as we call it repeatedly in the loop.

That wraps up the algorithms for getting our minesweeper game board set up. Let’s move on to the actual game play.

Opening A Cell

JavaScript code that executes when a minesweeper cell is opened.

Alright let’s dive right into this bad boy. We execute this function whenever a player clicks on a cell. It does a lot of work, and it also uses something called recursion. If you are unfamiliar with the concept, see the definition below:

Recursion: See recursion.

Ah, computer science jokes. They always go over so well at bars and coffee shops. You really ought to try them out on that cutie you’ve been crushing on.

Anyways, a recursive function is just a function that calls itself. Sounds like a stack overflow waiting to happen, right? That’s why you need a base case that returns a value without making any subsequent recursive calls.

Our function will eventually stop calling itself because there will be no more cells that need to be opened. We could have written this code without recursion, but I thought you all might want to see an example of it in action.

Handle Click Explained

The **handleClick **function takes a cell id as a parameter. We need to handle the case where the player pressed the ctrl button while clicking on the cell, but we will talk about that in a later section.

Assuming the game isn’t over and we are handling a basic left click event, there are a few checks we need to make. We want to ignore the click if the player already opened or flagged the cell. It would be frustrating for the player if an inaccurate click on an already flagged cell ended the game.

If neither of those are true then we will proceed. If a mine is present in the cell we need to initiate the game over logic and display the exploded mine in red. Otherwise, we will open the cell.

If the opened cell has mines surrounding it we will display the neighboring mine count to the player in the appropriate font color. If there are no mines surrounding the cell, then it is time for our recursion to kick in. After setting the background color of the cell to a slightly darker shade of gray, we call **handleClick **on each unopened neighboring cell without a flag.

Helper Functions

Let’s take a look at the helper functions we are using inside the **handleClick **function. We’ve already talked about getNeighbors, so we’ll skip that one. Let’s start with the **loss **function.

JavaScript code that gets called whenever the player has lost the game.

When a loss occurs, we set the variable that tracks this and then display a message letting the player know that the game is over. We also loop through each cell and display the mine locations. Then we stop the clock.

Second, we have the **getNumberColor **function. This function is responsible for giving us the color corresponding to the neighboring mine count.

JavaScript code that gets passed a number and returns a color.

I tried to match up the colors just like the classic Windows version of minesweeper does it. Maybe I should have used a switch statement, but I already took the screen shot, and it’s not really a big deal. Let’s move on to what the code looks like for putting a flag on a cell.

Flagging A Cell

JavaScript code for putting a flag on a minesweeper cell.

Right clicking on a cell will place a flag on it. If the player right clicks on an empty cell and we have more mines that need to be flagged we will display the red flag on the cell, update its flagged property to true, and decrement the number of mines remaining. We do the opposite if the cell already had a flag. Finally, we update the GUI to display the number of mines remaining.

Opening Neighboring Cells

JavaScript code for handling ctrl + left click

We have covered the actions of opening cells and marking them with flags, so let’s talk about the last action a player can take: opening an already opened cell’s neighboring cells. The **handleCtrlClick **function contains the logic for this. This player can perform this action by holding ctrl and left clicking on an opened cell that contains neighboring mines.

The first thing we do after checking those conditions is build up a list of the neighboring flagged cells. If the number of flagged cells matches the actual number of surrounding mines then we can proceed. Otherwise, we do nothing and exit the function.

If we were able to proceed, the next thing we do is check if any of the flagged cells did not contain a mine. If this is true, we know that the player predicted the mine locations incorrectly, and clicking on all of the non-flagged, neighboring cells will end in a loss. We will need to set the local *lost *variable and call the **loss **function. We talked about the **loss **function earlier in the article.

If the player did not lose, then we will need to open up the non-flagged neighboring cells. We simply need to loop through them and call the **handleClick **function on each. However, we must first set the *ctrlIsPressed *variable to false to prevent falling into the **handleCtrlClick **function by mistake.

Starting A New Game

We are almost done analyzing all of the JavaScript necessary to build minesweeper! All that we have left to cover are the initialization steps necessary for starting a new game.

JavaScript code for initializing minesweeper

The first thing we do is initialize a few variables. We need some constants for storing the html codes for the flag and mine icons. We also need some constants for storing the board size, the number of mines, the timer value, and the number of mines remaining.

Additionally, we need a variable for storing if the player is pushing the ctrl button. We utilize jQuery to add the event handlers to the document, and these handlers are responsible for setting the *ctrlIsPressed *variable.

Finally, we call the **newGame **function and also bind this function to the new game button.

Helper Functions

JavaScript code for starting a new game of minesweeper.

Th **newGame **function is responsible for resetting our variables so that our game is in a ready-to-play state. This includes resetting the values that are displayed to the player, calling initializeCells, and creating a new random board. It also includes resetting the clock, which gets updated every second.

Let’s wrap things up by looking at initializeCells.

JavaScript code for attaching click handlers to cells and checking for the victory condition.

The main purpose of this function is to add additional properties to our html game cells. Each cell needs the appropriate id added so that we can access it easily from the game logic. Every cell also needs a background image applied for stylistic reasons.

We also need to attach a click handler to every cell so that we can detect left and right clicks.

The function that handles left clicks calls handleClick, passing in the appropriate id. Then it checks to see if every cell without a mine has been opened. If this is true then the player has won the game and we can congratulate him/her appropriately.

The function that handles right clicks calls handleRightClick, passing in the appropriate id. Then it simply returns false. This causes the context menu not to pop up, which is the default behavior of a right click on a web page. You wouldn’t want to do this sort of thing for a standard business CRUD application, but for minesweeper it is appropriate.

Conclusion

Congrats on learning how to build minesweeper with JavaScript! That was a lot of code, but hopefully it makes sense after breaking it up into modules like this. We could definitely make more improvements to this program’s reusability, extensibility, and readability. We also did not cover the HTML or CSS in detail. If you have questions or see ways to improve the code, I’d love to hear from you in the comments!

Build a Quiz App with HTML, CSS, and JavaScript

<strong>Build a Quiz App with HTML, CSS, and JavaScript to improve your Core Web Development skills!</strong>

Build a Quiz App with HTML, CSS, and JavaScript to improve your Core Web Development skills!

In this video, we will create a simple spinning loader in CSS that will be displayed until we are finished requesting/loading questions from the API.

Course Content: https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript


Learn More

The Web Developer Bootcamp

The Complete 2019 Web Development Bootcamp

The Complete Web Developer Course 2.0

Building Web APIs with ASP.NET Core

Build Progressive Web Apps with React

Build a web scraper with Node

Build a Basic Website with ASP.NET MVC and Angular

Build Your First PWA with Angular

Top 10 Podcasts for Web Developers

How to create a dual sliding panel using HTML, CSS and JavaScript

How to create a dual sliding panel using HTML, CSS and JavaScript

How to create a dual sliding panel using HTML, CSS and JavaScript? Solution: Check out this JavaScript Dual Sliding Panel With CSS, Responsive Panel Slide.

Today, you will learn to create Responsive Panel Slide with dual panel. Basically, there are two panels with 50% of the screen width and you can see only a title in each panel, but when you will click on the panel it will expand by 100% and you will see a quote and a background image. There are also two arrow buttons you can see, one is left arrow and other is right.

So, Today I am sharing JavaScript Dual Sliding Panel With CSS. There is a toggle feature you can open the panel on click and also can close the panel on another click. Also, this is a responsive design, the panel becomes top to bottom aligns on small screen size devices. This program will be very informative and useful for you.

If you are thinking now how the panels actually are, then see the preview given below.

Preview Of Responsive Panel Slide

See this video preview to getting an idea of how the dual panel looks like.


Now you can see this visually, you also can see it live by pressing the button above. If you like this, then get the source code of its.

JavaScript Dual Sliding Panel With CSS Source Code

Before sharing source code, let’s talk about it. First I have created all the divs and elements using HTML, on each panel, there has a heading, arrow button, quote, and an image. I have used SVG for creating the two arrow buttons, there I have not used any icon library. Also, I have used some tags between the divs like article tag, and section tag.

Now using CSS I have placed all the elements on the right place. Basically, there are two panels with 50% width first you can see only the heading and arrow. Using CSS I have hides the quote and image section firstly, you can see it after clicking then it will expand to single on 100% width. There is also a hover effect, when you will hover on any panel then its arrow icon starts moving.

For the responsive design, I have changed the position of the panels. On a desktop, the panel is placed as one in left and one in right but on a small screen, its becomes one in the top and another in the bottom. And when you will click on the panel to expand in small screen it will cover 100% of the height of the screen.

In there JavaScript handling the toggle feature. First JS fetches the panels using document.querySelector (info) and stored in variables. Now its read the click action and if the left panel has been clicked then its hide the right and expand the left panel. Left all other things you will understand after getting the codes, I can’t explain all in writing.

For Creating this program, you have to create 3 files. First for HTML, second for CSS, and third for JavaScript. Follow the steps to creating this without any error.

index.html

Create an HTML file named ‘index.html‘ and put these codes given below.

<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>JS Dual Sliding Panels | Webdevtrick.com</title>
  <meta name="viewport" content="width=device-width">
  <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
 
  <div class="container">
  <section class="panels">
    <article class="panel left-panel">
      <div class="panel inner-left-panel">
        <p>"Success is a lousy teacher. It seduces smart people into thinking they can't lose."</p>
      </div>
      <div class="panel name">
        <h1 class="title">Bill Gates</h1>      
        <svg class="arrow arrow-left" width="40" height="40" viewBox="0 0 24 24"><path d="M0 0h24v24h-24z" fill="none"/><path d="M20 11h-12.17l5.59-5.59-1.42-1.41-8 8 8 8 1.41-1.41-5.58-5.59h12.17v-2z"/></svg>
      </div>
    </article>
    <article class="panel right-panel">
      <div class="panel name">
        <h1 class="title">Steve Jobs</h1>
        <svg class="arrow arrow-right" width="40" height="40" viewBox="0 0 24 24"><path d="M0 0h24v24h-24z" fill="none"/><path d="M12 4l-1.41 1.41 5.58 5.59h-12.17v2h12.17l-5.58 5.59 1.41 1.41 8-8z"/></svg>
      </div>
      <div class="panel inner-right-panel">
        <p>"Design is not just what it looks like and feels like. Design is how it works."</p>
      </div>
    </article>
  </section>
</div>
 
  <script  src="function.js"></script>
 
</body>
</html>

style.css

Now create a CSS file named ‘style.css‘ and put these codes given here.

* {
  box-sizing: border-box;
  -webkit-tap-highlight-color: rgba(255,255,255,0);
  overflow-x: hidden;
}
body {
  font-family: 'Montserrat';
  line-height: 1.5;
  -webkit-font-smoothing: antialiased;
}
.container {
  height: 100vh;
  container: hidden;
}
.panels {
  width: 200%;
}
.panel {
  float: left;
  width: 50%;
  -webkit-perspective: 400px;
          perspective: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
}
.left-panel,
.right-panel {
  will-change: transform;
  position: relative;
  left: -25%;
  -webkit-transform: translate(0, 0);
          transform: translate(0, 0);
}
.left-panel {
  background: #fce77d;
}
.left-panel:hover .arrow {
  -webkit-transform: translate(-100%, -50%);
          transform: translate(-100%, -50%);
}
.right-panel {
  background: #f96167;
}
.right-panel:hover .arrow {
  -webkit-transform: translate(0, -50%);
          transform: translate(0, -50%);
}
.left-panel-active {
  -webkit-transform: translate(50%, 0);
          transform: translate(50%, 0);
}
.left-panel-active .inner-left-panel {
  -webkit-transform: rotateY(0);
          transform: rotateY(0);
}
.left-panel-active .arrow {
  -webkit-transform: translate(-50%, -50%) rotate(180deg) !important;
          transform: translate(-50%, -50%) rotate(180deg) !important;
}
.right-panel-active {
  -webkit-transform: translate(-50%, 0);
          transform: translate(-50%, 0);
}
.right-panel-active .inner-right-panel {
  -webkit-transform: rotateY(0);
          transform: rotateY(0);
}
.right-panel-active .arrow {
  -webkit-transform: translate(-50%, -50%) rotate(180deg) !important;
          transform: translate(-50%, -50%) rotate(180deg) !important;
}
.left-panel-hidden {
  -webkit-transform: translate(-50%, 0);
          transform: translate(-50%, 0);
}
.right-panel-hidden {
  -webkit-transform: translate(50%, 0);
          transform: translate(50%, 0);
}
.name {
  cursor: pointer;
}
.inner-left-panel,
.inner-right-panel,
.name {
  will-change: transform;
  padding: 0 5vw;
  height: 100vh;
}
.inner-left-panel {
  -webkit-transform-origin: right center;
          transform-origin: right center;
  -webkit-transform: rotateY(-90deg);
          transform: rotateY(-90deg);
  transition-delay: 0.1s;
  background: url("https://webdevtrick.com/wp-content/uploads/bill.jpg") center/cover;
}
.inner-left-panel:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fce77d;
  z-index: -1;
  opacity: 0.85;
}
.inner-right-panel {
  -webkit-transform-origin: left center;
          transform-origin: left center;
  -webkit-transform: rotateY(90deg);
          transform: rotateY(90deg);
  transition-delay: 0.1s;
  background: url("https://webdevtrick.com/wp-content/uploads/steve.jpg") center/cover;
}
.inner-right-panel:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f96167;
  z-index: -1;
  opacity: 0.85;
}
.title {
  margin: 0;
  font-size: 40px;
  text-align: center;
  color: #212121;
}
.panels p {
  font-size: 30px;
  margin: 0;
}
@media (max-width: 640px) {
  .panels {
    width: 100%;
    height: 200vh;
  }
  .panel {
    float: none;
    width: 100%;
    height: 100vh;
    display: block;
    text-align: center;
  }
  .left-panel,
  .right-panel {
    top: -25%;
    left: 0;
  }
  .left-panel:hover .arrow {
    -webkit-transform: translate(-50%, -80%) rotate(90deg);
            transform: translate(-50%, -80%) rotate(90deg);
  }
  .right-panel:hover .arrow {
    -webkit-transform: translate(-50%, -20%) rotate(90deg);
            transform: translate(-50%, -20%) rotate(90deg);
  }
  .left-panel-active {
    -webkit-transform: translate(0, 50%);
            transform: translate(0, 50%);
  }
  .left-panel-active .inner-left-panel {
    -webkit-transform: rotateX(0);
            transform: rotateX(0);
  }
  .left-panel-active .arrow {
    -webkit-transform: translate(-50%, -50%) rotate(-90deg) !important;
            transform: translate(-50%, -50%) rotate(-90deg) !important;
  }
  .right-panel-active {
    -webkit-transform: translate(0, -50%);
            transform: translate(0, -50%);
  }
  .right-panel-active .inner-right-panel {
    -webkit-transform: rotateX(0);
            transform: rotateX(0);
  }
  .right-panel-active .arrow {
    -webkit-transform: translate(-50%, -50%) rotate(-90deg) !important;
            transform: translate(-50%, -50%) rotate(-90deg) !important;
  }
  .left-panel-hidden {
    -webkit-transform: translate(0, -50%);
            transform: translate(0, -50%);
  }
  .right-panel-hidden {
    -webkit-transform: translate(0, 50%);
            transform: translate(0, 50%);
  }
  .inner-left-panel,
  .inner-right-panel,
  .name {
    height: 50vh;
    padding: 2vh 8vw;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .inner-left-panel {
    -webkit-transform-origin: center bottom;
            transform-origin: center bottom;
    -webkit-transform: rotateX(90deg);
            transform: rotateX(90deg);
  }
  .inner-right-panel {
    -webkit-transform-origin: center top;
            transform-origin: center top;
    -webkit-transform: rotateX(-90deg);
            transform: rotateX(-90deg);
  }
  .title {
    font-size: 32px;
  }
  .panels p {
    font-size: 20px;
  }
}
.arrow {
  position: absolute;
  top: 75%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  fill: #212121;
  border: 3px solid #212121;
  border-radius: 50%;
  transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1);
}
@media (max-width: 640px) {
  .arrow {
    -webkit-transform: translate(-50%, -50%) rotate(90deg);
            transform: translate(-50%, -50%) rotate(90deg);
  }
  .arrow-left {
    top: 25%;
  }
}

function.js

The final step, Create a JavaScript file named ‘function.js‘ and put the codes.

var Panels = (function() {
  
  var panelLeft = document.querySelector('.left-panel');
  var panelRight = document.querySelector('.right-panel');
 
  var openLeft = function() {
		panelLeft.classList.toggle('left-panel-active');
    panelRight.classList.toggle('right-panel-hidden');
  };
 
  var openRight = function() {
    panelRight.classList.toggle('right-panel-active');
    panelLeft.classList.toggle('left-panel-hidden');
  };
  
  var bindActions = function() {
    panelLeft.addEventListener('click', openLeft, false);
    panelRight.addEventListener('click', openRight, false);
  };
  
  var init = function() {
    bindActions();
  };
  
  return {
    init: init
  };

}());
 
Panels.init();

That’s It. Now you have successfully created JavaScript Dual Sliding Panel With CSSResponsive Panel Slide. If you have any doubt or question comment down below.

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

Thank you !