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

master
blackfur 2021-02-10 16:53:36 +01:00
parent 8a99ef5c49
commit e99e200021
1 changed files with 28 additions and 6 deletions

View File

@ -1,16 +1,22 @@
use std::io::prelude::*;
use std::net::TcpStream;
use std::io::{Result as IoResult, Error};
use std::io::{Result as IoResult, Error, BufReader};
#[cfg(test)]
mod tests {
use crate::create;
use crate::{create, Vec3};
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
let mut mc = create("localhost:4711");
let position = Vec3 {
x: -2,
y: 8,
z: -2
};
mc.post_to_chat("Test");
println!(mc.get_block(position));
}
}
@ -22,7 +28,7 @@ struct Connection {
stream:TcpStream
}
struct Vec3 {
pub struct Vec3 {
x:i32,
y:i32,
z:i32
@ -30,7 +36,19 @@ struct Vec3 {
impl Connection {
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) {
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 {
let mut stream = TcpStream::connect(adress);
match stream {
Ok(_) => {}
Err(e) => {
panic!(e)
Err(_) => {
panic!("Failed to connect to the API! Is Minecraft running?")
}
}
Minecraft {