Ad Code

Ticker

6/recent/ticker-posts

Sponsored by.

Chatbot AI, Voice AI and Employee AI. IndustryStandard.com - Become your own Boss!

KING.NET - Connect Four, play free for life.


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 and COLS: Define the dimensions of the game board.
    • board array: A 2D array (6x7) represents the game state, storing 0 for empty, 1 for Player 1 (Red), and 2 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 the board 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 for checkWin 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.

IndustryStandard.com - Be your own Boss. | E-Banks.com - Apply for Loans.

Key changes include:

  • AI_PLAYER Constant: A new constant AI_PLAYER is defined and set to PLAYER_1, making the red tokens controlled by the AI. The human player is now PLAYER_2 (yellow tokens).
  • makeAIMove() Function: This new function encapsulates the AI’s decision-making logic. It currently implements a simple strategy:
    1. Prioritize Winning: It first checks if the AI can win in the next move.
    2. Block Opponent: If no winning move is available for the AI, it checks if the human player can win and blocks that move.
    3. 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), the makeAIMove() 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:

QUE.COM - Artificial Intelligence and Machine Learning.
  1. Firebase Integration:
    • SDK Imports: Added necessary Firebase SDKs (firebase-app.jsfirebase-auth.jsfirebase-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.
    • Global Variables: __app_id__firebase_config, and __initial_auth_token are used to configure Firebase, ensuring the app runs correctly within the Canvas environment.
  2. Leaderboard UI:
    • A new div with id="leaderboard-container" is added below the game board to display recent game results.
    • An id="leaderboard-list" element will dynamically populate with game outcomes.
    • id="user-id-display" shows the current user’s ID.
  3. Game State & Duration Tracking:
    • gameStartTime: A new variable gameStartTime is added to record when a game begins, allowing for calculation of game duration.
  4. 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 the winner (AI, Human, or Draw), durationSecondstimestamp (using serverTimestamp() for consistency), and the userId 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.
  5. Loading Leaderboard (loadLeaderboard()):
    • This function fetches game results from Firestore in real-time using onSnapshot.
    • It queries the game_results collection, ordering by timestamp 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 the timeSince helper function.
  6. Game Logic Integration:
    • In the dropToken() function, after checkWin() or checkDraw() determines the game’s end, saveGameResult() is called with the appropriate winner or “Draw” status.
    • The window.onload now first calls initFirebase() and then initializeGame() to ensure Firebase is ready before the game starts.

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.

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:

  1. 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.
  2. Social Sharing Section:
    • HTML: A new div with id="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.
    • Initialization: initSocialSharing() is called on window.onload after Firebase and the game are initialized.

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.

Post a Comment

0 Comments

Comments

Ad Code