## Vara Network 链上游戏案例 <img src="https://hackmd.io/_uploads/BkaFvOCgA.png" width="240" alt="GEAR"> ### Tac Tac Toe https://tictactoe.vara.network --- <img src="https://hackmd.io/_uploads/r1QFddAlC.png" width="1200" alt="GEAR"> --- ## 棋盘数据结构 (board) ``` 0 1 2 3 4 5 6 7 8 ``` 先手使用 `Mark::X`, 后手使用 `Mark::O` 符号,空白用`None` 表示 ``` pub enum Mark { X, O, } ``` `let board : Vec<Option<Mark>> = vec![None; 9]` --- ## 游戏实例 (GameInstance) ``` pub struct GameInstance { pub board: Vec<Option<Mark>>, pub player_mark: Mark, pub bot_mark: Mark, pub last_time: u64, pub game_over: bool, pub game_result: Option<GameResult>, } ``` 向入口函数发送消息更新游戏状态: - Init: `In<GameInit>` - Handle: `InOut<GameAction, Result<GameReply, GameError>>` --- ## 初始状态 (Init) 情况 1 :`[None; 9]` X:玩家 O:机器人 ``` () () () () () () () () () ``` 情况 2: `[None, None, None, None, Some(Mark::x), None, None, None, None]` X:机器人 O:玩家 ``` () () () () X () () () () ``` --- ## 终止状态 (GameResult) 棋盘理论上的状态: 3**9 = 19683 ``` pub enum GameResult { Player, Bot, Draw, } ``` 当有一方横向/纵向/对角线方向连成一线时即获胜 其余判定为平手 --- ## 获胜模式 ``` pub const VICTORIES: [[usize; 3]; 8] = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; ``` --- ## 玩家逻辑 ``` impl Game { fn player_move(&mut self, msg_source: &ActorId, step: u8) -> Result<GameReply, GameError> { you_move(); check_game_over()?; bot_move(); check_game_over()?; } } ``` ## 机器人算法 ``` fn make_move(game: &GameInstance) -> Option<usize> { ... } ``` --- ## 状态清理 游戏结束一分钟后自动清理链上状态 ``` fn send_messages(account: &ActorId, config: &Config) { msg::send_with_gas_delayed( exec::program_id(), GameAction::RemoveGameInstance { account_id: *account, }, config.gas_to_remove_game, 0, config.time_interval, ) .expect("Error in sending message"); } ``` --- ## References https://wiki.gear-tech.io/docs/examples/Gaming/tictactoe/ https://github.dev/gear-foundation/dapps/blob/master/contracts/tic-tac-toe/src/lib.rs --- # Questions <img src="https://hackmd.io/_uploads/SyK8P72d2.jpg" width="240" alt="GEAR"> <img src="https://hackmd.io/_uploads/By_kgE3_2.png" width="240" alt="VARA"> 课后答疑频道: https://t.me/Gear_CN
{"contributors":"[{\"id\":\"94262fbf-81ae-4ed7-933c-561a41bd977a\",\"add\":5806,\"del\":3365}]","title":"Tic Tac Toe","slideOptions":"{\"theme\":\"dark\",\"spotlight\":{\"enabled\":false},\"width\":1600,\"height\":900}","description":"Tic Tac Toe","image":"https://hackmd.io/_uploads/BJTlDdCxA.png"}
    226 views