Onchain AI Composability - AI Powered Gaming With Chess

In this page, we will demonstrate how to build a simple AI-powered chess game utilizing the LLAMA model deployed on the Base blockchain.

Smart Contract Design Overview

The contract enables text-based chess games where users play as White against the contract's AI playing as Black. The game follows standard chess rules and uses a request-response mechanism with EternalAI's decentralized AI inference.

Key Contract Features:

  • Game Initialization: Creates a game session for the user.

  • Game Moves: Processes user moves and responds with AI-generated moves.

  • Game State Management: Keeps track of game states and contexts.

Key Functions

Creating a Game

This function initializes a new game for the player, creating a game session and requesting AI inference based on the initial game prompt.

function createGame() external {
    string memory request = buildRequest(initPlayingPrompt);
    playingContext[msg.sender] = initPlayingPrompt;
    uint256 inferenceId = AIKernel(kernel).infer(bytes(request));
    currentInferId[msg.sender] = inferenceId;
    emit GameCreated(msg.sender, inferenceId, request);
}

Making Moves

This function processes a player's move, validates it, and requests the AI's next move.

Basically, the function will:

  • validate the existence of a current game session.

  • fetch and verifies the inference result.

  • update the game context based on the player's move.

  • send a new inference request for the next move.

The complete code is available at: https://github.com/eternalai-org/eternal-ai/tree/master/examples/DagentPlayChess

You can run the code with the following command:

Note: replace <PRIVATE_KEY> with your actual wallet private key. Ensure that the wallet has sufficient ETH on the Base network to cover transaction fees and amounts.

Playing Chess

After deploying the contract to Base network, you can start playing chess with the AI-powered chess contract by running the following command which will create transactions into the contract.

Note: replace <PRIVATE_KEY> with your actual wallet private key. Ensure that the wallet has sufficient ETH on the Base network to cover transaction fees and amounts.

Below are transactions on Base we've created when playing chess with the chess contract.

  1. Create a new game by a player with address 0x62998e172240F4CC26EC10717d16a8D4442bf2Dd

  2. The 1st move

  3. The 2st move

At every step you can view the updated chess board in your terminal.

Last updated