rust井子棋游戏源代码
use std::io;
struct ChessBoard{
val: Vec<i8>,
last_drop: (usize, usize)
}
impl ChessBoard{
fn is_win(&mut self) -> bool{
let mut temp;
for i in 0..3{
temp = self.val[(i*3)] + self.val[(i*3)+1] + self.val[(i*3)+1];
if temp == -3 || temp == 3{
return true
}
}
for i in 0..3{
temp = self.val[i] + self.val[3+i] + self.val[6+i];
if temp == -3 || temp == 3{
return true
}
}
temp = self.val[0] + self.val[4] + self.val[8];
if temp == -3 || temp == 3{
return true
}
temp = self.val[2] + self.val[4] + self.val[6];
if temp == -3 || temp == 3{
return true
}
return false;
}
fn drop_black(&mut self, row:usize, col:usize){
self.val[(row-1)*3 + col - 1] = 1;
self.last_drop = (row - 1, col - 1);
}
fn drop_white(&mut self, row:usize, col:usize){
self.val[(row-1)*3 + col - 1] = -1;
self.last_drop = (row - 1, col - 1);
}
fn new() -> ChessBoard{
ChessBoard{
val: vec![0, 0, 0, 0, 0, 0, 0, 0, 0,],
last_drop: (0, 0)
}
}
fn print(&self){
let mut flag = 0;
for i in &self.val {
print!("{val:>width$}",val = i, width=6);
flag += 1;
if flag % 3 == 0 {
println!("");
}
}
}
}
fn main() {
let mut chess_board = ChessBoard::new();
let mut flag = true;
chess_board.print();
println!("现在开始井子棋游戏");
loop{
println!("请输入行与列");
let mut row = String::new();
let mut col = String::new();
io::stdin().read_line(&mut row).expect("错误");
io::stdin().read_line(&mut col).expect("错误");
let row = match row.trim().parse() {
Ok(val) => val,
Err(_) => continue,
};
let col = match col.trim().parse() {
Ok(col) => col,
Err(_) => continue,
};
if flag == true{
flag = false;
chess_board.drop_black(row, col);
} else {
flag = true;
chess_board.drop_white(row, col);
}
if chess_board.is_win(){
break;
}
chess_board.print();
}
if flag == false{
println!("黑方胜");
} else {
println!("白方胜");
}
}