|
| 1 | +use gomori::{Board, Card, CardsSet, Color, Field, PlayTurnResponse}; |
| 2 | +use gomori_bot_utils::Bot; |
| 3 | +use pyo3::{pyfunction, types::PyDict, Py, PyObject, Python}; |
| 4 | + |
| 5 | +struct PythonBot { |
| 6 | + bot: PyObject, |
| 7 | +} |
| 8 | + |
| 9 | +// TODO: Re-evaluate this whole design |
| 10 | +impl gomori_bot_utils::Bot for PythonBot { |
| 11 | + fn new_game(&mut self, color: Color) { |
| 12 | + Python::with_gil(|py| { |
| 13 | + let kwargs = PyDict::new(py); |
| 14 | + kwargs |
| 15 | + .set_item("color", Py::new(py, color).unwrap()) |
| 16 | + .unwrap(); |
| 17 | + self.bot |
| 18 | + .call_method(py, "new_game", (), Some(kwargs)) |
| 19 | + .expect("Call to new_game() failed"); |
| 20 | + }) |
| 21 | + } |
| 22 | + |
| 23 | + fn play_first_turn(&mut self, cards: [Card; 5]) -> Card { |
| 24 | + Python::with_gil(|py| { |
| 25 | + let kwargs = PyDict::new(py); |
| 26 | + kwargs |
| 27 | + .set_item("cards", cards.map(|card| Py::new(py, card).unwrap())) |
| 28 | + .unwrap(); |
| 29 | + self.bot |
| 30 | + .call_method(py, "play_first_turn", (), Some(kwargs)) |
| 31 | + .expect("Call to play_first_turn() failed") |
| 32 | + .extract(py) |
| 33 | + .expect("play_first_turn() returned wrong type") |
| 34 | + }) |
| 35 | + } |
| 36 | + |
| 37 | + fn play_turn( |
| 38 | + &mut self, |
| 39 | + cards: [Card; 5], |
| 40 | + fields: Vec<Field>, |
| 41 | + cards_won_by_opponent: CardsSet, |
| 42 | + ) -> PlayTurnResponse { |
| 43 | + Python::with_gil(|py| { |
| 44 | + let kwargs = PyDict::new(py); |
| 45 | + kwargs |
| 46 | + .set_item("cards", cards.map(|card| Py::new(py, card).unwrap())) |
| 47 | + .unwrap(); |
| 48 | + kwargs |
| 49 | + .set_item("board", Py::new(py, Board::new(&fields)).unwrap()) |
| 50 | + .unwrap(); |
| 51 | + kwargs |
| 52 | + .set_item( |
| 53 | + "cards_won_by_opponent", |
| 54 | + Py::new(py, cards_won_by_opponent).unwrap(), |
| 55 | + ) |
| 56 | + .unwrap(); |
| 57 | + self.bot |
| 58 | + .call_method(py, "play_turn", (), Some(kwargs)) |
| 59 | + .expect("Call to play_turn() failed") |
| 60 | + .extract(py) |
| 61 | + .expect("play_turn() returned wrong type") |
| 62 | + }) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +#[pyfunction] |
| 67 | +pub fn run_bot(bot: PyObject) { |
| 68 | + PythonBot { bot }.run().unwrap() |
| 69 | +} |
0 commit comments