use std::io; const PLAYER_X: &str = "X"; const PLAYER_Y: &str = "Y"; const EMPTY: &str = " # "; fn main() { let mut board: Vec<[&str; 3]> = vec![ [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], ]; let mut turned_of = PLAYER_X; println!("Welcome {} and {} to tick tak game.", PLAYER_X, PLAYER_Y); println!("While playing add first value with row index and second value with colum value."); print_board(&mut board); // ****************play game********************* loop { println!( "------------------------------- Player {} turn --------------------------------------", turned_of ); let mut player_played_values = String::new(); io::stdin() .read_line(&mut player_played_values) .ok() .expect("read error"); let player_played_row_colum: Vec = player_played_values .split_whitespace() .map(|s| s.parse().expect("Enter valid input.")) .collect(); let row = player_played_row_colum[0] - 1; let colum = player_played_row_colum[1] - 1; if board[row][colum] == EMPTY { if turned_of == "X" { board[row][colum] = " X "; turned_of = PLAYER_Y; } else { board[row][colum] = " O "; turned_of = PLAYER_X; }; print_board(&mut board); let game_end = find_winner(&mut board); // println!("game_end {}", game_end); if game_end { break; } } else { println!("This is already selected."); } } // ************************************* } fn print_board(board: &mut Vec<[&str; 3]>) { println!("_________________"); for board_index in board { print!("|"); for board_inner_index in board_index { print!("{}", board_inner_index); } println!("|"); } println!("-----------------"); } fn find_winner(board: &mut Vec<[&str; 3]>) -> bool { let mut game_end = false; let matched_data = vec![ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for matched_data_index in matched_data { // println!("loop index={}", index); // println!( // "before row loop value={},{},{}", // matched_data_index[0], matched_data_index[1], matched_data_index[2] // ); let row1 = matched_data_index[0] / 3; let row2 = matched_data_index[1] / 3; let row3 = matched_data_index[2] / 3; let colum1 = find_colum(matched_data_index[0]); let colum2 = find_colum(matched_data_index[1]); let colum3 = find_colum(matched_data_index[2]); // println!( // "row={},colum1={},row={},colum2={},row={},colum3={}", // row1, colum1, row2, colum2, row3, colum3 // ); // println!( // "data {} ,{} ,{}", // board[row][colum1], board[row][colum2], board[row][colum3] // ); if board[row1][colum1] == board[row2][colum2] && board[row2][colum2] == board[row3][colum3] && board[row3][colum3] != EMPTY { println!("Winner is {}", board[row1][colum1]); game_end = true; } } return game_end; } fn find_colum(index: usize) -> usize { let colum_list = vec![0, 1, 2, 0, 1, 2, 0, 1, 2]; // println!("find value = {}",index); let board_colum = colum_list[index]; return board_colum; }