Site icon QUE.com

Connect Four Games against AI

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:

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:

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:

  1. 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.
    • 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.
    • A 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), durationSeconds, timestamp (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.

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:

  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.

Exit mobile version