Create Connect Four Game Using HTML, CSS, and JavaScript (Source Code)

Faraz

By Faraz -

Embark on a coding adventure! Follow our guide to build Connect Four using HTML, CSS, and JavaScript. Unleash your creativity in web development.


Create Connect Four Game Using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Welcome to the exciting world of game development! If you've ever wanted to improve your HTML, CSS, and JavaScript skills while creating your own online game, you've come to the right place. This comprehensive tutorial will walk you through creating a Connect Four game from scratch.

Whether you're a new web developer or just looking to add a fun project to your portfolio, this step-by-step guide will provide you with the knowledge and skills you need to fulfill your game development dreams. We'll start with the basics, setting up the HTML structure, and then move on to styling using CSS to make the game look good. Finally, we'll take a closer look at JavaScript to implement game logic to ensure a smooth and interactive gaming experience.

No prior game development experience is required, but knowledge of HTML, CSS, and JavaScript is helpful. Now turn your coding skills into an exciting game of Connect Four!

Source Code

Step 1 (HTML Code):

To begin, create the basic structure of your Connect Four game using HTML. Define the grid where the game will take place and set up the necessary elements.

Let's break the code down:

1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being used (HTML5 in this case).

2. <html lang="en">: The opening tag for the HTML document. The lang attribute is set to "en" for English, specifying the language of the document.

3. <head>: Contains meta-information about the HTML document, such as character set, viewport settings, and the page title.

  • <meta charset="UTF-8">: Sets the character encoding to UTF-8, which is a widely used character encoding for the web.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Configures the viewport settings for responsive design.
  • <title>Connect Four</title>: Sets the title of the web page, which is displayed in the browser's title bar or tab.
  • Google Fonts are included to style the text on the page.
  • <link rel="stylesheet" href="styles.css">: Links an external CSS file (styles.css) to the HTML document, providing styles for the visual presentation of the page.

4. <body>: Contains the content of the HTML document.

5. <div id="main-container">: The main container that holds all the content.

  • <div id="player">: Contains information about the current player.
  • <h1 id="player-type">Player - 1</h1>: Displays the current player, initially set to "Player - 1".
  • <div id="grid">: Represents the game grid.
  • The game grid consists of several rows, each containing buttons (represented by the <button> elements) that players can interact with.
  • <button type="button" id="reset-btn">Play Again</button>: A button with the ID "reset-btn" that allows players to start a new game.

6. <script src="script.js"></script>: Links an external JavaScript file (script.js) to the HTML document, providing dynamic functionality and interactivity to the page.

Step 2 (CSS Code):

Make your Connect Four game visually appealing by adding styles with CSS. Design the game board, pieces, and overall layout to enhance the user experience. let's break down the CSS code:

1. Body Styles:

body {
    background-color: #e9e7fd;
}
  • Sets the background color of the entire page to a light purple.

2. Main Container Styles:

#main-container {
    align-items: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 100vh;
}
  • Styles for the main container of the page.
  • Uses Flexbox to center its content both horizontally and vertically.
  • min-height: 100vh; ensures that the container takes at least the full height of the viewport.

3. Player Styles:

#player {
    background-color: #d5deff;
    border: 8px solid #4f3ff0;
    border-radius: 10px;
    margin-top: 50px;
    padding: 20px;
    width: 550px;
}
  • Styles for a player container.
  • Has a background color, border, border radius, and padding.
  • The width is fixed at 550 pixels.

4. Player Type Styles:

#player-type {
    color: #4f3ff0;
    font-family: "Poppins";
    letter-spacing: 5px;
    text-align: center;
    text-transform: uppercase;
}
  • Styles for the player type text inside the player container.
  • Uses the Poppins font family, has a specific color, letter spacing, and text transformation.

5. Grid Styles:

#grid {
    background-color: #4f3ff0;
    border: 3.5px solid #d5deff;
    border-radius: 8px;
    box-shadow: 2px 3px 7px grey;
    margin-top: 50px;
    max-width: 600px;
    padding: 3px;
}
  • Styles for a grid container.
  • Sets background color, border, border radius, box shadow, and padding.

6. Grid Row Styles:

.row {
    display: flex;
}
  • Styles for a grid row.
  • Uses Flexbox to display its children (columns) in a row.

7. Grid Column Styles:

.col {
    align-items: center;
    background-color: #d5deff;
    border: 1px solid  #4f3ff0;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    height: 75px;
    margin: 5px;
    width:  75px;
}
  • Styles for a grid column.
  • Uses Flexbox to center its content both horizontally and vertically.
  • Specifies height, width, background color, border, and border radius.

8. Button Styles:

.btn {
    background-color: transparent;
    border: none;
    color: transparent;
    height: 100%;
    padding: 0;
    width: 100%;
}
  • Styles for generic buttons.
  • Sets a transparent background, no border, and makes text transparent.

9. Reset Button Styles:

#reset-btn {
    background-color: transparent;
    border: 2px solid #4f3ff0;
    border-radius: 5px;
    color: #4f3ff0;
    font-family: "Poppins";
    font-size: 1.5rem;
    margin: 50px 0;
    padding: 10px 40px;
    text-transform: uppercase;
    transition: 0.7s;
}

#reset-btn:hover {
    background-color: #4f3ff0;
    color: #d5deff;
    cursor: pointer;
    transition: 0.7s;
}
  • Styles for a reset button and its hover effect.
  • Specifies background, border, border radius, color, font family, size, and padding.
  • On hover, the button changes its background and text color with a smooth transition.

10. Player 1 and Player 2 Button Styles:

.btn-player-1 {
    background-color: #34c471;
    border: 2px solid #34c471;
    border-radius: 50%;
    color: red;
    height:  50px;
    width: 50px;
}

.btn-player-2 {
    background-color: #df3670;
    border: 2px solid #df3670;
    border-radius: 50%;
    color: red;
    height:  50px;
    width: 50px;
}
  • Styles for buttons specific to Player 1 and Player 2.
  • Sets background color, border, border radius, color, height, and width.

11. Media Queries:

  • Adjust styles based on the viewport width.
body {
	background-color: #e9e7fd;
}

/* Main Container */

#main-container {

	align-items: center;
	display: flex;
	flex-direction: column;
	justify-content: center;
	min-height: 100vh;

}

/* Player Details */

#player {

	background-color: #d5deff;
	border: 8px solid #4f3ff0;
	border-radius: 10px;
	margin-top: 50px;
	padding: 20px;
	width: 550px;

}

#player-type {

	color: #4f3ff0;
	font-family: "Poppins";
	letter-spacing: 5px;
	text-align: center;
	text-transform: uppercase;

}

/* Grid */

#grid {

	background-color: #4f3ff0;
	border: 3.5px solid #d5deff;
	border-radius: 8px;
	box-shadow: 2px 3px 7px grey;
	margin-top: 50px;
	max-width: 600px;
	padding: 3px;

}

/* Grid Row */

.row {

	display: flex;

}

/* Grid Column */

.col {

	align-items: center;
	background-color: #d5deff;
	border: 1px solid  #4f3ff0;
	border-radius: 5px;
	display: flex;
	justify-content: center;
	height: 75px;
	margin: 5px;
	width:  75px;

}

/* Buttons */

.btn {

	background-color: transparent;
	border: none;
	color: transparent;
	height: 100%;
	padding: 0;
	width: 100%;

}

#reset-btn {

	background-color: transparent;
	border: 2px solid #4f3ff0;
	border-radius: 5px;
	color: #4f3ff0;
	font-family: "Poppins";
	font-size: 1.5rem;
	margin: 50px 0;
	padding: 10px 40px;
	text-transform: uppercase;
	transition: 0.7s;

}

#reset-btn:hover {

	background-color: #4f3ff0;
	color: #d5deff;
	cursor: pointer;
	transition: 0.7s;

}

/* Player - 1 Buttons */

.btn-player-1 {

	background-color: #34c471;
	border: 2px solid #34c471;
	border-radius: 50%;
	color: red;
	height:  50px;
	width: 50px;

}

/* Player - 2 Buttons */

.btn-player-2 {

	background-color: #df3670;
	border: 2px solid #df3670;
	border-radius: 50%;
	color: red;
	height:  50px;
	width: 50px;

}

/* Media Queries */

@media (max-width: 800px) {
	#grid {
		width: 500px;
	}

	.col {
		height: 62px;
		margin: 4px;
		width: 62px;
	}

	#player {
		width: 450px;
	}

	#reset-btn {
		font-size: 1.2rem;
	}

	.btn-player-1 {
		height: 40px;
		width: 40px;
	}

	.btn-player-2 {
		height: 40px;
		width: 40px;
	}
}

@media (max-width: 550px) {
	#grid {
		width: 400px;
	}

	.col {
		height: 50px;
		margin: 3px;
		width: 50px;
	}

	#player {
		width: 350px;
	}

	#reset-btn {
		font-size: 1rem;
	}

	.btn-player-1 {
		height: 30px;
		width: 30px;
	}

	.btn-player-2 {
		height: 30px;
		width: 30px;
	}
}

@media (max-width:  450px) {
	#grid {
		width: 90%;
	}

	.col {
		height: 40px;
		margin: 2px;
	}

	#player {
		align-items: center;
		display: flex;
		border-width: 5px;
		justify-content: center;
		height: 30px;
		width: 78%;
	}

	#player-type {
		font-size: 1.2rem;
	}

	#reset-btn {
		font-size: 0.8rem;
	}

	.btn-player-1 {
		height: 20px;
		width: 20px;
	}

	.btn-player-2 {
		height: 20px;
		width: 20px;
	}
} 

Step 3 (JavaScript Code):

Bring your Connect Four game to life by implementing the game logic using JavaScript. Handle player moves, check for a winning condition, and create a smooth gaming experience. Here's a breakdown of the code:

1. DOM Variables

  • buttons: It holds all the HTML elements with the class "btn". These represent the game grid cells.
  • reset: It holds the HTML element with the id "reset-btn". This is a button to reset the game.
  • playerType: It holds the HTML element with the id "player-type". This is used to display the current player's turn.

2. Game Flow Variables

  • playerNumber: It keeps track of the current player (either 1 or 2).
  • filledGrid: It is a 2D array representing the game board. Initially, all cells are filled with -1.
  • filledCells: It keeps track of the total number of cells that have been filled on the board.

3. Board Initialization

  • A loop initializes a 2D array filledGrid with all values set to -1.

4. Event Listeners

  • An event listener is set up for the reset button. When clicked, it calls the resetBoard function.
  • Event listeners are set up for each grid cell button. When clicked, it calls the makeMove function with the button clicked and its corresponding index.

5. makeMove Function

  • This function is called when a player makes a move by clicking a grid cell button.
  • It determines the row and column of the clicked cell, updates the game board, and checks for a win.
  • If a player wins, it displays an alert and resets the board.
  • If all cells are filled and no player has won, it displays a draw alert.
  • The clicked button is disabled to prevent further moves.

6. playerWon Function

  • Checks if the current player has won by checking for four consecutive cells in a row, column, or diagonal.

7. resetBoard Function

  • Resets the game board and UI elements.
  • Enables all buttons, removes player-specific styles, and resets variables.
// DOM Variables

var buttons = document.getElementsByClassName("btn");
var reset = document.getElementById("reset-btn");
var playerType = document.getElementById("player-type");

// Game Flow Variables

var playerNumber = 1; // Initially player - 1 gets to start his/her turn

var filledGrid = []; // Player board

var filledCells = 0; // No. of cells that has been filled

for(var i = 0; i < 6; i++) {

	var arr = [-1 , -1 , -1 , -1 , -1 , -1 , -1]; // Board is initialised with -1
	filledGrid.push(arr);

}


// Event Listener for Buttons

reset.addEventListener("click" , function() {

	resetBoard();

});

for(var i = 0; i < buttons.length; i++) {

	// Handing the Event when button was clicked

	buttons[i].addEventListener("click" , function() {

		// Make move and disable the button to avoid furthur clicking it again

		var buttonNo = this.classList[1];
		makeMove(this , buttonNo.slice(4));

	});

}


// Function to Make Move on the passed button and disable it
function makeMove(button , buttonNo) {

	var row = buttonNo % 7 === 0 ? Math.floor(buttonNo / 7) - 1 : Math.floor(buttonNo / 7);
	var col = buttonNo % 7 === 0 ? 6: (buttonNo % 7) - 1;

	if(playerNumber === 1) {

		button.classList.add("btn-player-1");


		filledGrid[row][col] = 1;
		filledCells++;


		if(playerWon(row , col , 1) === true) {
			setTimeout(function() {
				alert("Game Over: Green Wins");
				resetBoard();
			} , 200);
		}

		// Update the player
		playerNumber = 2;
		playerType.textContent = "Player - 2";

	} else {

		button.classList.add("btn-player-2");


		filledGrid[row][col] = 2;
		filledCells++;

		if(playerWon(row , col , 2) === true) {
			setTimeout(function() {
				alert("Game Over : Red Wins");
				resetBoard();
			} , 200);
		}

		// Update the player
		playerNumber = 1;
		playerType.textContent = "Player - 1";

	}

	// If all the cells has been filled

	if(filledCells === 42) {
		setTimeout(function() {
			alert("Game Draw");
			resetBoard();
		} , 200);
		return;
	}

	// Disable the button is the move is made
	setTimeout(function () {
		button.disabled = true;
	},10);

}

function playerWon(row , col , player) {

	var count = 0;

	// Check for columns

	for(var i = 0; i < 7; i++) {
		if(filledGrid[row][i] === player) {
			count++;
			if(count === 4) return true;
		} else {
			count = 0;
		}

	}

	count = 0;

	// Check for Rows

	for(var i = 0; i < 6; i++) {
		if(filledGrid[i][col] === player) {
			count++;
			if(count === 4) return true;
		} else {
			count = 0;
		}
	}


	count = 0;

	// Check for primary diagonal

	if(row >= col) {

		var i = row - col;
		var j = 0;

		for(; i <= 5; i++ , j++) {
			if(filledGrid[i][j] === player) {
				count++;
				if(count == 4) return true;
			} else {
				count = 0;
			}
		}
	} else {

		var i = 0;
		var j = col - row;

		for(; j <= 6; i++ , j++) {
			if(filledGrid[i][j] === player) {
				count++;
				if(count == 4) return true;
			} else {
				count = 0;
			}
		}

	}

	count = 0;

	// Check for secondary diagonal

	if(row + col <= 5) {

		var i = row + col;
		var j = 0;

		for(; i >= 0 && j <= row + col; i-- , j++) {
			if(filledGrid[i][j] === player) {
				count++;
				if(count == 4) return true;
			} else {
				count = 0;
			}
		}

	} else {

		var i = 5;
		var j = row + col - 5;

		for(; j <= 6; j++ , i--) {
			if(filledGrid[i][j] === player) {
				count++;
				if(count == 4) return true;
			} else {
				count = 0;
			}
		}

	}
	return false;

}

// Function to reset the Board completely
function resetBoard() {

	// Remove all the disabled buttons and the styles

	for(var i = 0; i < buttons.length; i++) {
		buttons[i].disabled = false;
		buttons[i].classList.remove("btn-player-1");
		buttons[i].classList.remove("btn-player-2");
	}


	// Player Number is changed to 1

	playerNumber = 1;
	playerType.textContent = "Player - 1";


	// Filled Cells is changed to 0

	filledCells = 0;


	// Filling the Board with -1

	for(var i = 0; i < 6; i++) {
		for(var j = 0; j < 7; j++) {
			filledGrid[i][j] = -1;
		}
 	}

}

Final Output:

Create Connect Four Game Using HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations! You've successfully created a Connect Four game using HTML, CSS, and JavaScript. Reflect on your learning journey and consider additional features or improvements for future projects. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺