From 497339ab30961f52c2a6430cce61289c86a6c94e Mon Sep 17 00:00:00 2001 From: serxoz Date: Mon, 12 Sep 2022 20:47:35 +0200 Subject: [PATCH] lugares e obxetos na base de datos --- locations/0.json | 11 --- locations/1.json | 10 --- locations/2.json | 10 --- migrations/.keep | 0 .../down.sql | 1 + .../2022-09-12-114033_create_locations/up.sql | 12 +++ .../down.sql | 1 + .../up.sql | 6 ++ .../2022-09-12-174911_create_objects/down.sql | 1 + .../2022-09-12-174911_create_objects/up.sql | 7 ++ .../down.sql | 1 + .../2022-09-12-175351_populate_object/up.sql | 5 ++ objects/o0.json | 5 -- src/main.rs | 3 + src/objects.rs | 49 ++++++----- src/rlocation.rs | 83 +++++++------------ 16 files changed, 96 insertions(+), 109 deletions(-) delete mode 100644 locations/0.json delete mode 100644 locations/1.json delete mode 100644 locations/2.json create mode 100644 migrations/.keep create mode 100644 migrations/2022-09-12-114033_create_locations/down.sql create mode 100644 migrations/2022-09-12-114033_create_locations/up.sql create mode 100644 migrations/2022-09-12-114839_populate_locations/down.sql create mode 100644 migrations/2022-09-12-114839_populate_locations/up.sql create mode 100644 migrations/2022-09-12-174911_create_objects/down.sql create mode 100644 migrations/2022-09-12-174911_create_objects/up.sql create mode 100644 migrations/2022-09-12-175351_populate_object/down.sql create mode 100644 migrations/2022-09-12-175351_populate_object/up.sql delete mode 100644 objects/o0.json diff --git a/locations/0.json b/locations/0.json deleted file mode 100644 index 4c25c80..0000000 --- a/locations/0.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "tag": "0", - "descripcion": "Estás en un pasillo muy oscuro.\nEscuchas un sonido de alarma en la lejanía.\nApenas puedes ver una luz pulsante al norte.\nEn el suelo encuntras una palanca.\n\n---\nSalidas: norte", - "salidas": { - "norte": "1", - "este": "", - "sur": "", - "oeste": "" - }, - "objetos": ["o0"] -} diff --git a/locations/1.json b/locations/1.json deleted file mode 100644 index b73fb1f..0000000 --- a/locations/1.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "tag": "1", - "descripcion": "La única iluminación de esta sala es una pequeña luz pulsante en un panel. Parece el puente de mando. Un humo denso llena la sala irritando tus pulmones. Entre el humo ves una puerta al este tras la cual parece que suena una alarma.\n\n---\nSalidas: este, sur", - "salidas": { - "norte": "", - "este": "2", - "sur": "0", - "oeste": "" - } -} diff --git a/locations/2.json b/locations/2.json deleted file mode 100644 index 1caf2ed..0000000 --- a/locations/2.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "tag": "2", - "descripcion": "De aquí surje el fuerte sonido de alarma que taladra tus tímpanos. Alrededor de la sala ves las vainas criogénicas en las que has estado durmiendo durante el viaje. Todas están vacías!\n\n---\nSalidas: oeste", - "salidas": { - "norte": "", - "este": "", - "sur": "", - "oeste": "1" - } -} diff --git a/migrations/.keep b/migrations/.keep new file mode 100644 index 0000000..e69de29 diff --git a/migrations/2022-09-12-114033_create_locations/down.sql b/migrations/2022-09-12-114033_create_locations/down.sql new file mode 100644 index 0000000..75573d8 --- /dev/null +++ b/migrations/2022-09-12-114033_create_locations/down.sql @@ -0,0 +1 @@ +DROP TABLE location diff --git a/migrations/2022-09-12-114033_create_locations/up.sql b/migrations/2022-09-12-114033_create_locations/up.sql new file mode 100644 index 0000000..bebeb04 --- /dev/null +++ b/migrations/2022-09-12-114033_create_locations/up.sql @@ -0,0 +1,12 @@ +CREATE TABLE location ( + tag varchar(100) NOT NULL, + nombre varchar(100), + descripcion varchar(2048) NOT NULL, + salida_norte varchar(100), + salida_sur varchar(100), + salida_este varchar(100), + salida_oeste varchar(100), + salida_arriba varchar(100), + salida_abajo varchar(100), + CONSTRAINT PK_Location PRIMARY KEY (tag) +) diff --git a/migrations/2022-09-12-114839_populate_locations/down.sql b/migrations/2022-09-12-114839_populate_locations/down.sql new file mode 100644 index 0000000..f7ac82a --- /dev/null +++ b/migrations/2022-09-12-114839_populate_locations/down.sql @@ -0,0 +1 @@ +TRUNCATE TABLE location; diff --git a/migrations/2022-09-12-114839_populate_locations/up.sql b/migrations/2022-09-12-114839_populate_locations/up.sql new file mode 100644 index 0000000..9c75f13 --- /dev/null +++ b/migrations/2022-09-12-114839_populate_locations/up.sql @@ -0,0 +1,6 @@ +INSERT INTO location +(tag, nombre, descripcion, salida_norte, salida_sur, salida_este, salida_oeste, salida_arriba, salida_abajo) +VALUES +('0', 'Pasillo', 'Estás en un pasillo muy oscuro.\nEscuchas un sonido de alarma en la lejanía.\nApenas puedes ver una luz pulsante al norte.\nEn el suelo encuntras una palanca.\n\n---\nSalidas: norte', "1", NULL, NULL, NULL, NULL, NULL), +('1', 'Puente', 'La única iluminación de esta sala es una pequeña luz pulsante en un panel. Parece el puente de mando. Un humo denso llena la sala irritando tus pulmones. Entre el humo ves una puerta al este tras la cual parece que suena una alarma.\n\n---\nSalidas: este, sur', NULL, "0", "2", NULL, NULL, NULL), +('2', 'Vainas', 'De aquí surje el fuerte sonido de alarma que taladra tus tímpanos. Alrededor de la sala ves las vainas criogénicas en las que has estado durmiendo durante el viaje. Todas están vacías!\n\n---\nSalidas: oeste', NULL, NULL, NULL, "1", NULL, NULL); diff --git a/migrations/2022-09-12-174911_create_objects/down.sql b/migrations/2022-09-12-174911_create_objects/down.sql new file mode 100644 index 0000000..a8b8821 --- /dev/null +++ b/migrations/2022-09-12-174911_create_objects/down.sql @@ -0,0 +1 @@ +DROP TABLE object diff --git a/migrations/2022-09-12-174911_create_objects/up.sql b/migrations/2022-09-12-174911_create_objects/up.sql new file mode 100644 index 0000000..4178bf6 --- /dev/null +++ b/migrations/2022-09-12-174911_create_objects/up.sql @@ -0,0 +1,7 @@ +CREATE TABLE object ( + tag varchar(100) NOT NULL, + nombre varchar(100), + descripcion varchar(2048) NOT NULL, + location_tag varchar(100) NOT NULL, + CONSTRAINT PK_Object PRIMARY KEY (tag) +) diff --git a/migrations/2022-09-12-175351_populate_object/down.sql b/migrations/2022-09-12-175351_populate_object/down.sql new file mode 100644 index 0000000..291a97c --- /dev/null +++ b/migrations/2022-09-12-175351_populate_object/down.sql @@ -0,0 +1 @@ +-- This file should undo anything in `up.sql` \ No newline at end of file diff --git a/migrations/2022-09-12-175351_populate_object/up.sql b/migrations/2022-09-12-175351_populate_object/up.sql new file mode 100644 index 0000000..15cc743 --- /dev/null +++ b/migrations/2022-09-12-175351_populate_object/up.sql @@ -0,0 +1,5 @@ +INSERT INTO object +(tag, nombre, descripcion, location_tag) +VALUES +('o0', 'palanca', 'Trozo de metal, servirá como palanca', '0'), +('o1', 'calmantes', 'Calmantes, sirven para el dolor', '2'); diff --git a/objects/o0.json b/objects/o0.json deleted file mode 100644 index 6533103..0000000 --- a/objects/o0.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "tag": "o0", - "nombre": "palanca", - "descripcion": "Trozo de metal, servirá como palanca." -} diff --git a/src/main.rs b/src/main.rs index 812ec27..87be942 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,9 @@ pub mod rlib; pub mod rlocation; pub mod player; pub mod objects; +pub mod schema; +pub mod models; +pub mod database; use crate::player::Player; diff --git a/src/objects.rs b/src/objects.rs index ff20d41..b3265c9 100644 --- a/src/objects.rs +++ b/src/objects.rs @@ -1,25 +1,32 @@ -use serde::Deserialize; -use std::fs::File; -use std::io::Read; +use crate::models::*; +use diesel::prelude::*; +use crate::database::establish_connection; -#[derive(Debug, Deserialize)] -#[allow(dead_code)] // evita os warnings de que non se le o campo -pub struct Object { - pub tag: String, // tamén é o nome do arquivo, mentras non se implementa bbdd - pub nombre: String, - pub descripcion: String, -} - -// get_object le o arquivo do obxeto e devolve o json -pub fn get_object(tag: String) -> Object { - let dir = "objects"; - let path = format!("{}/{}.json", dir, tag); - - let mut file = File::open(path).expect("Obxeto non atopado."); - let mut data = String::new(); - file.read_to_string(&mut data).expect("Error durante a lectura do obxeto."); - - let object: Object = serde_json::from_str(&data).expect("JSON was not well-formatted"); +//get_object trae da base de datos un obxeto pola sua pegatina +pub fn get_object(pegatina: String) -> Result { + use crate::schema::object::dsl::*; + let conn = &mut establish_connection(); object + .filter(tag.eq(pegatina)) + .first(conn) +} + +// get_objects trae da base de datos todos os obxetos de unha localización +pub fn get_objects(pegatina: String) -> Result, diesel::result::Error> { + use crate::schema::object::dsl::*; + let conn = &mut establish_connection(); + object + .filter(location_tag.eq(pegatina)) + .get_results(conn) +} + +//get_object_here trae da base de datos o obxeto polo nome e a pegatina da sala actual +pub fn get_object_here(pegatina: String, nome: String) -> Result { + use crate::schema::object::dsl::*; + let conn = &mut establish_connection(); + object + .filter(location_tag.eq(pegatina)) + .filter(nombre.eq(nome)) + .first(conn) } diff --git a/src/rlocation.rs b/src/rlocation.rs index 80fe932..7af4bb2 100644 --- a/src/rlocation.rs +++ b/src/rlocation.rs @@ -1,26 +1,10 @@ use crate::player::Player; -use crate::objects::get_object; -use serde::Deserialize; -use std::fs::File; -use std::io::Read; +use crate::objects::get_object_here; -#[derive(Debug, Deserialize)] -#[allow(dead_code)] // evita os warnings de que non se le o campo -pub struct Location { - tag: String, // tamén é o nome do arquivo, mentras non se implementa bbdd - descripcion: String, - salidas: Salidas, - objetos: Vec, -} +use crate::models::*; +use diesel::prelude::*; +use crate::database::establish_connection; -#[derive(Debug, Deserialize)] -#[allow(dead_code)] // evita os warnings de que non se le o campo -pub struct Salidas { - norte: String, - este: String, - sur: String, - oeste: String, -} pub fn execute_look(player: &mut Player, nombre: &str) -> String { let output: String; @@ -29,21 +13,20 @@ pub fn execute_look(player: &mut Player, nombre: &str) -> String { if nombre == "sala" { if player_location.as_str() != "" { - output = String::from(location.descripcion); + output = String::from(location.unwrap().descripcion); } else { output = String::from("Navengado el ether!"); } - } else { - // Recorre os obxetos da sala - for o in location.objetos { - let objeto = get_object(o); - if nombre == objeto.nombre { - output = String::from(objeto.descripcion); - return output; - } + } else if nombre != "" { + // Mira o obxeto que ven en nombre + let objeto = get_object_here(player_location.to_string(), nombre.to_string()); + if objeto.is_ok() { + output = String::from(objeto.unwrap().descripcion); + } else { + output = String::from("No encuentro lo que quieres mirar."); } - - output = String::from("Qué quieres mirar?") + } else { + output = String::from("Qué quieres mirar?"); } return output @@ -55,21 +38,21 @@ pub fn execute_go(player: &mut Player, coord: &str) -> String { if coord != "" { let tag: String; let player_location = &player.location; - let current_location = get_location(player_location.to_string()); + let current_location = get_location(player_location.to_string()).unwrap(); match coord { - "n" => tag = current_location.salidas.norte, - "e" => tag = current_location.salidas.este, - "s" => tag = current_location.salidas.sur, - "o" => tag = current_location.salidas.oeste, - "norte" => tag = current_location.salidas.norte, - "este" => tag = current_location.salidas.este, - "sur" => tag = current_location.salidas.sur, - "oeste" => tag = current_location.salidas.oeste, + "n" => if current_location.salida_norte.is_some() { tag = current_location.salida_norte.unwrap() } else { tag = String::from("")}, + "e" => if current_location.salida_este.is_some() { tag = current_location.salida_este.unwrap()} else { tag = String::from("")}, + "s" => if current_location.salida_sur.is_some() { tag = current_location.salida_sur.unwrap()} else { tag = String::from("")}, + "o" => if current_location.salida_oeste.is_some() { tag = current_location.salida_oeste.unwrap()} else { tag = String::from("")}, + "norte" => if current_location.salida_norte.is_some() { tag = current_location.salida_norte.unwrap()} else { tag = String::from("")}, + "este" => if current_location.salida_este.is_some() { tag = current_location.salida_este.unwrap()} else { tag = String::from("")}, + "sur" => if current_location.salida_sur.is_some() { tag = current_location.salida_sur.unwrap()} else { tag = String::from("")}, + "oeste" => if current_location.salida_oeste.is_some() { tag = current_location.salida_oeste.unwrap()} else { tag = String::from("")}, _ => return String::from("No existe esa dirección.") }; if tag.as_str() != "" { - let location = get_location(tag); + let location = get_location(tag).unwrap(); if location.tag == player.location { output = String::from("No te puedes acercar mucho más..."); } else { @@ -79,6 +62,7 @@ pub fn execute_go(player: &mut Player, coord: &str) -> String { } else { output = String::from("No existe esa salida."); } + } else { output = String::from("No entiendo a donde quieres ir. Debes elegir una coordenada correspondiente a las salidas de esta sala."); } @@ -86,16 +70,11 @@ pub fn execute_go(player: &mut Player, coord: &str) -> String { return output.to_string(); } -// get_location le o arquivo de localización e devolve o json -fn get_location(tag: String) -> Location { - let dir = "locations"; - let path = format!("{}/{}.json", dir, tag); - - let mut file = File::open(path).expect("Localización non atopada."); - let mut data = String::new(); - file.read_to_string(&mut data).expect("Error durante a lectura da localización."); - - let location: Location = serde_json::from_str(&data).expect("JSON was not well-formatted"); - +// get_location busca na base de datos a localización polo seu tag +pub fn get_location(pegatina: String) -> Result { + use crate::schema::location::dsl::*; + let conn = &mut establish_connection(); location + .filter(tag.eq(pegatina)) + .first(conn) }