tcg_ai 0.1.0

Pokemon TCG game engine AI controllers
Documentation
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! ReAct AI implementation for Pokemon TCG.
//!
//! This module provides a ReAct-style AI agent that uses an LLM to make decisions.
//! It implements the `AiController` trait to be compatible with the game engine.

use std::sync::{Arc, Mutex};
use rand::seq::SliceRandom;
use rand_chacha::ChaCha8Rng;
use rand::SeedableRng;

use tcg_core::{Action, GameView, Prompt};
use crate::traits::AiController;
use super::render::render_game_view;
use super::action_parser::{parse_response, ParsedResponse};

/// Configuration for the ReAct AI.
#[derive(Debug, Clone)]
pub struct ReactAiConfig {
    /// System prompt for the LLM.
    pub system_prompt: String,
    /// Temperature for LLM sampling.
    pub temperature: f32,
    /// Maximum tokens for LLM response.
    pub max_tokens: u32,
    /// Whether to include reasoning in prompts.
    pub include_reasoning: bool,
    /// Fallback to random action on parse failure.
    pub fallback_to_random: bool,
}

impl Default for ReactAiConfig {
    fn default() -> Self {
        Self {
            system_prompt: DEFAULT_SYSTEM_PROMPT.to_string(),
            temperature: 0.3,
            max_tokens: 256,
            include_reasoning: true,
            fallback_to_random: true,
        }
    }
}

/// Default system prompt for the ReAct AI.
pub const DEFAULT_SYSTEM_PROMPT: &str = r#"You are an expert Pokemon TCG player. Analyze the game state and choose the best action.

IMPORTANT: Respond with ONLY a JSON object in this format:
{"action": "<action_type>", "card_id": <id>, "target_id": <id>, "reason": "<brief reasoning>"}

Action types and their required fields:
- PlayBasic: card_id (play a basic Pokemon to bench)
- AttachEnergy: energy_id, target_id (attach energy to Pokemon)
- EvolveFromHand: card_id, target_id (evolve a Pokemon)
- PlayTrainer: card_id (play a trainer card)
- DeclareAttack: attack (name of the attack)
- Retreat: to_bench_id (switch active with benched Pokemon)
- EndTurn: (end your turn)
- ChooseActive: card_id (choose starting active)
- ChooseBench: card_ids (comma-separated IDs for bench)
- ChooseNewActive: card_id (choose new active after KO)

Strategy tips:
1. Prioritize knocking out opponent Pokemon for prizes
2. Attach energy to power up attacks
3. Evolve Pokemon when possible for higher HP and better attacks
4. Consider type matchups (weakness = 2x damage)
5. Manage your bench for backup attackers
6. Use trainer cards for card advantage

Respond with the single best action based on the current game state."#;

/// Trait for LLM providers.
pub trait LlmProvider: Send + Sync {
    /// Generate a response from the LLM.
    fn generate(&self, system: &str, user: &str, config: &ReactAiConfig) -> Result<String, String>;
}

/// A placeholder LLM provider that returns instructions for manual implementation.
/// Replace this with actual API calls to OpenAI, Anthropic, etc.
#[derive(Clone)]
pub struct PlaceholderLlmProvider;

impl LlmProvider for PlaceholderLlmProvider {
    fn generate(&self, _system: &str, _user: &str, _config: &ReactAiConfig) -> Result<String, String> {
        Err("LLM provider not implemented. Implement LlmProvider trait with your API.".to_string())
    }
}

/// Synchronous LLM provider wrapper for async APIs.
/// This allows wrapping async LLM calls for use in the sync AiController interface.
pub struct SyncLlmWrapper<F>
where
    F: Fn(&str, &str, &ReactAiConfig) -> Result<String, String> + Send + Sync,
{
    pub call_fn: F,
}

impl<F> LlmProvider for SyncLlmWrapper<F>
where
    F: Fn(&str, &str, &ReactAiConfig) -> Result<String, String> + Send + Sync,
{
    fn generate(&self, system: &str, user: &str, config: &ReactAiConfig) -> Result<String, String> {
        (self.call_fn)(system, user, config)
    }
}

/// ReAct AI agent for Pokemon TCG.
pub struct ReactAi {
    /// Configuration for the AI.
    config: ReactAiConfig,
    /// LLM provider for generating responses.
    llm: Arc<dyn LlmProvider>,
    /// Random number generator for fallback.
    rng: Mutex<ChaCha8Rng>,
    /// History of actions taken (for debugging/analysis).
    history: Mutex<Vec<ActionHistoryEntry>>,
    /// TODO list maintained across turns.
    todo_list: Mutex<Vec<String>>,
}

/// Entry in the action history.
#[derive(Debug, Clone)]
pub struct ActionHistoryEntry {
    pub game_state_summary: String,
    pub llm_response: Option<String>,
    pub parsed_action: Option<Action>,
    pub error: Option<String>,
}

impl ReactAi {
    /// Create a new ReactAi with default configuration.
    pub fn new(seed: u64) -> Self {
        Self::with_config(seed, ReactAiConfig::default(), Arc::new(PlaceholderLlmProvider))
    }

    /// Create a new ReactAi with custom configuration and LLM provider.
    pub fn with_config(seed: u64, config: ReactAiConfig, llm: Arc<dyn LlmProvider>) -> Self {
        Self {
            config,
            llm,
            rng: Mutex::new(ChaCha8Rng::seed_from_u64(seed)),
            history: Mutex::new(Vec::new()),
            todo_list: Mutex::new(vec![
                "Assess board state".to_string(),
                "Build up attackers".to_string(),
                "Take prize cards".to_string(),
            ]),
        }
    }

    /// Create a new ReactAi with a custom LLM call function.
    pub fn with_llm_fn<F>(seed: u64, call_fn: F) -> Self
    where
        F: Fn(&str, &str, &ReactAiConfig) -> Result<String, String> + Send + Sync + 'static,
    {
        Self::with_config(
            seed,
            ReactAiConfig::default(),
            Arc::new(SyncLlmWrapper { call_fn }),
        )
    }

    /// Get the action history.
    pub fn get_history(&self) -> Vec<ActionHistoryEntry> {
        self.history.lock().unwrap().clone()
    }

    /// Get the current TODO list.
    pub fn get_todo_list(&self) -> Vec<String> {
        self.todo_list.lock().unwrap().clone()
    }

    /// Build the user prompt from the game view.
    fn build_user_prompt(&self, view: &GameView) -> String {
        let mut parts = Vec::new();

        // Render game state
        parts.push(render_game_view(view));

        // Add TODO list
        let todos = self.todo_list.lock().unwrap();
        if !todos.is_empty() {
            parts.push(String::new());
            parts.push("=== YOUR TODO LIST ===".to_string());
            for (i, todo) in todos.iter().enumerate() {
                parts.push(format!("{}. {}", i + 1, todo));
            }
        }

        parts.push(String::new());
        parts.push("Choose your action and respond with JSON.".to_string());

        parts.join("\n")
    }

    /// Query the LLM for an action.
    fn query_llm(&self, view: &GameView) -> Result<ParsedResponse, String> {
        let user_prompt = self.build_user_prompt(view);

        let response = self.llm.generate(&self.config.system_prompt, &user_prompt, &self.config)?;

        parse_response(&response, view)
            .map_err(|e| format!("Parse error: {}", e))
    }

    /// Add an entry to the action history.
    fn log_action(&self, summary: String, response: Option<String>, action: Option<Action>, error: Option<String>) {
        let entry = ActionHistoryEntry {
            game_state_summary: summary,
            llm_response: response,
            parsed_action: action,
            error,
        };
        self.history.lock().unwrap().push(entry);
    }

    /// Update TODO list with new items.
    fn update_todos(&self, new_todos: Vec<String>) {
        if !new_todos.is_empty() {
            let mut todos = self.todo_list.lock().unwrap();
            for todo in new_todos {
                if !todos.contains(&todo) {
                    todos.push(todo);
                }
            }
            // Keep list manageable
            while todos.len() > 10 {
                todos.remove(0);
            }
        }
    }

    /// Generate a random fallback action.
    fn random_fallback_action(&self, view: &GameView) -> Option<Action> {
        let hints = &view.action_hints;
        let mut rng = self.rng.lock().unwrap();

        // Build list of possible actions
        let mut actions = Vec::new();

        // Play basics
        for id in &hints.playable_basic_ids {
            actions.push(Action::PlayBasic { card_id: *id });
        }

        // Attach energy
        for energy_id in &hints.playable_energy_ids {
            for target_id in &hints.attach_targets {
                actions.push(Action::AttachEnergy {
                    energy_id: *energy_id,
                    target_id: *target_id,
                });
            }
        }

        // Evolutions
        for (evo_id, targets) in &hints.evolve_targets_by_card_id {
            for target_id in targets {
                actions.push(Action::EvolveFromHand {
                    card_id: *evo_id,
                    target_id: *target_id,
                });
            }
        }

        // Trainers
        for id in &hints.playable_trainer_ids {
            actions.push(Action::PlayTrainer { card_id: *id });
        }

        // Attack
        if hints.can_declare_attack {
            for attack in &hints.usable_attacks {
                actions.push(Action::DeclareAttack { attack: attack.clone() });
            }
        }

        // End turn
        if hints.can_end_turn {
            actions.push(Action::EndTurn);
        }

        actions.choose(&mut *rng).cloned()
    }

    /// Generate a random prompt response.
    fn random_prompt_response(&self, view: &GameView, prompt: &Prompt) -> Vec<Action> {
        let mut rng = self.rng.lock().unwrap();

        match prompt {
            Prompt::ChooseStartingActive { options } => {
                if let Some(id) = options.choose(&mut *rng) {
                    vec![Action::ChooseActive { card_id: *id }]
                } else {
                    vec![]
                }
            }

            Prompt::ChooseBenchBasics { options, min, max } => {
                let count = (*min).max(1).min(*max).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(count);
                vec![Action::ChooseBench { card_ids: ids }]
            }

            Prompt::ChooseAttack { attacks } => {
                if let Some(attack) = attacks.choose(&mut *rng) {
                    vec![Action::DeclareAttack { attack: attack.clone() }]
                } else {
                    vec![Action::CancelPrompt]
                }
            }

            Prompt::ChooseCardsFromDeck { options, count, min, max, .. } => {
                let min_val = min.unwrap_or(*count);
                let max_val = max.unwrap_or(*count);
                let target = min_val.max(1).min(max_val).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(target);
                vec![Action::TakeCardsFromDeck { card_ids: ids }]
            }

            Prompt::ChooseCardsFromDiscard { options, count, min, max, .. } => {
                let min_val = min.unwrap_or(*count);
                let max_val = max.unwrap_or(*count);
                let target = min_val.max(1).min(max_val).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(target);
                vec![Action::TakeCardsFromDiscard { card_ids: ids }]
            }

            Prompt::ChoosePokemonInPlay { options, min, max, .. } => {
                let target = (*min).max(1).min(*max).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(target);
                vec![Action::ChoosePokemonTargets { target_ids: ids }]
            }

            Prompt::ReorderDeckTop { options, .. } => {
                let mut ids = options.clone();
                ids.shuffle(&mut *rng);
                vec![Action::ReorderDeckTop { card_ids: ids }]
            }

            Prompt::ChooseAttachedEnergy { count, min, pokemon_id, .. } => {
                // Need to get energy from the pokemon
                let target = min.unwrap_or(*count);
                let pokemon = view.my_active.as_ref()
                    .filter(|p| p.card.id == *pokemon_id)
                    .or_else(|| view.my_bench.iter().find(|p| p.card.id == *pokemon_id));

                if let Some(p) = pokemon {
                    let mut energy_ids: Vec<_> = p.attached_energy.iter().map(|e| e.id).collect();
                    energy_ids.shuffle(&mut *rng);
                    energy_ids.truncate(target);
                    vec![Action::ChooseAttachedEnergy { energy_ids }]
                } else {
                    vec![]
                }
            }

            Prompt::ChooseCardsFromHand { options, count, min, max, return_to_deck, .. } => {
                let min_val = min.unwrap_or(*count);
                let max_val = max.unwrap_or(*count);
                let target = min_val.max(1).min(max_val).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(target);
                if *return_to_deck {
                    vec![Action::ReturnCardsFromHandToDeck { card_ids: ids }]
                } else {
                    vec![Action::DiscardCardsFromHand { card_ids: ids }]
                }
            }

            Prompt::ChooseCardsInPlay { options, min, max, .. } => {
                let target = (*min).max(1).min(*max).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(target);
                vec![Action::ChooseCardsInPlay { card_ids: ids }]
            }

            Prompt::ChooseDefenderAttack { attacks, .. } => {
                if let Some(attack_name) = attacks.choose(&mut *rng) {
                    vec![Action::ChooseDefenderAttack { attack_name: attack_name.clone() }]
                } else {
                    vec![]
                }
            }

            Prompt::ChoosePokemonAttack { attacks, .. } => {
                if let Some(attack_name) = attacks.choose(&mut *rng) {
                    vec![Action::ChoosePokemonAttack { attack_name: attack_name.clone() }]
                } else {
                    vec![]
                }
            }

            Prompt::ChooseSpecialCondition { options, .. } => {
                if let Some(cond) = options.choose(&mut *rng) {
                    vec![Action::ChooseSpecialCondition { condition: *cond }]
                } else {
                    vec![]
                }
            }

            Prompt::ChoosePrizeCards { options, min, max, .. } => {
                let target = (*min).max(1).min(*max).min(options.len());
                let mut ids: Vec<_> = options.clone();
                ids.shuffle(&mut *rng);
                ids.truncate(target);
                vec![Action::ChoosePrizeCards { card_ids: ids }]
            }

            Prompt::ChooseNewActive { options, .. } => {
                if let Some(id) = options.choose(&mut *rng) {
                    vec![Action::ChooseNewActive { card_id: *id }]
                } else {
                    vec![]
                }
            }
        }
    }
}

impl AiController for ReactAi {
    fn propose_prompt_response(&mut self, view: &GameView, prompt: &Prompt) -> Vec<Action> {
        let summary = format!("Prompt: {:?}", prompt);

        // Try LLM first
        match self.query_llm(view) {
            Ok(parsed) => {
                self.log_action(
                    summary,
                    Some(format!("{:?}", parsed.action)),
                    Some(parsed.action.clone()),
                    None,
                );
                self.update_todos(parsed.todo_add);
                vec![parsed.action]
            }
            Err(e) => {
                // Fallback to random
                if self.config.fallback_to_random {
                    let actions = self.random_prompt_response(view, prompt);
                    self.log_action(
                        summary,
                        None,
                        actions.first().cloned(),
                        Some(format!("LLM failed: {}, using random", e)),
                    );
                    actions
                } else {
                    self.log_action(summary, None, None, Some(e));
                    vec![]
                }
            }
        }
    }

    fn propose_free_actions(&mut self, view: &GameView) -> Vec<Action> {
        let summary = format!("Phase: {:?}", view.phase);

        // Try LLM first
        match self.query_llm(view) {
            Ok(parsed) => {
                self.log_action(
                    summary,
                    Some(format!("{:?}", parsed.action)),
                    Some(parsed.action.clone()),
                    None,
                );
                self.update_todos(parsed.todo_add);
                vec![parsed.action]
            }
            Err(e) => {
                // Fallback to random
                if self.config.fallback_to_random {
                    if let Some(action) = self.random_fallback_action(view) {
                        self.log_action(
                            summary,
                            None,
                            Some(action.clone()),
                            Some(format!("LLM failed: {}, using random", e)),
                        );
                        vec![action]
                    } else {
                        // If no action available, end turn
                        if view.action_hints.can_end_turn {
                            vec![Action::EndTurn]
                        } else {
                            vec![]
                        }
                    }
                } else {
                    self.log_action(summary, None, None, Some(e));
                    vec![]
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_react_ai_creation() {
        let ai = ReactAi::new(42);
        assert!(!ai.get_todo_list().is_empty());
    }

    #[test]
    fn test_config_default() {
        let config = ReactAiConfig::default();
        assert!(config.temperature > 0.0);
        assert!(config.fallback_to_random);
    }
}