### Start the NetworkArenaServer Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html Starts the server, binding it to the specified IP address and port. The server will run until explicitly stopped and processes games in batches. ```rust server.start(String::from("127.0.0.1"), 8080).unwrap(); ``` -------------------------------- ### Start the NetworkArenaServer Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html?search= Starts the server, binding to a specified IP address and port. The server runs until stopped, playing games in batches and disconnecting clients after each batch. ```rust pub fn start( &mut self, addr: String, port: u16, ) -> Result<(), NetworkArenaServerError> ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/lib.rs.html?search= Demonstrates a common search pattern using std::vec. ```rust std::vec ``` -------------------------------- ### New Board Initialization Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html?search= Creates a new Reversi board with the standard starting configuration. The initial state is displayed using a string representation where 'X' is Black and 'O' is White, with Black starting first. ```rust pub fn new() -> Board { Board::default() } ``` ```rust use rust_reversi_core::board::Board; let board = Board::new(); assert_eq!(board.to_string().unwrap(), format!( " |abcdefgh\n", "-+--------\n", "1|--------\n", "2|--------\n", "3|--------\n", "4|---OX---\n", "5|---XO---\n", "6|--------\n", "7|--------\n", "8|--------\n", ).as_str()); ``` -------------------------------- ### Example Search: u32 to bool Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/lib.rs.html?search= Illustrates a search pattern for converting u32 to bool. ```rust u32 -> bool ``` -------------------------------- ### Set up player pairs for game execution Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html?search= Creates and returns pairs of players, each configured for different starting turns (Black and White). This setup ensures that games can be played with either player starting as Black or White. It manages the lifecycle of the underlying processes, ensuring they are properly started and ready for interaction. ```rust fn get_players(&mut self) -> Result<(Vec, Vec), ArenaError> { // P1equalsBlack let ((process1, stdin1, stdout1), (process2, stdin2, stdout2)) = self.init_processes(Turn::Black)?; let player_1b = Player::new(stdin1, stdout1); let player_2w = Player::new(stdin2, stdout2); // P2equalsBlack let ((process3, stdin3, stdout3), (process4, stdin4, stdout4)) = self.init_processes(Turn::White)?; let player_2b = Player::new(stdin4, stdout4); let player_1w = Player::new(stdin3, stdout3); Ok(( vec![(process1, process2), (process3, process4)], vec![(player_1b, player_2w), (player_2b, player_1w)], )) } ``` -------------------------------- ### Board::new Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html Creates a new Reversi board instance with the default initial state. Black starts the game. ```APIDOC ## Board::new ### Description Creates a new Reversi board instance with the default initial state. Black starts the game. ### Returns * `Board` instance ### Note * The initial board state is as follows: ``` use rust_reversi_core::board::Board; let board = Board::new(); assert_eq!(board.to_string().unwrap(), format!( " |abcdefgh\n", "-+--------\n", "1|--------\n", "2|--------\n", "3|--------\n", "4|---OX---\n", "5|---XO---\n", "6|--------\n", "7|--------\n", "8|--------\n", ).as_str()); ``` * X: Black, O: White * Black goes first ### Method `pub fn new() -> Board` ``` -------------------------------- ### Get Player Processes and Objects Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html Sets up and retrieves pairs of game processes and player objects for both Black and White turns. Ensures proper cleanup if the second player's process fails to start. ```rust let ((process1, stdin1, stdout1), (process2, stdin2, stdout2)) = self.init_processes(Turn::Black)?; let player_1b = Player::new(stdin1, stdout1); let player_2w = Player::new(stdin2, stdout2); let ((process3, stdin3, stdout3), (process4, stdin4, stdout4)) = self.init_processes(Turn::White)?; let player_2b = Player::new(stdin4, stdout4); let player_1w = Player::new(stdin3, stdout3); Ok(( vec![(process1, process2), (process3, process4)], vec![(player_1b, player_2w), (player_2b, player_1w)], )) ``` -------------------------------- ### Start and Test Local Process Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html Starts a game engine process, pipes its stdin and stdout, and performs a ping-pong test to verify communication. Handles potential I/O errors during the process. ```rust let mut cmd = Command::new(&command[0]); for arg in command.iter().skip(1) { cmd.arg(arg); } match turn { Turn::Black => cmd.arg("BLACK"), Turn::White => cmd.arg("WHITE"), }; let mut process = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?; let mut stdin = process.stdin.take().unwrap(); let stdout = process.stdout.take().unwrap(); // ping-pong test writeln!(stdin, "ping") .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Write error"))?; stdin .flush() .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Flush error"))?; let mut reader = BufReader::new(stdout); let mut response = String::new(); reader .read_line(&mut response) .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Read error"))?; if response.trim() != "pong" { return Err(std::io::Error::new( std::io::ErrorKind::Other, "Invalid response", )); } Ok((process, stdin, reader)) ``` -------------------------------- ### Get Player Pairs for Games Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up and returns pairs of player processes and their associated communication channels for both possible starting turns (Black and White). Ensures proper cleanup if the second player fails to initialize. ```rust fn get_players(&mut self) -> Result<(Vec, Vec), ArenaError> { // P1equalsBlack let ((process1, stdin1, stdout1), (process2, stdin2, stdout2)) = self.init_processes(Turn::Black)?; let player_1b = Player::new(stdin1, stdout1); let player_2w = Player::new(stdin2, stdout2); // P2equalsBlack let ((process3, stdin3, stdout3), (process4, stdin4, stdout4)) = self.init_processes(Turn::White)?; let player_2b = Player::new(stdin4, stdout4); let player_1w = Player::new(stdin3, stdout3); Ok(( vec![(process1, process2), (process3, process4)], vec![(player_1b, player_2w), (player_2b, player_1w)], )) } ``` -------------------------------- ### Start Player Process Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts an external player process, pipes its stdin and stdout, and performs a ping-pong test to verify communication. This function is used internally by LocalArena to launch and validate player engines. ```rust fn start_process( command: &[String], turn: Turn, ) -> Result<(Child, ChildStdin, BufReader), std::io::Error> { let mut cmd = Command::new(&command[0]); for arg in command.iter().skip(1) { cmd.arg(arg); } match turn { Turn::Black => cmd.arg("BLACK"), Turn::White => cmd.arg("WHITE"), }; let mut process = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?; let mut stdin = process.stdin.take().unwrap(); let stdout = process.stdout.take().unwrap(); // ping-pong test writeln!(stdin, "ping") .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Write error"))?; stdin .flush() .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Flush error"))?; let mut reader = BufReader::new(stdout); let mut response = String::new(); reader .read_line(&mut response) .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Read error"))?; if response.trim() != "pong" { return Err(std::io::Error::new( std::io::ErrorKind::Other, "Invalid response", )); } Ok((process, stdin, reader)) } ``` -------------------------------- ### Start Game Process Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a new process for a game player (black or white). This function is used internally to manage the separate processes for each player's AI. ```rust let (process_b, mut stdin_b, mut reader_b) = NetworkArenaClient::start_process(&self.command, Turn::Black)?; let process_b = Arc::new(Mutex::new(process_b)); self.process_b = Some(process_b.clone()); let (process_w, mut stdin_w, mut reader_w) = NetworkArenaClient::start_process(&self.command, Turn::White)?; let process_w = Arc::new(Mutex::new(process_w)); self.process_w = Some(process_w.clone()); ``` -------------------------------- ### Get player process pairs Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html?search=std%3A%3Avec Initializes and returns pairs of player processes and their corresponding Player objects. It runs two sets of initializations to get players for both Black and White starting turns, ensuring that each player can be tested in both roles. This prepares all necessary components for a full game simulation. ```rust fn get_players(&mut self) -> Result<(Vec, Vec), ArenaError> { // P1equalsBlack let ((process1, stdin1, stdout1), (process2, stdin2, stdout2)) = self.init_processes(Turn::Black)?; let player_1b = Player::new(stdin1, stdout1); let player_2w = Player::new(stdin2, stdout2); // P2equalsBlack let ((process3, stdin3, stdout3), (process4, stdin4, stdout4)) = self.init_processes(Turn::White)?; let player_2b = Player::new(stdin4, stdout4); let player_1w = Player::new(stdin3, stdout3); Ok(( vec![(process1, process2), (process3, process4)], vec![(player_1b, player_2w), (player_2b, player_1w)], )) } ``` -------------------------------- ### NetworkArenaServer::start Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html Starts the network arena server, listening for incoming TCP connections and managing game sessions. ```APIDOC ## NetworkArenaServer::start ### Description Starts the network arena server, listening for incoming TCP connections and managing game sessions. The server runs until explicitly stopped. It plays games in batches and disconnects/clears clients after each batch. ### Arguments * `addr` (String) - The IP address to bind the server to. * `port` (u16) - The port number to bind the server to. ### Returns * `Result<(), NetworkArenaServerError>` - Ok if the server starts successfully, otherwise returns a `NetworkArenaServerError`. ``` -------------------------------- ### Create a new Board instance Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/board/struct.Board.html Initializes a new Board with the standard starting configuration for a Reversi game. The initial state is asserted to match a predefined string representation. ```rust use rust_reversi_core::board::Board; let board = Board::new(); assert_eq!(board.to_string().unwrap(), format!( " |abcdefgh\n", "-+--------\n", "1|--------\n", "2|--------\n", "3|--------\n", "4|---OX---\n", "5|---XO---\n", "6|--------\n", "7|--------\n", "8|--------\n", ).as_str()); ``` -------------------------------- ### Example Search: Option to Option Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/lib.rs.html?search= Shows a search pattern for mapping Option to Option using a function. ```rust Option, (T -> U) -> Option ``` -------------------------------- ### NetworkArenaServer::start Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the NetworkArenaServer, binding it to a specified IP address and port. The server will run until explicitly stopped. ```APIDOC ## NetworkArenaServer::start ### Description Starts the server, making it listen for connections on the specified address and port. ### Arguments * `addr` (String) - The IP address to bind the server to. * `port` (u16) - The port number to bind the server to. ### Returns * `Result<(), NetworkArenaServerError>` - Ok if the server started successfully, otherwise an error. ### Notes * The server operates in batches, playing `game_per_iter` games before disconnecting and clearing clients. * The server will continue running until stopped. ``` -------------------------------- ### NetworkArenaServer::start Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html?search= Starts the NetworkArenaServer, binding it to a specified IP address and port. The server will run until explicitly stopped. ```APIDOC ## NetworkArenaServer::start ### Description Starts the server. The server will keep running until it is stopped. It plays games in batches and disconnects/clears clients after each batch. ### Arguments * `addr` (String) - IP address to bind. * `port` (u16) - Port to bind. ### Returns * `Result<(), NetworkArenaServerError>` - Ok if the server started successfully, otherwise an error. ### Note * The server will keep running until it is stopped. * The server will play games in batches of `game_per_iter`. * The server will disconnect clients after each batch. * The server will clear clients after each batch. ``` -------------------------------- ### connect Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html Establishes a connection to the game server and initializes communication channels for both black and white turns. It handles starting the necessary processes and setting up read timeouts. ```APIDOC ## connect ### Description Connects to a specified server address and port, setting up communication streams for game turns. This method also starts the underlying processes for handling game logic. ### Method `connect` ### Arguments * `addr` - (String) The IP address of the server to connect to. * `port` - (u16) The port number of the server. ### Returns * `Result<(), NetworkArenaClientError>` - Returns `Ok(())` if the connection and setup are successful, otherwise returns a `NetworkArenaClientError`. ### Example ```rust let mut client = NetworkArenaClient::new("your_command"); match client.connect("127.0.0.1".to_string(), 8080) { Ok(_) => println!("Connected successfully!"), Err(e) => eprintln!("Connection failed: {:?}", e), } ``` ``` -------------------------------- ### Board Initialization with Default State Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html?search=std%3A%3Avec Creates a new Reversi board with the standard starting configuration. The initial state is displayed using a string representation for clarity. ```rust impl Default for Board { fn default() -> Self { Board { player_board: 0x00_00_00_08_10_00_00_00, opponent_board: 0x00_00_00_10_08_00_00_00, turn: Turn::Black, legal_moves_cache: None, } } } impl Board { /// Create a new Board instance /// # Returns /// * `Board` instance /// # Note /// * The initial board state is as follows: /// ``` /// use rust_reversi_core::board::Board; /// let board = Board::new(); /// assert_eq!(board.to_string().unwrap(), format!( /// "{}", /// " |abcdefgh\n", /// "-+--------\n", /// "1|--------\n", /// "2|--------\n", /// "3|--------\n", /// "4|---OX---\n", /// "5|---XO---\n", /// "6|--------\n", /// "7|--------\n", /// "8|--------\n", /// ).as_str()); /// ``` /// * X: Black, O: White /// * Black goes first pub fn new() -> Board { Board::default() } } ``` -------------------------------- ### NetworkArenaServer::start Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html Starts the network server, listening for incoming TCP connections. Manages client connections, plays games in batches, and disconnects/clears clients after each batch. ```rust pub fn start(&mut self, addr: String, port: u16) -> Result<(), NetworkArenaServerError> { let listener = TcpListener::bind(format!("{}:{}", addr, port))?; for stream in listener.incoming() { match stream { Ok(stream) => match self.client_manager.add_client(stream) { Ok(_) => { if self.client_manager.is_full() { self.play()?; self.client_manager.disconnect()?; self.client_manager.clear(); } } Err(e) => { return Err(NetworkArenaServerError::from(e)); } }, Err(e) => { return Err(NetworkArenaServerError::from(e)); } } } Ok(()) } ``` -------------------------------- ### NetworkArenaServer::start Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html?search=std%3A%3Avec Starts the NetworkArenaServer, binding it to a specified IP address and port. The server will continuously play games in batches until explicitly stopped. ```APIDOC ## NetworkArenaServer::start ### Description Starts the server, binding it to the specified IP address and port. The server will play games in batches and disconnect clients after each batch. ### Arguments * `addr` (String) - IP address to bind. * `port` (u16) - Port to bind. ### Returns * `Result<(), NetworkArenaServerError>` - Ok if the server started successfully, otherwise an error. ### Notes * The server will keep running until it is stopped. * The server will play games in batches of `game_per_iter`. * The server will disconnect clients after each batch. * The server will clear clients after each batch. ``` -------------------------------- ### Rust: New Board Instance Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Reversi board instance using the default initial configuration. This is the standard way to start a new game. ```rust /// Create a new Board instance /// # Returns /// * `Board` instance /// # Note /// * The initial board state is as follows: /// ``` /// use rust_reversi_core::board::Board; /// let board = Board::new(); /// assert_eq!(board.to_string().unwrap(), format!( /// "{}{}{}{}{}{}{}{}{}{}", /// " |abcdefgh\n", /// "-+--------\n", /// "1|--------\n", /// "2|--------\n", /// "3|--------\n", /// "4|---OX---\n", /// "5|---XO---\n", /// "6|--------\n", /// "7|--------\n", /// "8|--------\n", /// ).as_str()); /// ``` /// * X: Black, O: White /// * Black goes first pub fn new() -> Board { Board::default() } ``` -------------------------------- ### Create a new LocalArena instance Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.LocalArena.html?search=u32+-%3E+bool Initializes a new LocalArena for playing games. The commands specify the executables for each player, and `show_progress` controls whether a progress bar is displayed. Ensure player executables are correctly specified and handle 'ping'/'pong' for connection. ```rust use rust_reversi_core::arena::LocalArena; let command1 = vec!["./player1".to_string()]; let command2 = vec!["./player2".to_string()]; let show_progress = true; let arena = LocalArena::new(command1, command2, show_progress); ``` -------------------------------- ### NetworkArenaServer::start Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the network arena server, listening for incoming TCP connections. It manages clients, plays games in batches, and disconnects/clears clients after each batch. ```rust pub fn start(&mut self, addr: String, port: u16) -> Result<(), NetworkArenaServerError> { let listener = TcpListener::bind(format!(...))?; for stream in listener.incoming() { match stream { Ok(stream) => match self.client_manager.add_client(stream) { Ok(_) => { if self.client_manager.is_full() { self.play()?; self.client_manager.disconnect()?; self.client_manager.clear(); } } Err(e) => { return Err(NetworkArenaServerError::from(e)); } }, Err(e) => { return Err(NetworkArenaServerError::from(e)); } } } Ok(()) } ``` -------------------------------- ### connect Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search=std%3A%3Avec Establishes a connection to the game server and initializes the client processes for black and white turns. ```APIDOC ## connect ### Description Connects to the specified server IP address and port. It also starts separate processes for handling black and white turns, setting up communication channels for them. ### Method `connect` ### Arguments - `addr` (String) - The IP address of the server. - `port` (u16) - The port number of the server. ### Returns - `Result<(), NetworkArenaClientError>` - Returns `Ok(())` if the connection and initialization are successful, otherwise returns a `NetworkArenaClientError`. ### Internal Logic - Establishes a TCP connection to the server. - Sets a read timeout for the stream. - Starts two separate processes using `NetworkArenaClient::start_process` for black and white turns. - Enters a loop to read responses from the server and send appropriate commands to the respective processes. - Handles server commands like `isready`, `black`, `white`, and `stats`. ``` -------------------------------- ### Game::new Constructor Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/core.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new `Game` instance with a fresh board and the provided black and white players. The game starts in the 'Playing' state. ```rust fn new(black_player: &'a mut Player, white_player: &'a mut Player) -> Self { Game { board: Board::new(), black_player, white_player, moves: Vec::new(), board_log: Vec::new(), status: GameStatus::Playing, } } ``` -------------------------------- ### NetworkArenaClient::new Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaClient.html?search=u32+-%3E+bool Creates a new instance of NetworkArenaClient. This method initializes the client with a given command. ```APIDOC ## NetworkArenaClient::new ### Description Creates a new instance of NetworkArenaClient with the specified command. ### Method `new(command: Vec) -> Self` ### Arguments * `command` (Vec) - The command to run the client. ### Returns * `Self` - A new NetworkArenaClient instance. ``` -------------------------------- ### Implement Search Trait for ThunderSearch Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/search/thunder.rs.html?search=u32+-%3E+bool Provides the implementation for the `Search` trait for the `ThunderSearch` struct. This includes methods for getting the best move, getting the best move with a timeout, and getting the search score. ```rust impl Search for ThunderSearch { /// Get the best move for the given board. /// # Arguments /// * `board` - The board to search. /// # Returns /// The best move. /// `Some(usize)` - The best move. /// `None` - player must pass. fn get_move(&self, board: &mut Board) -> Option { let mut root = ThunderNode::new(board.clone(), self.epsilon, self.evaluator.clone()); root.expand(); for _ in 0..self.n_playouts { root.evaluate(); } let mut best_child_index = 0; let mut best_n_visits = 0; for (i, child) in root.children.as_ref().unwrap().iter().enumerate() { if child.n_visits > best_n_visits { best_n_visits = child.n_visits; best_child_index = i; } } let legal_moves = board.get_legal_moves_vec(); Some(legal_moves[best_child_index]) } /// Get the best move for the given board with a timeout. /// # Arguments /// * `board` - The board to search. /// * `timeout` - The timeout duration. /// # Returns /// The best move. /// `Some(usize)` - The best move. /// `None` - player must pass. /// # Note /// The search will be stopped when the timeout is reached or the number of playouts is reached. /// If you want to stop the search when the timeout is reached, set the timeout to a bigger value. fn get_move_with_timeout(&self, board: &mut Board, timeout: Duration) -> Option { let mut root = ThunderNode::new(board.clone(), self.epsilon, self.evaluator.clone()); root.expand(); let search_duration = timeout.as_secs_f64() - self.margin_time; let time_keeper = TimeKeeper::new(Duration::from_secs_f64(search_duration)); for i in 0..self.n_playouts { root.evaluate(); if i % self.check_interval == 0 && time_keeper.is_timeout() { break; } } let mut best_child_index = 0; let mut best_n_visits = 0; for (i, child) in root.children.as_ref().unwrap().iter().enumerate() { if child.n_visits > best_n_visits { best_n_visits = child.n_visits; best_child_index = i; } } let legal_moves = board.get_legal_moves_vec(); Some(legal_moves[best_child_index]) } /// Get the search score for the given board. /// # Arguments /// * `board` - The board to search. /// # Returns /// The search score. /// # Note /// The search score is the winrate of the best move. /// The search will be stopped when the number of playouts is reached. fn get_search_score(&self, board: &mut Board) -> f64 { if board.is_game_over() { return match (board.is_win(), board.is_lose()) { (Ok(true), _) => 1.0, (_, Ok(true)) => 0.0, _ => 0.5, }; } let mut root = ThunderNode::new(board.clone(), self.epsilon, self.evaluator.clone()); root.expand(); for _ in 0..self.n_playouts { root.evaluate(); } root.w / root.n_visits as f64 } } ``` -------------------------------- ### Get Opposite Turn Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/board/enum.Turn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to get the opposite turn using the `opposite` method. This is useful for switching turns in a game. ```rust use rust_reversi_core::board::Turn; let turn = Turn::Black; assert_eq!(turn.opposite(), Turn::White); ``` -------------------------------- ### NetworkArenaClient::new Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaClient.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance of NetworkArenaClient. This function initializes the client with a given command to run. ```APIDOC ## NetworkArenaClient::new ### Description Creates a new NetworkArenaClient instance. ### Arguments * `command` - (Vec) - Command to run the client. ### Returns * `NetworkArenaClient` - The newly created NetworkArenaClient instance. ``` -------------------------------- ### NetworkArenaClient::new Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaClient.html Creates a new instance of NetworkArenaClient. This method initializes the client with a command to run. ```APIDOC ## NetworkArenaClient::new ### Description Create a new NetworkArenaClient with the specified command. ### Arguments * `command` (Vec) - Command to run the client. ### Returns * `NetworkArenaClient` - The newly created NetworkArenaClient instance. ``` -------------------------------- ### NetworkArenaClient::new Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaClient.html?search= Creates a new instance of NetworkArenaClient. This method initializes the client with a command to run. ```APIDOC ## NetworkArenaClient::new ### Description Creates a new instance of NetworkArenaClient, initializing it with a command. ### Method `new` ### Parameters #### Arguments * `command` (Vec) - Required - Command to run the client ### Returns * `NetworkArenaClient` - The new NetworkArenaClient instance. ``` -------------------------------- ### Search Trait Definition Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/search/mod.rs.html Defines the core functionality for any search algorithm, including getting a move, getting a move with a timeout, and retrieving the search score. Implementations require the `Debug` trait. ```rust pub trait Search: Debug { fn get_move(&self, board: &mut Board) -> Option; fn get_move_with_timeout( &self, board: &mut Board, timeout: std::time::Duration, ) -> Option; fn get_search_score(&self, board: &mut Board) -> f64; } ``` -------------------------------- ### Create a new NetworkArenaServer Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html?search=std%3A%3Avec Instantiates a new NetworkArenaServer. Ensure `game_per_iter` is an even number. ```rust use rust_reversi_core::arena::NetworkArenaServer; let mut server = NetworkArenaServer::new(100, true).unwrap(); ``` -------------------------------- ### Search Trait Definition Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/search/trait.Search.html?search= Defines the core interface for search algorithms in the Reversi game. Implementors must provide methods for getting a move, getting a move with a timeout, and calculating a search score. ```rust pub trait Search: Debug { // Required methods fn get_move(&self, board: &mut Board) -> Option; fn get_move_with_timeout( &self, board: &mut Board, timeout: Duration, ) -> Option; fn get_search_score(&self, board: &mut Board) -> f64; } ``` -------------------------------- ### NetworkArenaClient::start_process Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts an external process for a Reversi client, configuring its arguments based on the player's turn (Black or White). It performs a ping-pong test to ensure communication is established. ```rust fn start_process( command: &[String], turn: Turn, ) -> Result<(Child, ChildStdin, BufReader), std::io::Error> { let mut cmd = Command::new(&command[0]); for arg in command.iter().skip(1) { cmd.arg(arg); } match turn { Turn::Black => cmd.arg("BLACK"), Turn::White => cmd.arg("WHITE"), }; let mut process = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?; let mut stdin = process.stdin.take().unwrap(); let stdout = process.stdout.take().unwrap(); // ping-pong test writeln!(stdin, "ping") .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Write error"))?; stdin .flush() .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Flush error"))?; let mut reader = BufReader::new(stdout); let mut response = String::new(); reader .read_line(&mut response) .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Read error"))?; if response.trim() != "pong" { // ... (error handling for non-pong response) ... } // ... (return value) ... } ``` -------------------------------- ### Get the current board state as a string Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/board/struct.Board.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the current board configuration as a string, following the format expected by `set_board_str`. This is useful for displaying or saving the board state. ```rust let board_string = board.get_board_line().unwrap(); ``` -------------------------------- ### Get Number of Playouts Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/search/thunder.rs.html Retrieves the configured number of playouts for the ThunderSearch. ```rust pub fn get_n_playouts(&self) -> usize { self.n_playouts } ``` -------------------------------- ### NetworkArenaClient::new Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html Constructs a new NetworkArenaClient with a given command to run the client process. ```rust pub fn new(command: Vec) -> Self { NetworkArenaClient { command, stats: (0, 0, 0), pieces: (0, 0), process_b: None, process_w: None, } } ``` -------------------------------- ### get_margin_time Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/search/alpha_beta.rs.html?search=std%3A%3Avec Gets the current margin time set for the search algorithm. ```APIDOC ## get_margin_time ### Description Gets the current margin time set for the search algorithm. ### Method `&self` (This is a method on a struct, not an HTTP method) ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A (This is an SDK method) ### Response #### Success Response - `f64`: The current margin time for the search. #### Response Example ```json { "example": 0.005 } ``` ``` -------------------------------- ### Total Piece Count Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html Get the sum of all stones (player and opponent) on the board. ```APIDOC ## piece_sum ### Description Get the sum of all stones on the board. ### Method `piece_sum(&self) -> i32` ### Returns - `i32`: The total number of stones. ``` -------------------------------- ### Get Search Margin Time Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/search/alpha_beta.rs.html?search=u32+-%3E+bool Retrieves the currently set margin time for the search. ```rust pub fn get_margin_time(&self) -> f64 { self.margin_time } ``` -------------------------------- ### NetworkArenaServer::new Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaServer.html?search=std%3A%3Avec Creates a new instance of NetworkArenaServer. This function initializes the server with specified parameters for game iterations and progress display. ```APIDOC ## NetworkArenaServer::new ### Description Creates a new NetworkArenaServer. ### Arguments * `game_per_iter` (usize) - Number of games to play in each iteration. Must be an even number. * `show_progress` (bool) - Show progress of the games. ### Returns * `Result` - The new NetworkArenaServer instance or an error. ### Example ```rust use rust_reversi_core::arena::NetworkArenaServer; let mut server = NetworkArenaServer::new(100, true).unwrap(); ``` ``` -------------------------------- ### Get Exploration Parameter Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/search/struct.ThunderSearch.html Retrieves the current exploration parameter (epsilon) for the search algorithm. ```rust pub fn get_epsilon(&self) -> f64 ``` -------------------------------- ### connect Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search= Establishes a connection to the game server and initializes the client processes for black and white turns. It handles initial server handshake and prepares for game data exchange. ```APIDOC ## connect ### Description Establishes a connection to the game server and initializes the client processes for black and white turns. It handles initial server handshake and prepares for game data exchange. ### Method `connect` ### Arguments - `addr` (String) - The IP address of the server. - `port` (u16) - The port number of the server. ### Returns - `Result<(), NetworkArenaClientError>` - Ok if the connection and initialization are successful, otherwise an error. ### Example ```rust // Assuming `client` is an instance of NetworkArenaClient // let result = client.connect("127.0.0.1".to_string(), 1337); ``` ``` -------------------------------- ### AlphaBetaSearch Get Win Score Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/search/struct.AlphaBetaSearch.html?search= Retrieves the win score configured for the AlphaBetaSearch instance. ```rust pub fn get_win_score(&self) -> i32 ``` -------------------------------- ### Check Client Readiness Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html Verifies if both connected clients are ready to start a game. It sends a 'isready' command to each client and expects a 'readyok' response. Returns an error if a client does not exist or if communication fails. ```rust fn is_ready(&mut self) -> Result { for stream in self.clients.iter_mut() { match stream.as_mut() { Some(stream) => { stream.write_all(SUPER_COMMAND_MARKER.as_bytes())?; stream.write_all(b" isready\n")?; stream.flush()?; let mut buffer = [0; BUF_SIZE]; let mut response = String::new(); match stream.read(&mut buffer) { Ok(n) => { response.push_str(&String::from_utf8_lossy(&buffer[..n])); } Err(e) => return Err(ClientManagerError::from(e)), } if response.trim() != "readyok" { return Ok(false); } } None => return Err(ClientManagerError::ClientNotExists), } } Ok(true) } ``` -------------------------------- ### Get Exploration Parameter (Epsilon) Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/search/thunder.rs.html?search=u32+-%3E+bool Retrieves the current exploration parameter (epsilon) for the Thunder Search. ```rust pub fn get_epsilon(&self) -> f64 { ``` -------------------------------- ### Get Current Turn in Rust Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html Returns the current player's turn (Black or White). ```Rust impl Board { /// Get the current turn /// # Returns /// * Turn of the player pub fn get_turn(&self) -> Turn { self.turn } } ``` -------------------------------- ### ThunderSearch Getters and Setters Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/search/struct.ThunderSearch.html?search=std%3A%3Avec Provides methods to get and set various parameters of the ThunderSearch instance. ```APIDOC ## ThunderSearch Getters and Setters ### Description These methods allow retrieval and modification of the internal state of a `ThunderSearch` instance, including playout count, exploration parameter, margin time, and check interval. ### Methods * `get_n_playouts(&self) -> usize` * `set_n_playouts(&mut self, n_playouts: usize)` * `get_epsilon(&self) -> f64` * `set_epsilon(&mut self, epsilon: f64)` * `get_margin_time(&self) -> f64` * `set_margin_time(&mut self, margin_time: f64)` * `get_check_interval(&self) -> usize` * `set_check_interval(&mut self, check_interval: usize)` ### Usage Use the getter methods to inspect current settings and setter methods to adjust them before initiating a search. ``` -------------------------------- ### MctsSearch Getters and Setters Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/search/struct.MctsSearch.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods to get and set the configuration parameters of the MctsSearch instance. ```APIDOC ## MctsSearch Configuration ### Getters - `get_n_playouts(&self) -> usize`: Get the number of playouts to run. - `get_c(&self) -> f64`: Get the exploration parameter. - `get_expansion_threshold(&self) -> usize`: Get the number of visits to expand the node. - `get_margin_time(&self) -> f64`: Get the margin time. - `get_check_interval(&self) -> usize`: Get the check interval. ### Setters - `set_n_playouts(&mut self, n_playouts: usize)`: Set the number of playouts to run. - `set_c(&mut self, c: f64)`: Set the exploration parameter. - `set_expansion_threshold(&mut self, expansion_threshold: usize)`: Set the number of visits to expand the node. - `set_margin_time(&mut self, margin_time: f64)`: Set the margin time. - `set_check_interval(&mut self, check_interval: usize)`: Set the check interval. ``` -------------------------------- ### ClientManager is_ready Method Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search=u32+-%3E+bool Checks if both clients connected to the `ClientManager` are ready. It sends a 'isready' command to each client and expects a 'readyok' response. Returns an error if a client does not exist or if a read operation fails. ```rust fn is_ready(&mut self) -> Result { for stream in self.clients.iter_mut() { match stream.as_mut() { Some(stream) => { stream.write_all(SUPER_COMMAND_MARKER.as_bytes())?; stream.write_all(b" isready\n")?; stream.flush()?; let mut buffer = [0; BUF_SIZE]; let mut response = String::new(); match stream.read(&mut buffer) { Ok(n) => { response.push_str(&String::from_utf8_lossy(&buffer[..n])); } Err(e) => return Err(ClientManagerError::from(e)), } if response.trim() != "readyok" { return Ok(false); } } None => return Err(ClientManagerError::ClientNotExists), } } Ok(true) } ``` -------------------------------- ### AlphaBetaSearch Get Max Depth Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/search/struct.AlphaBetaSearch.html?search= Retrieves the maximum search depth configured for the AlphaBetaSearch instance. ```rust pub fn get_max_depth(&self) -> usize ``` -------------------------------- ### NetworkArenaClient::new Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/arena/struct.NetworkArenaClient.html?search= Creates a new instance of NetworkArenaClient. This method initializes the client with a command to run the server process. ```rust pub fn new(command: Vec) -> Self ``` -------------------------------- ### Move Generation and Board Representation Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html?search=std%3A%3Avec Provides methods for getting legal moves and a string representation of the board. ```APIDOC ## get_random_move ### Description Gets a random legal move for the current player. ### Note If there are no legal moves available, returns `Err(BoardError::NoLegalMove)`. ### Returns `Result` - The index of a random legal move. ## to_string ### Description Converts the current board state into a string representation. ### Note 'X' represents Black, 'O' represents White, and '.' represents an empty square. This method is used for implementing the `fmt::Display` trait. ### Returns `Result` - A string representing the board. ``` -------------------------------- ### Get Player Piece Count Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/board.rs.html?search=std%3A%3Avec Returns the total number of stones belonging to the current player on the board. ```APIDOC ## player_piece_num ### Description Get the number of player's stones. ### Method GET ### Endpoint `/board/player_pieces` ### Returns * `i32`: The count of the player's stones. ``` -------------------------------- ### Create a new LocalArena instance Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/local.rs.html?search=std%3A%3Avec Instantiates a LocalArena to manage two external player processes. Use this to set up a game environment where players are separate executables. The commands provided should point to the player executables and any necessary arguments. ```rust use rust_reversi_core::arena::LocalArena; let command1 = vec!["./player1".to_string()]; let command2 = vec!["./player2".to_string()]; let show_progress = true; let arena = LocalArena::new(command1, command2, show_progress); ``` -------------------------------- ### StackVec64::iter() - Get an iterator Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/utils/struct.StackVec64.html?search=u32+-%3E+bool Returns an iterator over the elements of the StackVec64. The iterator yields references to the elements. ```rust pub fn iter(&self) -> Iter<'_, T> ``` -------------------------------- ### StackVec64 Initialization and Basic Operations Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/utils/stack_vec.rs.html Demonstrates how to create a new StackVec64, push elements into it, and check its length and emptiness. Assumes T implements Copy and Default traits. ```rust use std::ops::{Index, IndexMut}; #[derive(Clone, Debug)] pub struct StackVec64 { data: [T; 64], len: usize, } impl StackVec64 { #[inline] pub fn new() -> Self { Self { data: [T::default(); 64], len: 0, } } #[inline] pub fn push(&mut self, value: T) { debug_assert!(self.len < 64, "StackVec64 is full"); self.data[self.len] = value; self.len += 1; } #[inline] pub fn len(&self) -> usize { self.len } #[inline] pub fn is_empty(&self) -> bool { self.len == 0 } #[inline] pub fn clear(&mut self) { self.len = 0; } } ``` -------------------------------- ### connect Source: https://docs.rs/rust_reversi_core/1.0.2/src/rust_reversi_core/arena/network.rs.html?search=u32+-%3E+bool Establishes a connection to the game server and initializes the client processes for black and white turns. It continuously reads from the stream and processes server commands. ```APIDOC ## connect ### Description Connects to the specified server address and port, then starts separate processes for handling black and white turns. The client then enters a loop to read server messages, process commands like 'isready', 'black', 'white', and 'stats', and send appropriate responses. ### Method `pub fn connect(&mut self, addr: String, port: u16) -> Result<(), NetworkArenaClientError>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (Ok) Returns `Ok(())` if the connection and initial setup are successful. #### Error Response Returns `Err(NetworkArenaClientError)` if any of the following occur: - Connection to the server fails. - Read timeout is exceeded. - The connection is broken. - The server sends an unexpected response. ### Example ```rust // Assuming network_client is an instance of NetworkArenaClient // let result = network_client.connect("127.0.0.1".to_string(), 8080); // match result { // Ok(_) => println!("Connected successfully!"), // Err(e) => println!("Connection error: {:?}", e), // } ``` ``` -------------------------------- ### StackVec64::len() - Get the number of elements Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/utils/struct.StackVec64.html?search=u32+-%3E+bool Returns the number of elements currently in the StackVec64. This is an immutable operation. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### get_random_move Source: https://docs.rs/rust_reversi_core/1.0.2/rust_reversi_core/board/struct.Board.html Gets a random legal move for the current player. Returns an error if no legal moves are available. ```APIDOC ## pub fn get_random_move(&mut self) -> Result ### Description Get random move. ### Returns * `Result` ### Notes * If there is no legal move, return Err(BoardError::NoLegalMove) ```