1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use crate::{
    checks::ENABLED_CHECK,
    database::{
        model::TicTacToePlayer,
        TicTacToeCreateGameError,
    },
    ClientDataKey,
};
use serenity::{
    builder::{
        CreateAttachment,
        CreateMessage,
    },
    client::Context,
    framework::standard::{
        macros::command,
        Args,
        CommandResult,
    },
    model::prelude::*,
};
use tracing::error;

#[command]
#[description("Start a game of Tic-Tac-Toe")]
#[usage("<computer OR @user, X OR O>")]
#[example("computer X")]
#[min_args(2)]
#[max_args(2)]
#[checks(Enabled)]
#[bucket("default")]
pub async fn play(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
    let data_lock = ctx.data.read().await;
    let client_data = data_lock
        .get::<ClientDataKey>()
        .expect("missing client data");
    let tic_tac_toe_data = client_data.tic_tac_toe_data.clone();
    let db = client_data.db.clone();
    drop(data_lock);

    let opponent: TicTacToePlayer = match args.trimmed().single() {
        Ok(player) => player,
        Err(e) => {
            let response = format!(
                "Invalid opponent. Choose 'computer' or '@user'. Error: {}",
                e
            );
            msg.channel_id.say(&ctx.http, response).await?;
            return Ok(());
        }
    };

    let author_team: tic_tac_toe::Team = match args.trimmed().single() {
        Ok(team) => team,
        Err(e) => {
            let response = format!("Invalid team. Choose 'X' or 'O'. Error: {}", e);
            msg.channel_id.say(&ctx.http, response).await?;
            return Ok(());
        }
    };

    let author_id = msg.author.id;
    let guild_id = msg.guild_id;

    let game = match db
        .create_tic_tac_toe_game(guild_id.into(), author_id.into(), author_team, opponent)
        .await
    {
        Ok(game) => game,
        Err(TicTacToeCreateGameError::AuthorInGame) => {
            let response = "Finish your current game in this server before starting a new one. Use `tic-tac-toe concede` to end your current game.";
            msg.channel_id.say(&ctx.http, response).await?;
            return Ok(());
        }
        Err(TicTacToeCreateGameError::OpponentInGame) => {
            let response = "Your opponent is currently in another game in this server. Wait for them to finish.";
            msg.channel_id.say(&ctx.http, response).await?;
            return Ok(());
        }
        Err(TicTacToeCreateGameError::Database(e)) => {
            error!("{:?}", e);
            msg.channel_id.say(&ctx.http, "database error").await?;
            return Ok(());
        }
    };

    let game_board = game.board;
    let user = if let TicTacToePlayer::User(opponent_id) = opponent {
        // Cannot be a computer here as there are at least 2 human players at this point
        if author_team == tic_tac_toe::Team::X {
            author_id
        } else {
            opponent_id
        }
    } else {
        // The opponent is not a user, so it is a computer.
        // We already calculated the move and updated if the computer is X.
        // All that's left is to @author and print the board state.
        author_id
    };

    let file = match tic_tac_toe_data
        .renderer
        .render_board_async(game_board)
        .await
    {
        Ok(file) => CreateAttachment::bytes(file, format!("{}.png", game_board.encode_u16())),
        Err(error) => {
            error!("Failed to render Tic-Tac-Toe board: {error}");
            msg.channel_id
                .say(
                    &ctx.http,
                    format!("Failed to render Tic-Tac-Toe board: {error}"),
                )
                .await?;
            return Ok(());
        }
    };

    let message_builder = CreateMessage::new()
        .content(format!("Game created! Your turn {}", user.mention()))
        .add_file(file);
    msg.channel_id
        .send_message(&ctx.http, message_builder)
        .await?;

    Ok(())
}