> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Hello World for Solana Game Development

> Get started building Solana games with a basic adventure game using the Anchor framework.

In this development guide, we will walk through a simple onchain game using the
Solana blockchain. This game, lovingly called _Tiny Adventure_, is a
beginner-friendly Solana program created using the
[Anchor framework](https://www.anchor-lang.com/docs). The goal of this program
is to show you how to create a simple game that allows players to track their
position and move left or right.

You'll build the program in an Anchor project on your computer, deploy it to a
local validator, and move the player with a TypeScript client.

If you need to familiarize yourself with the Anchor framework, feel free to
check out the [Anchor documentation](https://www.anchor-lang.com/docs).

## Getting Started

This guide uses the Anchor CLI, the Solana CLI, and Node.js. If you haven't
installed them yet,
[install the Solana development tools](/developers/docs/quickstart). The
installer sets up Rust, the Solana CLI, the Anchor CLI, Node.js, and Yarn. This
guide was tested with Anchor CLI 1.1.2 and Solana CLI 3.1.10, the pair the
installer sets up through AVM.

### Create the project

Create a project with a single-file program and a TypeScript setup:

```bash Terminal
anchor init tiny-adventure --template single --test-template mocha --package-manager yarn
cd tiny-adventure
```

`--template single` puts the whole program in one file,
`programs/tiny-adventure/src/lib.rs`. `--test-template mocha` sets up a
TypeScript project with Anchor's TypeScript client, `@anchor-lang/core`, which
the client in this guide uses. `--package-manager yarn` installs it with Yarn.
Without the flag, `anchor init` uses the first of pnpm, Yarn, and npm that it
finds. You won't use the starter test, which is written for the template's
counter program, so delete it:

```bash Terminal
rm tests/tiny-adventure.ts
```

### Initial Program Code

Replace the contents of `programs/tiny-adventure/src/lib.rs` with the code
below:

```rust lib.rs
use anchor_lang::prelude::*;

// Replace with your program ID (`anchor keys sync` sets it for you)
declare_id!("11111111111111111111111111111111");

#[program]
pub mod tiny_adventure {
    use super::*;

    // instruction handlers will go here
}

// structs will go here

fn print_player(player_position: u8) {
    if player_position == 0 {
        msg!("A Journey Begins!");
        msg!("o.......");
    } else if player_position == 1 {
        msg!("..o.....");
    } else if player_position == 2 {
        msg!("....o...");
    } else if player_position == 3 {
        msg!("........\\o/");
        msg!("You have reached the end! Super!");
    }
}
```

In this game, the player starts at position 0 and can move left or right. To
show the player's progress throughout the game, we'll use message logs to
display their journey.

The `declare_id!` placeholder is replaced with your program's address in
[Build and Deploy](#build-and-deploy).

## Defining the Game Data Account

The first step in building the game is to define a structure for the onchain
account that will store the player's position.

The `GameDataAccount` struct contains a single field, `player_position`, which
stores the player's current position as an unsigned 8-bit integer.

```rust lib.rs
use anchor_lang::prelude::*;

// Replace with your program ID (`anchor keys sync` sets it for you)
declare_id!("11111111111111111111111111111111");

#[program]
pub mod tiny_adventure {
    use super::*;

    ...
}

// Define the Game Data Account structure
#[account]
pub struct GameDataAccount {
    player_position: u8,
}

...
```

## Program Instructions

Our Tiny Adventure program consists of only 3
[instruction handlers](/developers/docs/core/instructions):

- `initialize` - sets up an onchain account to store the player's position
- `move_left` - lets the player move their position to the left
- `move_right` - lets the player move their position to the right

### Initialize Instruction

Our `initialize` instruction initializes the `GameDataAccount` if it does not
already exist, sets the `player_position` to 0, and prints some message logs.

The `initialize` instruction requires 3 accounts:

- `new_game_data_account` - the `GameDataAccount` we are initializing
- `signer` - the player paying for the initialization of the `GameDataAccount`
- `system_program` - a required account when creating a new account

```rust lib.rs
#[program]
pub mod tiny_adventure {
    use super::*;

    // Instruction to initialize GameDataAccount and set position to 0
    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.new_game_data_account.player_position = 0;
        msg!("A Journey Begins!");
        msg!("o.......");
        Ok(())
    }
}

// Specify the accounts required by the initialize instruction
#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init_if_needed,
        seeds = [b"level1"],
        bump,
        payer = signer,
        space = 8 + 1
    )]
    pub new_game_data_account: Account<'info, GameDataAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

...
```

In this example, a [program-derived address (PDA)](/developers/docs/core/pda) is used for
the `GameDataAccount` address. This enables us to deterministically locate the
address later on. It is important to note that the PDA in this example is
generated with a single fixed value as the seed (`level1`), limiting our program
to creating only one `GameDataAccount`. The `init_if_needed` constraint then
ensures that the `GameDataAccount` is initialized only if it doesn't already
exist.

`init_if_needed` is behind an Anchor Cargo feature because it can open a program
to re-initialization attacks: the instruction also runs when the account already
exists, so it must not reset data that you want to keep. Enable the feature in
`programs/tiny-adventure/Cargo.toml` by replacing the `anchor-lang` line under
`[dependencies]` with:

```toml programs/tiny-adventure/Cargo.toml
[dependencies]
anchor-lang = { version = "1.1.2", features = ["init-if-needed"] }
```

Without the feature, `anchor build` fails with
`init_if_needed requires that anchor-lang be imported with the init-if-needed cargo feature enabled`.

It is worth noting that the current implementation does not have any
restrictions on who can modify the `GameDataAccount`. This effectively
transforms the game into a multiplayer experience where everyone can control the
player's movement. Calling `initialize` again also sets the position back to 0.

Alternatively, you can use the signer's address as an extra seed in the
`initialize` instruction, which would enable each player to create their own
`GameDataAccount`.

### Move Left Instruction

Now that we can initialize a `GameDataAccount` account, let's implement the
`move_left` instruction which allows a player to update their `player_position`.

In this example, moving left simply means decrementing the `player_position`
by 1. We'll also set the minimum position to 0. The only account needed for this
instruction is the `GameDataAccount`.

```rust lib.rs
#[program]
pub mod tiny_adventure {
    use super::*;
    ...

    // Instruction to move left
    pub fn move_left(ctx: Context<MoveLeft>) -> Result<()> {
        let game_data_account = &mut ctx.accounts.game_data_account;
        if game_data_account.player_position == 0 {
            msg!("You are back at the start.");
        } else {
            game_data_account.player_position -= 1;
            print_player(game_data_account.player_position);
        }
        Ok(())
    }
}

// Specify the account required by the move_left instruction
#[derive(Accounts)]
pub struct MoveLeft<'info> {
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
}

...
```

### Move Right Instruction

Lastly, let's implement the `move_right` instruction. Similarly, moving right
will simply mean incrementing the `player_position` by 1. We'll also limit the
maximum position to 3.

Just like before, the only account needed for this instruction is the
`GameDataAccount`.

```rust lib.rs
#[program]
pub mod tiny_adventure {
    use super::*;
    ...

    // Instruction to move right
    pub fn move_right(ctx: Context<MoveRight>) -> Result<()> {
        let game_data_account = &mut ctx.accounts.game_data_account;
        if game_data_account.player_position == 3 {
            msg!("You have reached the end! Super!");
        } else {
            game_data_account.player_position = game_data_account.player_position + 1;
            print_player(game_data_account.player_position);
        }
        Ok(())
    }
}

// Specify the account required by the move_right instruction
#[derive(Accounts)]
pub struct MoveRight<'info> {
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
}

...
```

## Build and Deploy

We've now completed the Tiny Adventure program. Your final
`programs/tiny-adventure/src/lib.rs` should resemble the following:

```rust lib.rs
use anchor_lang::prelude::*;

// Replace with your program ID (`anchor keys sync` sets it for you)
declare_id!("11111111111111111111111111111111");

#[program]
pub mod tiny_adventure {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        ctx.accounts.new_game_data_account.player_position = 0;
        msg!("A Journey Begins!");
        msg!("o.......");
        Ok(())
    }

    pub fn move_left(ctx: Context<MoveLeft>) -> Result<()> {
        let game_data_account = &mut ctx.accounts.game_data_account;
        if game_data_account.player_position == 0 {
            msg!("You are back at the start.");
        } else {
            game_data_account.player_position -= 1;
            print_player(game_data_account.player_position);
        }
        Ok(())
    }

    pub fn move_right(ctx: Context<MoveRight>) -> Result<()> {
        let game_data_account = &mut ctx.accounts.game_data_account;
        if game_data_account.player_position == 3 {
            msg!("You have reached the end! Super!");
        } else {
            game_data_account.player_position = game_data_account.player_position + 1;
            print_player(game_data_account.player_position);
        }
        Ok(())
    }
}

fn print_player(player_position: u8) {
    if player_position == 0 {
        msg!("A Journey Begins!");
        msg!("o.......");
    } else if player_position == 1 {
        msg!("..o.....");
    } else if player_position == 2 {
        msg!("....o...");
    } else if player_position == 3 {
        msg!("........\\o/");
        msg!("You have reached the end! Super!");
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init_if_needed,
        seeds = [b"level1"],
        bump,
        payer = signer,
        space = 8 + 1
    )]
    pub new_game_data_account: Account<'info, GameDataAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct MoveLeft<'info> {
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
}

#[derive(Accounts)]
pub struct MoveRight<'info> {
    #[account(mut)]
    pub game_data_account: Account<'info, GameDataAccount>,
}

#[account]
pub struct GameDataAccount {
    player_position: u8,
}
```

Point `declare_id!` at your project's program address, then build the program:

```bash Terminal
anchor keys sync
anchor build
```

`anchor keys sync` reads the program keypair that `anchor init` created in
`target/deploy/tiny_adventure-keypair.json` and writes its address into
`declare_id!`. `anchor build` compiles the program to
`target/deploy/tiny_adventure.so`, and writes its IDL to
`target/idl/tiny_adventure.json` and the TypeScript types the client imports to
`target/types/tiny_adventure.ts`.

Next, start a local validator in a second terminal, and leave it running:

```bash Terminal
solana-test-validator
```

`solana-test-validator` runs a single-node Solana network on your computer, with
its RPC endpoint at `http://127.0.0.1:8899`. When it starts, it gives
500,000,000 SOL to your Solana CLI wallet, `~/.config/solana/id.json`, the same
wallet `Anchor.toml` uses, so you don't need devnet SOL. It keeps its state in a
`test-ledger` folder in the directory you start it from, so your program and the
game state survive a restart. To start over, stop it and run
`solana-test-validator --reset`, which also removes your program, so deploy it
again.

Back in the first terminal, deploy the program to the local validator:

```bash Terminal
anchor program deploy
```

`anchor program deploy` deploys the program that `anchor build` wrote to
`target/deploy` to the cluster set in `Anchor.toml`, which is `localnet`, the
local validator. The output shows your program's address:

```txt title="Output"
Deploying program: tiny_adventure
Program ID: Bf4B6VRTSPsn3h4bJhXWqP65Lob1uveabnvpCWro2aym
Skipping IDL deployment on localnet
```

<Warning>
  **`anchor build` or `anchor program deploy` fails?** Anchor 1.1 builds SBPF
  v0 programs. The test validator in Solana CLI 4.1 and later rejects deploying
  them, so `anchor program deploy` fails with
  `Detected sbpf_version required by the executable which are not enabled`.
  Without AVM, on Solana CLI 4.3 or later, `anchor build` already fails with
  `Platform tools v1.52 is incompatible with SBPFv3`.

  Run `solana --version` to see your active Solana CLI. To switch, install
  Anchor 1.1.2 with AVM, as the installer and
  [Install dependencies](/developers/docs/intro/installation/dependencies#install-anchor-cli)
  set it up: when you run `anchor`, AVM makes Solana CLI 3.1.10 your active
  release, and its test validator runs v0 programs. Then stop
  `solana-test-validator` and start it again. Anchor CLI 1.2 and later build
  SBPF v3 programs, which the newer test validators run.
</Warning>

## Get Started with the Client

This next section will guide you through a simple client-side implementation for
interacting with the game. We'll break down the code and provide detailed
explanations for each step.

Create a `client.ts` file in the project's root folder, next to `Anchor.toml`,
with the code below. Then add the code snippets from the following sections, in
order, inside the `main` function:

```ts client.ts
import * as anchor from "@anchor-lang/core";
import { Program } from "@anchor-lang/core";
import { TinyAdventure } from "./target/types/tiny_adventure";

async function main() {
  // Add the code from the following sections here.
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

### Connect to the Program

First, let's create a client for the program and print the wallet that plays
the game.

```ts client.ts
// `anchor run` passes the cluster and wallet from Anchor.toml
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
const program = anchor.workspace.tinyAdventure as Program<TinyAdventure>;

console.log("My address:", provider.wallet.publicKey.toBase58());
const balance = await provider.connection.getBalance(provider.wallet.publicKey);
console.log(`My balance: ${balance / anchor.web3.LAMPORTS_PER_SOL} SOL`);
```

`AnchorProvider.env()` connects to the cluster and loads the wallet that
`anchor run` passes to the script in the `ANCHOR_PROVIDER_URL` and
`ANCHOR_WALLET` environment variables, which come from `Anchor.toml`: the local
validator and `~/.config/solana/id.json`. That wallet pays for and signs every
transaction the client sends. `anchor.workspace.tinyAdventure` creates a client
for your program from the IDL that `anchor build` wrote to `target/idl`, and the
`TinyAdventure` type from `target/types` gives you typed instructions and
accounts.

### Derive the GameDataAccount Account Address

Next, let's derive the PDA for the `GameDataAccount` using the
`findProgramAddressSync` function.

> A [program-derived address (PDA)](/developers/docs/core/pda) is a unique address in the
> format of a public key, derived using the program's ID and additional seeds.

```ts client.ts
// Everyone who interacts with your program controls the character stored at this PDA
const [globalLevel1GameDataAccount] =
  anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("level1", "utf8")],
    program.programId
  );
```

### Initialize the Game State

Next, let's try to fetch the game data account using the PDA from the previous
step. If the account doesn't exist, we'll create it by invoking the `initialize`
instruction from our program.

```ts client.ts
let txHash: string;
let gameDataAccount;

try {
  gameDataAccount = await program.account.gameDataAccount.fetch(
    globalLevel1GameDataAccount
  );
} catch {
  // Check if the account is already initialized, otherwise initialize it
  txHash = await program.methods
    .initialize()
    .accountsPartial({
      newGameDataAccount: globalLevel1GameDataAccount,
      signer: provider.wallet.publicKey,
      systemProgram: anchor.web3.SystemProgram.programId
    })
    .rpc();

  console.log(`Use 'solana confirm -v ${txHash} --url localhost' to see the logs`);
  console.log("A journey begins...");
  console.log("o........");
}
```

`accountsPartial` lets you pass every account the instruction requires, as the
program's `Initialize` struct lists them. With `.accounts()` instead, the client
fills in the accounts it can work out from the IDL itself: the PDA, whose seeds
are in the IDL, the System Program, and the signer, which defaults to your
wallet. `.rpc()` signs the transaction with your wallet, sends it, and waits for
the validator to process it.

### Move Left and Right

Now we are ready to interact with the game by moving left or right. This is done
by invoking the `moveLeft` or `moveRight` instructions from the program by
submitting a transaction to the Solana network.

You can repeat this step as many times as you like. Each time, the move logic
runs onchain and updates the player's state.

```ts client.ts
// Here you can play around now, move left and right
txHash = await program.methods
  //.moveLeft()
  .moveRight()
  .accounts({
    gameDataAccount: globalLevel1GameDataAccount
  })
  .rpc();
console.log(`Use 'solana confirm -v ${txHash} --url localhost' to see the logs`);

gameDataAccount = await program.account.gameDataAccount.fetch(
  globalLevel1GameDataAccount
);

console.log("Player position is:", gameDataAccount.playerPosition.toString());
```

The `MoveLeft` and `MoveRight` structs don't give the `GameDataAccount` any
seeds, so the client can't work out its address from the IDL, and you pass it in
`.accounts()`.

### Logging the Player's Position

Lastly, let's use a `switch` statement to log the character's position based on
the `playerPosition` value stored in the `gameDataAccount`. We'll use this as a
visual representation of the character's movement in the game.

```ts client.ts
switch (gameDataAccount.playerPosition) {
  case 0:
    console.log("A journey begins...");
    console.log("o........");
    break;
  case 1:
    console.log("....o....");
    break;
  case 2:
    console.log("......o..");
    break;
  case 3:
    console.log(".........\\o/");
    break;
}
```

### Run the Client Program

Your `client.ts` should now look like this:

```ts client.ts expandable
import * as anchor from "@anchor-lang/core";
import { Program } from "@anchor-lang/core";
import { TinyAdventure } from "./target/types/tiny_adventure";

async function main() {
  // `anchor run` passes the cluster and wallet from Anchor.toml
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);
  const program = anchor.workspace.tinyAdventure as Program<TinyAdventure>;

  console.log("My address:", provider.wallet.publicKey.toBase58());
  const balance = await provider.connection.getBalance(provider.wallet.publicKey);
  console.log(`My balance: ${balance / anchor.web3.LAMPORTS_PER_SOL} SOL`);

  // Everyone who interacts with your program controls the character stored at this PDA
  const [globalLevel1GameDataAccount] =
    anchor.web3.PublicKey.findProgramAddressSync(
      [Buffer.from("level1", "utf8")],
      program.programId
    );

  let txHash: string;
  let gameDataAccount;

  try {
    gameDataAccount = await program.account.gameDataAccount.fetch(
      globalLevel1GameDataAccount
    );
  } catch {
    // Check if the account is already initialized, otherwise initialize it
    txHash = await program.methods
      .initialize()
      .accountsPartial({
        newGameDataAccount: globalLevel1GameDataAccount,
        signer: provider.wallet.publicKey,
        systemProgram: anchor.web3.SystemProgram.programId
      })
      .rpc();

    console.log(`Use 'solana confirm -v ${txHash} --url localhost' to see the logs`);
    console.log("A journey begins...");
    console.log("o........");
  }

  // Here you can play around now, move left and right
  txHash = await program.methods
    //.moveLeft()
    .moveRight()
    .accounts({
      gameDataAccount: globalLevel1GameDataAccount
    })
    .rpc();
  console.log(`Use 'solana confirm -v ${txHash} --url localhost' to see the logs`);

  gameDataAccount = await program.account.gameDataAccount.fetch(
    globalLevel1GameDataAccount
  );

  console.log("Player position is:", gameDataAccount.playerPosition.toString());

  switch (gameDataAccount.playerPosition) {
    case 0:
      console.log("A journey begins...");
      console.log("o........");
      break;
    case 1:
      console.log("....o....");
      break;
    case 2:
      console.log("......o..");
      break;
    case 3:
      console.log(".........\\o/");
      break;
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

To run it, add a `client` script to the `[scripts]` section of `Anchor.toml`,
below the `test` line that `anchor init` created:

```toml Anchor.toml
[scripts]
client = "npx tsx client.ts"
```

Then, with `solana-test-validator` still running, run the client:

```bash Terminal
anchor run client
```

`anchor run client` runs the script with `ANCHOR_PROVIDER_URL` and
`ANCHOR_WALLET` set from `Anchor.toml`. Running `npx tsx client.ts` on its own
fails with `ANCHOR_PROVIDER_URL is not defined`. The first time, `npx` downloads
[tsx](https://tsx.hirok.io), which runs TypeScript files directly. The output
should be similar to the following. Your address, balance, and transaction
signatures will differ:

```txt title="Output"
My address: ECtV7ekqb5wN6aEL1JLxxYzKMtXHRLzDsH8H1Pt37BMJ
My balance: 499999998.9706921 SOL
Use 'solana confirm -v 5dyWbnSY3BLyvdizLUJoJUPWXKCyP3VQbfuJ9hetQMfZjt1iZDssooLDqZyFdcVGgsHAeUkRHKHXQBG7jmcCEHAZ --url localhost' to see the logs
A journey begins...
o........
Use 'solana confirm -v Hpa8XwrKjuVpuYgBfwwabA2bK22VcsBQ4ckGu9mP5uechydj5XCC5eatXy251JWjB11QqoVXvw9WRphwL6JjKE8 --url localhost' to see the logs
Player position is: 1
....o....
```

The first run creates the `GameDataAccount`, then moves the player right. Run
`anchor run client` again, and the player moves to position 2, then 3. At
position 3, `move_right` logs `You have reached the end! Super!` and the player
stays where it is. To move left instead, comment out `.moveRight()` and
uncomment `.moveLeft()`.

To see the messages the program logged, run the `solana confirm` command that
the client printed for the move. The end of its output lists the logs:

```txt title="Output (excerpt)"
  Log Messages:
    Program Bf4B6VRTSPsn3h4bJhXWqP65Lob1uveabnvpCWro2aym invoke [1]
    Program log: Instruction: MoveRight
    Program log: ..o.....
    Program Bf4B6VRTSPsn3h4bJhXWqP65Lob1uveabnvpCWro2aym consumed 1596 of 200000 compute units
    Program Bf4B6VRTSPsn3h4bJhXWqP65Lob1uveabnvpCWro2aym success
```

You have built, deployed, and invoked the Tiny Adventure game from the client.

## What's Next?

With the basic game complete, unleash your creativity and practice building
independently by implementing your own ideas to enrich the game experience. Here
are a few suggestions:

1. Modify the in-game texts to create an intriguing story. To let a friend play
   through your custom narrative, deploy the program to devnet
   ([Deploy Program](/developers/docs/programs/build-first-program#deploy-program)
   shows how) and observe the onchain transactions as they happen.
2. Add a chest that rewards players with
   [SOL Rewards](/developers/cookbook/games/store-sol-in-pda) or let the player
   collect coins and
   [interact with tokens](/developers/cookbook/games/interact-with-tokens) as
   they progress through the game.
3. Create a grid that allows the player to move up, down, left, and right, and
   introduce multiple players for a more dynamic experience.

### Part Two

You can continue the guided development of our Tiny Adventure game, with this
guide [Tiny Adventure - Part Two](/developers/cookbook/games/store-sol-in-pda),
where we will demonstrate how to store SOL in the program and distribute it to
players as rewards.

### More Resources

You can also discover more Solana game development resources here:

- [Getting Started Guide](/developers/cookbook/games/getting-started-with-game-development)
- [Solana Gaming SDKs](/developers/docs/clients/community/game-sdks)
- [Learn by example](/developers/cookbook/games/game-examples)
- [Energy System](/developers/cookbook/games/energy-system)
- [NFTs in games](/developers/cookbook/games/nfts-in-games)
- [Token in games](/developers/cookbook/games/interact-with-tokens)
