Implement basic cmdline UI framework

Issue #1
This commit is contained in:
2021-12-12 12:50:02 +01:00
parent 6d433a6d01
commit aa899740c6
2 changed files with 29 additions and 4 deletions

View File

@@ -33,7 +33,10 @@ def make_piece(piece_str):
def get_state():
engine.stdin.write(b"get_state\n")
engine.stdin.flush()
position_str = engine.stdout.readline().decode("ascii").strip()
reply = engine.stdout.readline().decode("ascii").strip()
status, position_str = reply.split(",")
if status != "ok":
flask.abort(400)
position = {
position_str[i + 2 : i + 4]: make_piece(position_str[i : i + 2])
for i in range(0, len(position_str), 4)

View File

@@ -66,15 +66,37 @@ impl Ui {
board,
}
}
fn get_state(&self, args: &[&str]) -> Result<String, String> {
if !args.is_empty() {
Err("get_state takes no args".to_owned())
} else {
let result = format!("{}", self.board);
Ok(result)
}
}
fn handle_command(&mut self, s: &str) -> Result<String, String> {
let mut cmd = s.split(',');
// There will be at least an empty string => otherwise panic
let cmd_type = cmd.next().unwrap();
let args: Vec<&str> = cmd.collect();
match cmd_type {
"get_state" => self.get_state(&args),
"" => Err("No command given".to_owned()),
_ => Err("Invalid command".to_owned()),
}
}
pub fn run(&mut self) -> Result<(), ()> {
let stdin = std::io::stdin();
let mut input_lines = stdin.lock().lines();
loop {
match input_lines.next() {
None => break Ok(()),
Some(line) => match &line.unwrap()[..] {
"get_state" => println!("{}", self.board),
_ => break Err(()),
Some(line) => match line {
Err(_) => break Err(()),
Ok(line) => match self.handle_command(&line) {
Ok(result) => println!("ok,{}", result),
Err(reason) => println!("err,{}", reason),
},
},
}
}