Anchor program
For starters, we will guide you through creating an Anchor program that gradually replenishes the player’s energy reserves over time. The energy will enable them to execute various actions within the game. In our example, a lumberjack will chop trees with every tree rewarding one wood and costing one energy point.Creating the player account
First the player needs to create an account which saves the state of our player. We will also save the Unix time stamp of the player’s last interaction with the program in thelast_login value. With this state, we will be able to calculate
how much energy the player has at a certain point in time. We also have a value
for how much wood the lumberjack cuts in the game.
Chopping trees
Then whenever the player calls thechop_tree instruction we will check if the
player has enough energy and reward them with one wood (by incrementing the
player’s wood count). The chop_tree function goes inside the #[program]
module next to init_player; the ErrorCode enum and the ChopTree accounts
struct go outside it. ChopTree loads the same player account, derived from the
player seed and the signer’s address.
Calculating the energy
The interesting part happens in theupdate_energy function. We check how much
time has passed and calculate the energy that the player will have at the given
time. We will do the same in the client. We lazily update the energy instead of
polling it all the time. This is a common technique in game development.
update_energy is a helper, not an instruction, so define it outside the
#[program] module (for example, below the account structs) together with the
two constants. The loop stops once the player has MAX_ENERGY, so energy never
goes above the maximum, however long the player has been away.
JavaScript client
Create connection
In the Anchor.ts file we create a connection to the Solana blockchain (in this case, devnet):confirmed. On Solana,
confirmed is equivalent to finalized: the block containing the transaction
has been certified by validators and can’t be reversed. This takes about 150
milliseconds after the block is produced, which is fast enough for games. New
code can use finalized directly.
Initialize player data
First, we will find the program address for the player account using the seed stringplayer and the player’s public key
(deriving the PDA). Then we call initPlayer to create the
account.
Subscribe to account updates
Next we will use websockets within the JavaScript client to subscribe and listen for changes on the player’s account. We use websockets here (over manually polling the RPC) because it is a faster way to get the changes.connection.onAccountChange creates a socket connection to the RPC node which
will push any changes that happen to the account to the client. We can then use
the program.coder to decode the account data into the TypeScript types and
directly use it in the game.