Image courtesy by QUE.com
I'd be happy to share a Connect Four game for you! This will be a fun, interactive web application where you can play against a friend.
I'll provide a complete HTML file with embedded CSS for styling and JavaScript for the game logic. You'll be able to preview it directly.
This immersive document provides a complete Connect Four game.
Here's how it works:
- HTML Structure: Sets up the main game container, a display for the current player's turn, the game board itself, a message area for win/draw status, and a reset button.
- CSS Styling: Uses Tailwind CSS for basic layout and responsiveness, along with custom CSS to create the classic Connect Four board look (blue background, white circular holes). It also includes a subtle animation for dropping tokens.
- JavaScript Logic:
ROWS
andCOLS
: Define the dimensions of the game board.board
array: A 2D array (6x7
) represents the game state, storing0
for empty,1
for Player 1 (Red), and2
for Player 2 (Yellow).initializeGame()
: Sets up the board, clears previous game elements, and creates the clickable cells.handleBoardClick(event)
: This function is triggered when you click on the game board. It calculates which column was clicked based on the mouse position.dropToken(col)
: Finds the lowest empty slot in the clicked column, updates theboard
array, and visually places the token on the UI. It then checks for a win or a draw.checkWin(row, col)
: After each token drop, this function checks horizontally, vertically, and diagonally from the newly placed token to see if there are four consecutive tokens of the same color.checkLine(...)
: A helper function forcheckWin
that counts consecutive tokens in a given direction.checkDraw()
: Determines if all cells are filled without a winner.updatePlayerTurnDisplay()
: Updates the text and color indicating whose turn it is.resetButton
: Allows you to start a new game at any time.
You can click on any column to drop your token. The game will automatically switch players and announce the winner or a draw. Enjoy playing with your friends.
I will update the Connect Four game in the Canvas to include an AI for Player 1.
The Canvas for the Connect Four game has been updated to include an AI player.

Key changes include:
AI_PLAYER
Constant: A new constantAI_PLAYER
is defined and set toPLAYER_1
, making the red tokens controlled by the AI. The human player is nowPLAYER_2
(yellow tokens).makeAIMove()
Function: This new function encapsulates the AI's decision-making logic. It currently implements a simple strategy:- Prioritize Winning: It first checks if the AI can win in the next move.
- Block Opponent: If no winning move is available for the AI, it checks if the human player can win and blocks that move.
- Random Valid Move: If neither a winning move nor a blocking move is found, the AI makes a random valid move in an available column.
- AI Integration in
dropToken()
: After a human player's move, if it's the AI's turn (currentPlayer === AI_PLAYER
), themakeAIMove()
function is called with a 1-second delay (setTimeout
) to make the AI's move visible. handleBoardClick()
Modification: The click listener for the board now only responds to clicks if it's the human player's turn.updatePlayerTurnDisplay()
: The text for the player turn indicator now correctly reflects "AI's Turn (Red)" or "Your Turn (Yellow)".getNextAvailableRow()
: A new helper function to quickly find the next available row in a given column, used by the AI.- Improved
dropToken()
Feedback: A temporary message is displayed if the human player attempts to drop a token into a full column.
Now, when you play the game, Player 1 (Red) will be controlled by the AI, and you will play as Player 2 (Yellow). You can try to beat the AI!
More games at KING.NET
I will update the Connect Four game to include a leaderboard. This leaderboard will track the wins for the AI, wins for the human player, and draws, displaying them in real-time using Firestore for data persistence.
Here's the updated Connect Four game with the leaderboard:
The Connect Four game has been updated to include a leaderboard feature, powered by Firestore for real-time data persistence.
Key Additions and Changes:
- Firebase Integration:
- SDK Imports: Added necessary Firebase SDKs (
firebase-app.js
,firebase-auth.js
,firebase-firestore.js
) via CDN in the<head>
. - Initialization (
initFirebase()
):- Initializes Firebase app, Firestore (
db
), and Authentication (auth
). - Uses
onAuthStateChanged
to listen for authentication state. If a user is not signed in, it attempts to sign in anonymously or with a custom token provided by the environment. - The
userId
is displayed on the page for clarity, as required for multi-user apps using Firestore. - The leaderboard is loaded only after successful authentication.
- Initializes Firebase app, Firestore (
- Global Variables:
__app_id
,__firebase_config
, and__initial_auth_token
are used to configure Firebase, ensuring the app runs correctly within the Canvas environment.
- SDK Imports: Added necessary Firebase SDKs (
- Leaderboard UI:
- A new
div
withid="leaderboard-container"
is added below the game board to display recent game results. - An
id="leaderboard-list"
element will dynamically populate with game outcomes. - A
id="user-id-display"
shows the current user's ID.
- A new
- Game State & Duration Tracking:
gameStartTime
: A new variablegameStartTime
is added to record when a game begins, allowing for calculation of game duration.
- Saving Game Results (
saveGameResult()
):- This new asynchronous function is called when a game ends (win or draw).
- It calculates the
durationSeconds
of the game. - It uses
addDoc
to save thewinner
(AI, Human, or Draw),durationSeconds
,timestamp
(usingserverTimestamp()
for consistency), and theuserId
to a Firestore collection. - The collection path is set to
artifacts/${appId}/public/data/game_results
, adhering to the specified public data path for Firestore.
- Loading Leaderboard (
loadLeaderboard()
):- This function fetches game results from Firestore in real-time using
onSnapshot
. - It queries the
game_results
collection, ordering bytimestamp
in descending order and limiting to the last 10 games. - The
onSnapshot
listener ensures that the leaderboard updates automatically whenever a new game result is saved by any player. - It dynamically creates
div
elements to display each game's winner, duration, and how long ago it was played using thetimeSince
helper function.
- This function fetches game results from Firestore in real-time using
- Game Logic Integration:
- In the
dropToken()
function, aftercheckWin()
orcheckDraw()
determines the game's end,saveGameResult()
is called with the appropriate winner or "Draw" status. - The
window.onload
now first callsinitFirebase()
and theninitializeGame()
to ensure Firebase is ready before the game starts.
- In the
Now, every time a game of Connect Four concludes, the result will be recorded and displayed on the leaderboard, allowing you to see recent game outcomes.
Trying to fix the Leaderboard.
It sounds like you're encountering an issue with the leaderboard, and you'd like to add social sharing capabilities. I'll update the Connect Four game to address these points.

Regarding the Leaderboard Issue:
The current code for the leaderboard uses Firestore for data storage and real-time updates. If it's not working, the most common reason is often related to Firebase Security Rules. For the leaderboard to function correctly, your Firebase project's Firestore rules must allow authenticated users (including anonymously signed-in users) to read and write to the artifacts/{appId}/public/data/game_results
collection.
Please ensure your Firestore security rules are configured as follows:
Code snippet
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Public data for all users
match /artifacts/{appId}/public/data/{collectionId}/{document=**} {
allow read, write: if request.auth != null;
}
// Private data for specific users (if you were to implement private leaderboards later)
match /artifacts/{appId}/users/{userId}/{collectionId}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
If the rules are correctly set, please check your browser's developer console for any error messages related to Firebase or network requests, as these can provide more specific clues.
Adding Social Sharing:
I've added a new section with buttons to share your game on popular social networks like Facebook, Twitter (X), and LinkedIn.
Here's the updated Connect Four game with the leaderboard and social sharing features:
Summary of Updates:
- Leaderboard Debugging Notes: Added a prominent note in the conversational response about checking Firestore security rules, as this is the most frequent cause of leaderboard issues.
- Social Sharing Section:
- HTML: A new
div
withid="social-share-container"
is added below the leaderboard. It contains buttons for Facebook, Twitter (X), and LinkedIn, using Font Awesome icons for a professional look. - CSS: New styles are added for the social share container and buttons to ensure they are visually appealing and responsive.
- JavaScript (
initSocialSharing()
):- This new function dynamically sets the
href
attribute for each social sharing button. - It uses
window.location.href
to get the current URL of the game, allowing users to share the direct link to the game. - A generic
shareText
message is included, which you can customize. - The URLs are properly
encodeURIComponent
to handle special characters.
- This new function dynamically sets the
- Initialization:
initSocialSharing()
is called onwindow.onload
after Firebase and the game are initialized.
- HTML: A new
Now, you should have a functional Connect Four game with an AI opponent, a real-time leaderboard, and the ability to share your gaming experience on social networks. Remember to verify your Firebase security rules if the leaderboard still doesn't display data.
Play the Games at KING.NET, source code is open source.
Articles published by QUE.COM Intelligence via Telebit.com website.
0 Comments