Added receive() and send_receive functions for Connection struct + added get_block() function for Minecraft struct

This commit is contained in:
blackfur 2021-02-10 16:53:36 +01:00
parent 4637b9e524
commit 4c82ec1950

View file

@ -1,16 +1,22 @@
use std::io::prelude::*; use std::io::prelude::*;
use std::net::TcpStream; use std::net::TcpStream;
use std::io::{Result as IoResult, Error}; use std::io::{Result as IoResult, Error, BufReader};
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::create; use crate::{create, Vec3};
#[test] #[test]
fn it_works() { fn it_works() {
assert_eq!(2 + 2, 4); assert_eq!(2 + 2, 4);
let mut mc = create("localhost:4711"); let mut mc = create("localhost:4711");
let position = Vec3 {
x: -2,
y: 8,
z: -2
};
mc.post_to_chat("Test"); mc.post_to_chat("Test");
println!(mc.get_block(position));
} }
} }
@ -22,7 +28,7 @@ struct Connection {
stream:TcpStream stream:TcpStream
} }
struct Vec3 { pub struct Vec3 {
x:i32, x:i32,
y:i32, y:i32,
z:i32 z:i32
@ -30,7 +36,19 @@ struct Vec3 {
impl Connection { impl Connection {
pub fn send(&mut self, msg:&str) { pub fn send(&mut self, msg:&str) {
self.stream.write(&format!("{}\n",msg).as_bytes()); self.stream.write(&format!("{}\n", msg).as_bytes());
}
pub fn receive(&mut self) -> &str {
let mut reader = BufReader::new(&self.stream);
let mut line = String::new();
reader.read_line(&mut line);
line.as_str()
}
pub fn send_receive(&mut self, msg:&str) -> &str {
self.send(msg);
self.receive()
} }
} }
@ -38,14 +56,18 @@ impl Minecraft {
pub fn post_to_chat(&mut self, msg:&str) { pub fn post_to_chat(&mut self, msg:&str) {
self.conn.send(&format!("chat.post({})", msg)); self.conn.send(&format!("chat.post({})", msg));
} }
pub fn get_block(&mut self, pos:Vec3) -> &str{
self.conn.send_receive(&format!("world.getBlock({},{},{})", pos.x, pos.y, pos.z))
}
} }
pub fn create(adress:&str) -> Minecraft { pub fn create(adress:&str) -> Minecraft {
let mut stream = TcpStream::connect(adress); let mut stream = TcpStream::connect(adress);
match stream { match stream {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(_) => {
panic!(e) panic!("Failed to connect to the API! Is Minecraft running?")
} }
} }
Minecraft { Minecraft {