How To Create Connect Four Game Using HTML, CSS, and JavaScript

codinglabsolution

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



How To Create Connect Four Game Using HTML, CSS, and JavaScript




Welcome to the world of game development! In this tutorial, we'll guide you through creating your own Connect Four game from scratch using HTML, CSS, and JavaScript. Whether you're a beginner or looking to expand your skills, this step-by-step guide will help you build an engaging project for your portfolio.

Source Code

Step 1 (HTML Code):


Begin by structuring your Connect Four game using HTML. Establish the framework for the game grid and include essential elements.


Breakdown:


1. <!DOCTYPE html>: Indicates the document type and version of HTML used (HTML5).

2. <html lang="en">: Opening tag for the HTML document, with the lang attribute set to "en" for English.

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

   - <meta charset="UTF-8">: Defines the character encoding as UTF-8.

   - <meta name="viewport" content="width=device-width, initial-scale=1.0">: Configures viewport settings for responsive design.

   - <title>Connect Four</title>: Sets the title of the web page.

   - Google Fonts are included for styling text on the page.

   - <link rel="stylesheet" href="styles.css">: Links an external CSS file (styles.css) for visual styling.

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

5. <div id="main-container">: Primary container holding all content.

   - <div id="player">: Section displaying information about the current player.

     - <h1 id="player-type">Player - 1</h1>: Indicates the current player, initially set to "Player - 1".

   - <div id="grid">: Represents the game grid.

     - The grid comprises rows containing buttons (<button> elements) for player interaction.

   - <button type="button" id="reset-btn">Play Again</button>: Button allowing players to start a new game.

6. <script src="script.js"></script>: Links an external JavaScript file (script.js) for dynamic functionality and interactivity.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Connect Four</title>

	<!-- Google Fonts -->
	<link rel="preconnect" href="https://fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap" rel="stylesheet">

	<!-- CSS -->
	<link rel="stylesheet" href="styles.css">

</head>
<body>

	<div id="main-container">

		<div id="player">

			<h1 id="player-type">Player - 1</h1>

		</div>

		<div id="grid">

			<div class="row">

				<div class="col">

					<button class="btn btn-1"></button>

				</div>

				<div class="col">

					<button class="btn btn-2"></button>

				</div>

				<div class="col">

					<button class="btn btn-3"></button>

				</div>

				<div class="col">

					<button class="btn btn-4"></button>

				</div>

				<div class="col">

					<button class="btn btn-5"></button>

				</div>

				<div class="col">

					<button class="btn btn-6"></button>

				</div>

				<div class="col">

					<button class="btn btn-7"></button>

				</div>

			</div>

			<div class="row">

				<div class="col">

					<button class="btn btn-8"></button>

				</div>

				<div class="col">

					<button class="btn btn-9"></button>

				</div>

				<div class="col">

					<button class="btn btn-10"></button>

				</div>

				<div class="col">

					<button class="btn btn-11"></button>

				</div>

				<div class="col">

					<button class="btn btn-12"></button>

				</div>

				<div class="col">

					<button class="btn btn-13"></button>

				</div>

				<div class="col">

					<button class="btn btn-14"></button>

				</div>

			</div>

			<div class="row">

				<div class="col">

					<button class="btn btn-15"></button>

				</div>

				<div class="col">

					<button class="btn btn-16"></button>

				</div>

				<div class="col">

					<button class="btn btn-17"></button>

				</div>

				<div class="col">

					<button class="btn btn-18"></button>

				</div>

				<div class="col">

					<button class="btn btn-19"></button>

				</div>

				<div class="col">

					<button class="btn btn-20"></button>

				</div>

				<div class="col">

					<button class="btn btn-21"></button>

				</div>

			</div>

			<div class="row">

				<div class="col">

					<button class="btn btn-22"></button>

				</div>

				<div class="col">

					<button class="btn btn-23"></button>

				</div>

				<div class="col">

					<button class="btn btn-24"></button>

				</div>

				<div class="col">

					<button class="btn btn-25"></button>

				</div>

				<div class="col">

					<button class="btn btn-26"></button>

				</div>

				<div class="col">

					<button class="btn btn-27"></button>

				</div>

				<div class="col">

					<button class="btn btn-28"></button>

				</div>

			</div>

			<div class="row">

				<div class="col">

					<button class="btn btn-29"></button>

				</div>

				<div class="col">

					<button class="btn btn-30"></button>

				</div>

				<div class="col">

					<button class="btn btn-31"></button>

				</div>

				<div class="col">

					<button class="btn btn-32"></button>

				</div>

				<div class="col">

					<button class="btn btn-33"></button>

				</div>

				<div class="col">

					<button class="btn btn-34"></button>

				</div>

				<div class="col">

					<button class="btn btn-35"></button>

				</div>

			</div>

			<div class="row">

				<div class="col">

					<button class="btn btn-36"></button>

				</div>

				<div class="col">

					<button class="btn btn-37"></button>

				</div>

				<div class="col">

					<button class="btn btn-38"></button>

				</div>

				<div class="col">

					<button class="btn btn-39"></button>

				</div>

				<div class="col">

					<button class="btn btn-40"></button>

				</div>

				<div class="col">

					<button class="btn btn-41"></button>

				</div>

				<div class="col">

					<button class="btn btn-42"></button>

				</div>

			</div>

		</div>

		<button type="button" id="reset-btn">Play Again</button>

	</div>

	<script src="script.js"></script>

</body>
</html>

Step 2 (CSS Code):


Enhance the visual appeal of your Connect Four game by applying CSS styles. Design the game elements, including the board, pieces, and overall layout, to provide an engaging user experience.


Breakdown:


1. Body Styles:

   - Sets the background color of the entire page to a light purple (#e9e7fd).


2. Main Container Styles:

   - Uses Flexbox to center its content both horizontally and vertically.

   - Ensures the container takes at least the full height of the viewport.


3. Player Styles:

   - Defines styles for the player container, including background color, border, border radius, padding, and fixed width.


4. Player Type Styles:

   - Specifies text styles for the player type, such as color, font family, letter spacing, text alignment, and text transformation.


5. Grid Styles:

   - Defines styles for the grid container, including background color, border, border radius, box shadow, padding, and maximum width.


6. Grid Row Styles:

   - Utilizes Flexbox to display its children (columns) in a row.


7. Grid Column Styles:

   - Specifies styles for grid columns, including alignment, background color, border, border radius, height, width, margin, and Flexbox properties.


8. Button Styles:

   - Defines styles for generic buttons, setting transparent background, no border, and transparent text.


9. Reset Button Styles:

   - Specifies styles for the reset button, including background, border, border radius, color, font family, size, padding, text transformation, and hover effect.


10. Player 1 and Player 2 Button Styles:

    - Sets styles for buttons specific to Player 1 and Player 2, including background color, border, border radius, color, height, and width.


11. Media Queries:

    - Adjusts styles based on the viewport width for responsive design.

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):


Animate your Connect Four game with JavaScript by implementing the game logic. Manage player moves, detect winning conditions, and ensure smooth gameplay. Here's a breakdown of the code:


1. DOM Variables:

   - buttons: Holds HTML elements representing the game grid cells.

   - reset: Holds the reset button element.

   - playerType: Displays the current player's turn.


2. Game Flow Variables:

   - playerNumber: Tracks the current player (either 1 or 2).

   - filledGrid: Represents the game board with a 2D array, initially filled with -1.

   - filledCells: Tracks the total filled cells on the board.


3. Board Initialization:

   - Initializes the filledGrid 2D array with all values set to -1.


4. Event Listeners:

   - Sets up an event listener for the reset button to call the resetBoard function.

   - Adds event listeners to each grid cell button, triggering the makeMove function when clicked.


5. makeMove Function:

   - Called when a player clicks a grid cell button.

   - Determines the row and column of the clicked cell, updates the board, and checks for a win.

   - Displays an alert and resets the board if a player wins.

   - Shows a draw alert if all cells are filled and no player wins.

   - Disables the clicked button to prevent further moves.


6. playerWon Function:

   - Checks if the current player has won by detecting 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;
		}
 	}

}

Source Code: Download Files

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!

Tags: connect fourhtmlcssjavascriptgame developmentweb developmentsource codeconnect four game tutorialhtml game programmingcss styling for gamesjavascript game logicweb-based connect four

إرسال تعليق

ملفات تعريف الارتباط
نستخدم ملفات تعريف الارتباط (Cookies) لفهم كيفية استخدامك لموقعنا وتحسين تجربتك في المحتوى والإعلانات. باستمرارك في تصفح الموقع، فإنك توافق على استخدامنا لملفات تعريف الارتباط وفقًا لسياسة الخصوصية لدينا.
أُووبس!
يبدو أن هناك خطأ ما في اتصالك بالإنترنت. يرجى الاتصال بالإنترنت وبدء التصفح مرة أخرى.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.