Overview
The Tic-Tac-Toe example demonstrates how to implement game logic in Leo using structs, conditional statements, and helper functions. This example showcases state representation, input validation, and win condition checking.This example is located at
.circleci/tictactoe/ in the Leo repository and is actively tested in CI.Program Structure
Data Structures
Row Struct
Represents a single row in the game board:0u8: Empty cell1u8: Player 1’s mark2u8: Player 2’s mark
Board Struct
Represents the complete game board:Why Not Arrays?
Leo could represent the board as[[u8; 3]; 3], but this example uses structs to demonstrate:
- Custom type definitions
- Named field access
- Struct initialization
- Nested struct composition
Arrays would be more concise, but structs provide better readability for educational purposes.
Core Functions
Creating a New Game
0u8.
Usage:
Making a Move
player: The player making the move (1 or 2)row: The row (1, 2, or 3)col: The column (1, 2, or 3)board: The current game board
Board: The updated game boardu8: Winner (1 or 2) or 0 if no winner yet
Input Validation
- Player is either 1 or 2
- Row is between 1 and 3
- Column is between 1 and 3
Move Validation
- The target cell matches the row/col parameters
- The cell is empty (
== 0u8)
If the cell is already occupied, the board is returned unchanged (the move is silently ignored).
Helper Functions
Checking for a Winner
b: The game board to checkp: The player to check for (1 or 2)
true if the player has won, false otherwise
Win Conditions:
- Three in a row (horizontally)
- Three in a column (vertically)
- Three in a diagonal
Playing the Game
Step 1: Create a New Board
Step 2: Player 1 Makes a Move
Step 3: Player 2 Makes a Move
Continue Until Win
Keep making moves until one player wins:Running the Demo
Use the Run Script
Build the Program
View Generated Code
Key Language Features
Struct Initialization
Field Access
Conditional Logic
Early Return
return keyword.
Helper Functions
Improvements and Extensions
Add Draw Detection
Use Records for Private Games
Add Turn Validation
Store Games On-Chain
Testing
Create Test Inputs
Createinputs/tictactoe.in:
Run Tests
Related Examples
Token
More complex example with records and mappings
Lottery
Simpler example with randomness
Further Reading
Data Types
Learn more about structs and data types
Functions
Function documentation
Statements
Control flow guide
Built-in Types
Type reference