From 6d988d13f7fc1652e2d041cfd1c4b40dce6a8adb Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Tue, 7 May 2019 05:30:03 +0200 Subject: Add the game server --- .gitignore | 6 ++++++ game_server/Cargo.toml | 9 +++++++++ game_server/build.sh | 3 +++ game_server/src/main.rs | 3 +++ 4 files changed, 21 insertions(+) create mode 100644 game_server/Cargo.toml create mode 100755 game_server/build.sh create mode 100644 game_server/src/main.rs diff --git a/.gitignore b/.gitignore index c3cc7dd..90ff30a 100644 --- a/.gitignore +++ b/.gitignore @@ -263,3 +263,9 @@ __pycache__/ *.pyc /ZooBOTanica/Critters /DSACore/Token + +# Let the fockin cargo shit be +Cargo.lock + +# dont save that target (bad boy) +/game_server/target diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml new file mode 100644 index 0000000..fba755c --- /dev/null +++ b/game_server/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "game-server" +version = "0.1.0" +authors = ["natrixaeria", "truedoctor"] +edition = "2018" +description = "A general game server for connections to web clients. Currently (on the way to) deploying a skribbl.io like game." + +[dependencies] +rocket = "0.4" diff --git a/game_server/build.sh b/game_server/build.sh new file mode 100755 index 0000000..67e239f --- /dev/null +++ b/game_server/build.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +rustup run nightly cargo run diff --git a/game_server/src/main.rs b/game_server/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/game_server/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} -- cgit v1.2.3-70-g09d2 From e2d83e09f8af95c82385967f61e2ec8342a4b2c9 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Tue, 7 May 2019 05:51:58 +0200 Subject: Add a logging feature with pretty_env_logger --- game_server/Cargo.toml | 2 ++ game_server/build.sh | 3 ++- game_server/src/group.rs | 7 +++++++ game_server/src/lobby.rs | 2 ++ game_server/src/main.rs | 10 +++++++++- 5 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 game_server/src/group.rs create mode 100644 game_server/src/lobby.rs diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml index fba755c..f3aabed 100644 --- a/game_server/Cargo.toml +++ b/game_server/Cargo.toml @@ -6,4 +6,6 @@ edition = "2018" description = "A general game server for connections to web clients. Currently (on the way to) deploying a skribbl.io like game." [dependencies] +log = "0.4" +pretty_env_logger = "0.3" rocket = "0.4" diff --git a/game_server/build.sh b/game_server/build.sh index 67e239f..9def83e 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -1,3 +1,4 @@ #!/usr/bin/env sh -rustup run nightly cargo run +rustup run nightly cargo build +RUST_LOG=trace target/debug/game-server diff --git a/game_server/src/group.rs b/game_server/src/group.rs new file mode 100644 index 0000000..3241eee --- /dev/null +++ b/game_server/src/group.rs @@ -0,0 +1,7 @@ +struct Group { + id: u32, + name: String, +} + +impl Group { +} diff --git a/game_server/src/lobby.rs b/game_server/src/lobby.rs new file mode 100644 index 0000000..c0717d3 --- /dev/null +++ b/game_server/src/lobby.rs @@ -0,0 +1,2 @@ +struct Lobby { +} diff --git a/game_server/src/main.rs b/game_server/src/main.rs index e7a11a9..685c633 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,3 +1,11 @@ +mod lobby; +mod group; + +#[macro_use] extern crate log; +use pretty_env_logger; + fn main() { - println!("Hello, world!"); + pretty_env_logger::init(); + + trace!("test info"); } -- cgit v1.2.3-70-g09d2 From 73eb78e3ac5eb7d382c1aca98da84cd866d54570 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Sat, 11 May 2019 06:26:26 +0200 Subject: Create a fundamental project structure --- game_server/build.sh | 8 ++++++-- game_server/src/group.rs | 19 +++++++++++++++++-- game_server/src/lobby.rs | 35 ++++++++++++++++++++++++++++++++++- game_server/src/main.rs | 15 +++++++++++++-- 4 files changed, 70 insertions(+), 7 deletions(-) diff --git a/game_server/build.sh b/game_server/build.sh index 9def83e..c42a7ac 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -1,4 +1,8 @@ #!/usr/bin/env sh -rustup run nightly cargo build -RUST_LOG=trace target/debug/game-server +if rustup run nightly cargo build; then + echo build success! + RUST_LOG=trace target/debug/game-server +else + echo build failed! +fi diff --git a/game_server/src/group.rs b/game_server/src/group.rs index 3241eee..9774979 100644 --- a/game_server/src/group.rs +++ b/game_server/src/group.rs @@ -1,7 +1,22 @@ -struct Group { - id: u32, +pub type GroupId = u32; + +pub struct Group { + id: GroupId, name: String, } impl Group { + pub(crate) fn new(id: GroupId, name: String) -> Group { + Group { id, name } + } + + pub(crate) fn get_id(&self) -> GroupId { + self.id + } + + pub fn run(&self) { + let id = self.id; + std::thread::spawn(move || + loop {println!("group id: {} meldet sich", id)}); + } } diff --git a/game_server/src/lobby.rs b/game_server/src/lobby.rs index c0717d3..8808b7f 100644 --- a/game_server/src/lobby.rs +++ b/game_server/src/lobby.rs @@ -1,2 +1,35 @@ -struct Lobby { +use std::collections::HashMap; + +use super::group::{Group, GroupId}; + +pub struct Lobby { + groups: HashMap, +} + +impl Lobby { + pub fn new() -> Lobby { + Self { + groups: HashMap::new(), + } + } + + pub fn add_group(&mut self, group: Group) { + self.groups.insert(group.get_id(), group); + } + + pub fn iter<'a>(&'a self) -> GroupIterator<'a> { + GroupIterator { groups: self.groups.values() } + } +} + +pub struct GroupIterator<'a> { + groups: std::collections::hash_map::Values<'a, GroupId, Group> +} + +impl<'a> Iterator for GroupIterator<'a> { + type Item = &'a Group; + + fn next(&mut self) -> Option { + self.groups.next() + } } diff --git a/game_server/src/main.rs b/game_server/src/main.rs index 685c633..7e08b46 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,11 +1,22 @@ -mod lobby; mod group; +mod lobby; #[macro_use] extern crate log; use pretty_env_logger; +use group::Group; +use lobby::Lobby; + fn main() { pretty_env_logger::init(); - trace!("test info"); + let mut lobby = Lobby::new(); + lobby.add_group(Group::new(0, "Test".to_string())); + lobby.add_group(Group::new(1, "Very Serious".to_string())); + + for group in lobby.iter() { + group.run() + } + + loop {} } -- cgit v1.2.3-70-g09d2 From eedd564c1490a1cc785a1a8bbfdc3e5987543e52 Mon Sep 17 00:00:00 2001 From: TrueDoctor Date: Wed, 15 May 2019 23:05:47 +0200 Subject: change chathub url --- WebInterface/NodeJSServer/src/js/play.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WebInterface/NodeJSServer/src/js/play.js b/WebInterface/NodeJSServer/src/js/play.js index af0f70d..2d4effe 100644 --- a/WebInterface/NodeJSServer/src/js/play.js +++ b/WebInterface/NodeJSServer/src/js/play.js @@ -2,7 +2,7 @@ import Interface from './modules/interface'; import UIManager from './modules/ui/uiManager'; import Networker from './modules/networking/networker'; -const SERVERURL = 'https://kobert.dev/dsa/api/chatHub'; +const SERVERURL = 'https://kobert.dev/api/Login'; let iface = new Interface(); let uiMan = new UIManager(iface); -- cgit v1.2.3-70-g09d2 From 163897120db77d45435ab1576aaa28f6d9409bf5 Mon Sep 17 00:00:00 2001 From: TrueDoctor Date: Wed, 15 May 2019 23:08:09 +0200 Subject: see last commit --- WebInterface/NodeJSServer/src/js/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WebInterface/NodeJSServer/src/js/index.js b/WebInterface/NodeJSServer/src/js/index.js index 407cd39..249adc9 100644 --- a/WebInterface/NodeJSServer/src/js/index.js +++ b/WebInterface/NodeJSServer/src/js/index.js @@ -2,7 +2,7 @@ import Interface from './modules/interface'; import UIManager from './modules/ui/uiManager'; import Networker from './modules/networking/networker'; -const SERVERURL = 'https://kobert.dev/dsa/api/chatHub'; +const SERVERURL = 'https://kobert.dev/api/Login'; let iface = new Interface(); let uiMan = new UIManager(iface); -- cgit v1.2.3-70-g09d2 From 2f9e5dfaac05538fdf4513569b4df6872ee85b89 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Wed, 15 May 2019 23:46:11 +0200 Subject: Add web client functionality additionally added -r feature to build.sh, which reverses build output. --- game_server/Cargo.toml | 3 +- game_server/build.sh | 25 +++++++++--- game_server/err | 73 +++++++++++++++++++++++++++++++++++ game_server/rbuild.sh | 2 + game_server/src/backend_connection.rs | 31 +++++++++++++++ game_server/src/gameserver.rs | 0 game_server/src/group.rs | 22 ++--------- game_server/src/lobby.rs | 10 ++--- game_server/src/main.rs | 13 +++++-- game_server/src/test_group.rs | 28 ++++++++++++++ 10 files changed, 173 insertions(+), 34 deletions(-) create mode 100644 game_server/err create mode 100644 game_server/rbuild.sh create mode 100644 game_server/src/backend_connection.rs create mode 100644 game_server/src/gameserver.rs create mode 100644 game_server/src/test_group.rs diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml index f3aabed..baf27fa 100644 --- a/game_server/Cargo.toml +++ b/game_server/Cargo.toml @@ -8,4 +8,5 @@ description = "A general game server for connections to web clients. Currently ( [dependencies] log = "0.4" pretty_env_logger = "0.3" -rocket = "0.4" +reqwest = "0.9" +websocket = "0.22" diff --git a/game_server/build.sh b/game_server/build.sh index c42a7ac..5929e29 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -1,8 +1,21 @@ #!/usr/bin/env sh -if rustup run nightly cargo build; then - echo build success! - RUST_LOG=trace target/debug/game-server -else - echo build failed! -fi +case $1 in + ("") + if rustup run nightly cargo --color always build; then + echo build success! + RUST_LOG=info target/debug/game-server + else + echo build failed! + fi + ;; + -r) + sh build.sh &> err && cat err | tac + ;; + -c) + rustup run nightly cargo clean + ;; + *) + echo invalid argument + ;; +esac diff --git a/game_server/err b/game_server/err new file mode 100644 index 0000000..6ca8a6f --- /dev/null +++ b/game_server/err @@ -0,0 +1,73 @@ + Compiling game-server v0.1.0 (/home/jan/projects/DiscoBot/game_server) +error[E0277]: the trait bound `(): futures::future::Future` is not satisfied + --> src/backend_connection.rs:32:24 + | +32 |  hyper::rt::run(hyper::rt::lazy(|| { + |  ^^^^^^^^^^^^^^^ the trait `futures::future::Future` is not implemented for `()` + | + = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `()` + = note: required by `futures::future::lazy::lazy` + +error[E0599]: no method named `wait` found for type `std::result::Result, [closure@src/backend_connection.rs:55:38: 55:73]>, http::uri::InvalidUri>` in the current scope + --> src/backend_connection.rs:56:24 + | +56 |  }).wait(); + |  ^^^^ + | + = note: the method `wait` exists but the following trait bounds were not satisfied: + `&mut std::result::Result, [closure@src/backend_connection.rs:55:38: 55:73]>, http::uri::InvalidUri> : futures::future::Future` + +error[E0308]: mismatched types + --> src/backend_connection.rs:58:17 + | +58 |  res + |  ^^^ expected (), found enum `std::result::Result` + | + = note: expected type `()` + found type `std::result::Result, http::uri::InvalidUri>` + +error[E0277]: the trait bound `(): futures::future::Future` is not satisfied + --> src/backend_connection.rs:32:24 + | +32 |   hyper::rt::run(hyper::rt::lazy(|| { + |  ________________________^ +33 | |  let client = hyper::Client::builder() +34 | |  .build::<_, hyper::Body>( +35 | |  HttpsConnector::new(4).unwrap() +... | +59 | |  } +60 | |  })); + | |__________^ the trait `futures::future::Future` is not implemented for `()` + | + = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `()` + = note: required by `futures::future::lazy::Lazy` + +error[E0277]: the trait bound `(): futures::future::Future` is not satisfied + --> src/backend_connection.rs:32:9 + | +32 |  hyper::rt::run(hyper::rt::lazy(|| { + |  ^^^^^^^^^^^^^^ the trait `futures::future::Future` is not implemented for `()` + | + = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `()` + = note: required by `hyper::rt::run` + +error[E0063]: missing field `res_receiver` in initializer of `backend_connection::BackendConnection` + --> src/backend_connection.rs:62:9 + | +62 |  BackendConnection { + |  ^^^^^^^^^^^^^^^^^ missing `res_receiver` + +error[E0609]: no field `request_sender` on type `&backend_connection::BackendConnection` + --> src/backend_connection.rs:69:14 + | +69 |  self.request_sender.send( + |  ^^^^^^^^^^^^^^ + +error: aborting due to 7 previous errors + +Some errors have detailed explanations: E0063, E0277, E0308, E0599, E0609. +For more information about an error, try `rustc --explain E0063`. +error: Could not compile `game-server`. + +To learn more, run the command again with --verbose. +build failed! diff --git a/game_server/rbuild.sh b/game_server/rbuild.sh new file mode 100644 index 0000000..22b10b5 --- /dev/null +++ b/game_server/rbuild.sh @@ -0,0 +1,2 @@ +#!/bin/bash +sh build.sh &> err && cat err | tac diff --git a/game_server/src/backend_connection.rs b/game_server/src/backend_connection.rs new file mode 100644 index 0000000..9307c4a --- /dev/null +++ b/game_server/src/backend_connection.rs @@ -0,0 +1,31 @@ +use reqwest::{Response, Client, Url, UrlError, Error as ReqError}; + +pub struct BackendConnection { + host: String, + client: Client, + last_response: Option> +} + +impl BackendConnection { + pub fn new(host: &str) -> Self { + BackendConnection { + host: host.to_string(), + client: Client::new(), + last_response: None + } + } + + pub fn request(&mut self, location: &str) -> Result<(), UrlError> { + Ok(self.last_response = + Some(self.client.get(Url::parse(&format!("{}{}", self.host, location))?) + .send())) + } + + pub fn get_response(&self) -> &Option> { + &self.last_response + } + + pub fn host_name<'a>(&'a self) -> &'a str { + &self.host + } +} diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs new file mode 100644 index 0000000..e69de29 diff --git a/game_server/src/group.rs b/game_server/src/group.rs index 9774979..55e4fbf 100644 --- a/game_server/src/group.rs +++ b/game_server/src/group.rs @@ -1,22 +1,8 @@ pub type GroupId = u32; -pub struct Group { - id: GroupId, - name: String, -} - -impl Group { - pub(crate) fn new(id: GroupId, name: String) -> Group { - Group { id, name } - } - - pub(crate) fn get_id(&self) -> GroupId { - self.id - } +pub trait Group { + fn id(&self) -> GroupId; + fn name(&self) -> String; - pub fn run(&self) { - let id = self.id; - std::thread::spawn(move || - loop {println!("group id: {} meldet sich", id)}); - } + fn run(&self); } diff --git a/game_server/src/lobby.rs b/game_server/src/lobby.rs index 8808b7f..fe3bdee 100644 --- a/game_server/src/lobby.rs +++ b/game_server/src/lobby.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use super::group::{Group, GroupId}; pub struct Lobby { - groups: HashMap, + groups: HashMap>, } impl Lobby { @@ -13,8 +13,8 @@ impl Lobby { } } - pub fn add_group(&mut self, group: Group) { - self.groups.insert(group.get_id(), group); + pub fn add_group(&mut self, group: Box) { + self.groups.insert(group.id(), group); } pub fn iter<'a>(&'a self) -> GroupIterator<'a> { @@ -23,11 +23,11 @@ impl Lobby { } pub struct GroupIterator<'a> { - groups: std::collections::hash_map::Values<'a, GroupId, Group> + groups: std::collections::hash_map::Values<'a, GroupId, Box> } impl<'a> Iterator for GroupIterator<'a> { - type Item = &'a Group; + type Item = &'a Box; fn next(&mut self) -> Option { self.groups.next() diff --git a/game_server/src/main.rs b/game_server/src/main.rs index 7e08b46..f7a1085 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,22 +1,27 @@ mod group; +mod test_group; mod lobby; +mod backend_connection; #[macro_use] extern crate log; use pretty_env_logger; -use group::Group; +use test_group::TestGroup; use lobby::Lobby; +use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); let mut lobby = Lobby::new(); - lobby.add_group(Group::new(0, "Test".to_string())); - lobby.add_group(Group::new(1, "Very Serious".to_string())); for group in lobby.iter() { group.run() } - loop {} + let mut backend = BackendConnection::new("http://129.13.215.68:5000"); + loop { + backend.request("/scribble").unwrap(); + println!("{:?}", backend.get_response()); + } } diff --git a/game_server/src/test_group.rs b/game_server/src/test_group.rs new file mode 100644 index 0000000..bd570e3 --- /dev/null +++ b/game_server/src/test_group.rs @@ -0,0 +1,28 @@ +use super::group::{Group, GroupId}; + +pub struct TestGroup { + id: GroupId, + name: String, +} + +impl Group for TestGroup { + fn id(&self) -> GroupId { + self.id + } + + fn name(&self) -> String { + self.name.clone() + } + + fn run(&self) { + let id = self.id; + let name = self.name.to_owned(); + std::thread::spawn(move || /*loop { println!("> group nr.{} wishes you: '{}'", id, name) }*/()); + } +} + +impl TestGroup { + pub fn new(id: GroupId, name: String) -> Self { + TestGroup { id, name } + } +} -- cgit v1.2.3-70-g09d2 From 91fc989eea5ee16c2f000064b5c040a6fe6f23b9 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Thu, 16 May 2019 01:10:10 +0200 Subject: Implement tokens --- DSACore/Auxiliary/WeaponImporter.cs | 1 + DSACore/Controllers/CommandsController.cs | 4 +- DSACore/Controllers/LobbyController.cs | 32 +++ DSACore/Controllers/TokensController.cs | 28 +++ DSACore/DSACore.csproj | 6 +- DSACore/DSA_Game/Dsa.cs | 2 +- DSACore/FireBase/Database.cs | 2 + DSACore/Hubs/ChatHub.cs | 216 ------------------- DSACore/Hubs/Login.cs | 228 +++++++++++++++++++++ DSACore/Models/Database/Advantage.cs | 19 -- DSACore/Models/Database/CharSpell.cs | 19 -- DSACore/Models/Database/DSA/Advantage.cs | 16 ++ DSACore/Models/Database/DSA/CharSpell.cs | 16 ++ DSACore/Models/Database/DSA/DatabaseChar.cs | 61 ++++++ DSACore/Models/Database/DSA/Field.cs | 16 ++ DSACore/Models/Database/DSA/GeneralSpell.cs | 20 ++ DSACore/Models/Database/DSA/GroupChar.cs | 13 ++ DSACore/Models/Database/DSA/Inventory.cs | 12 ++ DSACore/Models/Database/DSA/Talent.cs | 26 +++ DSACore/Models/Database/DSA/Weapon.cs | 50 +++++ DSACore/Models/Database/DSA/WeaponTalent.cs | 18 ++ DSACore/Models/Database/DatabaseChar.cs | 63 ------ DSACore/Models/Database/Field.cs | 19 -- DSACore/Models/Database/GeneralSpell.cs | 25 --- DSACore/Models/Database/Group.cs | 19 -- DSACore/Models/Database/GroupChar.cs | 18 -- DSACore/Models/Database/Groups/DSAGroup.cs | 10 + DSACore/Models/Database/Groups/Group.cs | 13 ++ DSACore/Models/Database/Inventory.cs | 15 -- DSACore/Models/Database/Talent.cs | 29 --- DSACore/Models/Database/Weapon.cs | 53 ----- DSACore/Models/Database/WeaponTalent.cs | 18 -- DSACore/Models/Network/Token.cs | 21 ++ DSACore/Startup.cs | 2 +- .../src/js/modules/ui/components/modal/modal.js | 1 - 35 files changed, 592 insertions(+), 519 deletions(-) create mode 100644 DSACore/Controllers/LobbyController.cs create mode 100644 DSACore/Controllers/TokensController.cs delete mode 100644 DSACore/Hubs/ChatHub.cs create mode 100644 DSACore/Hubs/Login.cs delete mode 100644 DSACore/Models/Database/Advantage.cs delete mode 100644 DSACore/Models/Database/CharSpell.cs create mode 100644 DSACore/Models/Database/DSA/Advantage.cs create mode 100644 DSACore/Models/Database/DSA/CharSpell.cs create mode 100644 DSACore/Models/Database/DSA/DatabaseChar.cs create mode 100644 DSACore/Models/Database/DSA/Field.cs create mode 100644 DSACore/Models/Database/DSA/GeneralSpell.cs create mode 100644 DSACore/Models/Database/DSA/GroupChar.cs create mode 100644 DSACore/Models/Database/DSA/Inventory.cs create mode 100644 DSACore/Models/Database/DSA/Talent.cs create mode 100644 DSACore/Models/Database/DSA/Weapon.cs create mode 100644 DSACore/Models/Database/DSA/WeaponTalent.cs delete mode 100644 DSACore/Models/Database/DatabaseChar.cs delete mode 100644 DSACore/Models/Database/Field.cs delete mode 100644 DSACore/Models/Database/GeneralSpell.cs delete mode 100644 DSACore/Models/Database/Group.cs delete mode 100644 DSACore/Models/Database/GroupChar.cs create mode 100644 DSACore/Models/Database/Groups/DSAGroup.cs create mode 100644 DSACore/Models/Database/Groups/Group.cs delete mode 100644 DSACore/Models/Database/Inventory.cs delete mode 100644 DSACore/Models/Database/Talent.cs delete mode 100644 DSACore/Models/Database/Weapon.cs delete mode 100644 DSACore/Models/Database/WeaponTalent.cs create mode 100644 DSACore/Models/Network/Token.cs diff --git a/DSACore/Auxiliary/WeaponImporter.cs b/DSACore/Auxiliary/WeaponImporter.cs index 8ed2b3f..635d477 100644 --- a/DSACore/Auxiliary/WeaponImporter.cs +++ b/DSACore/Auxiliary/WeaponImporter.cs @@ -6,6 +6,7 @@ using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using DSACore.FireBase; +using DSACore.Models.Database.DSA; using Group = System.Text.RegularExpressions.Group; namespace DSACore.Auxiliary diff --git a/DSACore/Controllers/CommandsController.cs b/DSACore/Controllers/CommandsController.cs index 5f27f63..d35690c 100644 --- a/DSACore/Controllers/CommandsController.cs +++ b/DSACore/Controllers/CommandsController.cs @@ -10,14 +10,14 @@ using Microsoft.AspNetCore.Mvc; namespace DSACore.Controllers { - [Route("api/[controller]")] + [Route("dsa/[controller]")] public class CommandsController : Controller { // GET: api/ [HttpGet] public string Get() { - return "Dies ist die supa dolle Web Api"; + return "Usage: post the command to execute"; } // GET api//5 diff --git a/DSACore/Controllers/LobbyController.cs b/DSACore/Controllers/LobbyController.cs new file mode 100644 index 0000000..a946184 --- /dev/null +++ b/DSACore/Controllers/LobbyController.cs @@ -0,0 +1,32 @@ +using DSACore.Models.Network; +using System; +using Microsoft.AspNetCore.Mvc; + +namespace DSACore.Controllers +{ + public class ScribbleController : Controller + { + [Route("[controller]")] + // GET: api/ + [HttpGet] + public string Get() + { + return "Usage: get /tokens/{Token}"; + } + + [HttpPost] + public string Post([FromBody]Command cmd) + { + try + { + return Commands.CommandHandler.ExecuteCommand(cmd).message; + } + catch (Exception e) + { + return $"Ein Fehler ist aufgetreten: \n {e.Message}"; + } + + } + + } +} \ No newline at end of file diff --git a/DSACore/Controllers/TokensController.cs b/DSACore/Controllers/TokensController.cs new file mode 100644 index 0000000..453d477 --- /dev/null +++ b/DSACore/Controllers/TokensController.cs @@ -0,0 +1,28 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace DSACore.Controllers +{ + [Route("lobby/[controller]")] + [ApiController] + public class TokensController : Controller + { + + // GET + [HttpGet("{token}")] + public async Task> Get(int token) + { + + if (!Hubs.Users.Tokens.Exists(x => x.GetHashCode() == token)) + { + return NotFound(); + } + + var group = Hubs.Users.Tokens.Find(x => x.GetHashCode() == token); + return Ok(group); + } + } +} \ No newline at end of file diff --git a/DSACore/DSACore.csproj b/DSACore/DSACore.csproj index ad760c2..3d928e1 100644 --- a/DSACore/DSACore.csproj +++ b/DSACore/DSACore.csproj @@ -1,4 +1,4 @@ - + netcoreapp2.1 @@ -18,4 +18,8 @@ + + + + diff --git a/DSACore/DSA_Game/Dsa.cs b/DSACore/DSA_Game/Dsa.cs index 3b2e4aa..cbdb734 100644 --- a/DSACore/DSA_Game/Dsa.cs +++ b/DSACore/DSA_Game/Dsa.cs @@ -16,7 +16,7 @@ namespace DSACore.DSA_Game public static class Dsa { #if DEBUG - public const string rootPath = "C:\\Users\\Dennis\\Source\\Repos\\DiscoBot\\DSACore\\";//"DiscoBot\\DSACore\\"; + public const string rootPath = "";//"C:\\Users\\Dennis\\Source\\Repos\\DiscoBot\\DSACore\\";//"DiscoBot\\DSACore\\"; #else public const string rootPath = "";//"DiscoBot\\DSACore\\"; #endif diff --git a/DSACore/FireBase/Database.cs b/DSACore/FireBase/Database.cs index db57381..15b76f0 100644 --- a/DSACore/FireBase/Database.cs +++ b/DSACore/FireBase/Database.cs @@ -6,6 +6,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using DSACore.Models.Database.DSA; +using DSACore.Models.Database.Groups; namespace DSACore.FireBase diff --git a/DSACore/Hubs/ChatHub.cs b/DSACore/Hubs/ChatHub.cs deleted file mode 100644 index 1994164..0000000 --- a/DSACore/Hubs/ChatHub.cs +++ /dev/null @@ -1,216 +0,0 @@ -using DSACore.DSA_Game.Characters; -using DSACore.FireBase; -using DSACore.Models.Network; -using Microsoft.AspNetCore.SignalR; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace DSACore.Hubs -{ - public class ChatHub : Hub - { - //private static Dictionary UserGroup = new Dictionary(); - - private const string receiveMethod = "ReceiveMessage";//receiveMethod; - - private static List DSAGroups = new List(); - - static ChatHub() - { - DSAGroups = Database.GetGroups().Result; - DSAGroups.Add(new Group("login", "")); - DSAGroups.Add(new Group("online", "")); - //AddGroups(); - } - - private static async void AddGroups() - { - await Database.AddGroup(new Models.Database.Group { Name = "HalloWelt", Password = "valid" }); - await Database.AddGroup(new Models.Database.Group { Name = "Die Krassen Gamer", Password = "valid" }); - await Database.AddGroup(new Models.Database.Group { Name = "DSA", Password = "valid" }); - await Database.AddGroup(new Models.Database.Group { Name = "Die Überhelden", Password = "valid" }); - } - - public async Task SendMessage(string user, string message) - { - try - { - string group = getGroup(Context.ConnectionId).Name; - } - catch (InvalidOperationException e) - { - //await Clients.Caller.SendCoreAsync(receiveMethod, - // new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" }); - } - - if (message[0] == '/') - { - var args = message.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList(); - - bool Timon = args.Any(x => x == "hallo"); - - var ident = args.First().Replace("/", ""); - if (args.Count > 0) - { - args.RemoveAt(0); - } - - var ret = Commands.CommandHandler.ExecuteCommand(new Command - { - CharId = 0, - CmdIdentifier = ident, - CmdTexts = args, - Name = user - }); - - switch (ret.ResponseType) - { - case ResponseType.Caller: - case ResponseType.Error: - await Clients.Caller.SendAsync(receiveMethod, ret.message); - break; - case ResponseType.Broadcast: - await SendToGroup(ret.message); - break; - } - - - } - else - { - await SendToGroup(message); - } - - } - - private Task SendToGroup(string message) - { - try - { - string group = getGroup(Context.ConnectionId).Name; - return Clients.Group(group).SendCoreAsync(receiveMethod, - new object[] {getUser(Context.ConnectionId).Name, message}); - } - catch (InvalidOperationException e) - { - return Clients.Caller.SendCoreAsync(receiveMethod, - new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" }); - } - } - - private Models.Network.Group getGroup(string id) - { - return DSAGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))); - } - - private User getUser(string id) - { - return DSAGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))).Users.First(z => z.ConnectionId.Equals(id)); - } - - public async Task GetGroups() - { - var test = Database.GetGroups(); - test.Wait(); - foreach (var group in test.Result) - { - if (!DSAGroups.Exists(x => x.Name.Equals(group.Name))) - { - DSAGroups.Add(group); - } - } - - await Clients.Caller.SendCoreAsync("ListGroups", new object[] { DSAGroups.Select(x => x.SendGroup()) }); - //throw new NotImplementedException("add database call to get groups"); - } - - public async Task AddGroup(string group, string password) - { - DSAGroups.Add(new Group(group, password)); - var Dgroup = new DSACore.Models.Database.Group { Name = group, Id = DSAGroups.Count - 1 }; - //Database.AddGroup(Dgroup); - await Clients.Caller.SendCoreAsync(receiveMethod, new[] { $"group {@group} sucessfully added" }); - //throw new NotImplementedException("add database call to add groups"); - } - - public async Task UploadChar(string xml) - { - var group = getGroup(Context.ConnectionId); - - await Database.AddChar(new Character(new MemoryStream(Encoding.UTF8.GetBytes(xml))), group); - //throw new NotImplementedException("add database call to add groups"); - } - - public async Task Login(string group, string user, string hash) - { - //string password = System.Text.Encoding.UTF8.GetString(hash); - if (hash == DSAGroups.First(x => x.Name == group).Password) - { - var gGroup = DSAGroups.First(x => x.Name.Equals(group)); - if (!gGroup.Users.Exists(x => x.Name.Equals(user))) - { - await Groups.RemoveFromGroupAsync(Context.ConnectionId, "login"); - await Groups.AddToGroupAsync(Context.ConnectionId, group); - gGroup.Users.Add(new User { ConnectionId = Context.ConnectionId, Name = user }); - await SendToGroup("Ein neuer Nutzer hat die Gruppe betreten"); - await Clients.Caller.SendAsync("LoginResponse", 0); - await Clients.Caller.SendAsync("PlayerStatusChanged", new[] {user, "online"}); - } - else - { - await Clients.Caller.SendAsync("LoginResponse", 1); - } - } - else - { - await Clients.Caller.SendAsync("LoginResponse", 2); - //await Clients.Caller.SendAsync(receiveMethod, "Falsches Passwort!"); - } - } - - public override Task OnDisconnectedAsync(Exception exception) - { - Disconnect().Wait(); - return base.OnDisconnectedAsync(exception); - } - - public override Task OnConnectedAsync() - { - Groups.AddToGroupAsync(Context.ConnectionId, "login").Wait(); - Groups.AddToGroupAsync(Context.ConnectionId, "online").Wait(); - return base.OnConnectedAsync(); - } - - public async Task Disconnect() - { - await Groups.RemoveFromGroupAsync(Context.ConnectionId, "online"); - if (DSAGroups.Exists(x => x.Users.Exists(y => y.ConnectionId == Context.ConnectionId))) - { - try - { - var group = getGroup(Context.ConnectionId); - - - var user = getUser(Context.ConnectionId); - - await Clients.Caller.SendAsync("PlayerStatusChanged", new[] { user.Name, "offline" }); - //await SendToGroup(user.Name + " disconnected from the Server"); - group.Users.Remove(user); - await Groups.RemoveFromGroupAsync(Context.ConnectionId, group.Name); - } - catch (Exception e) - { - Console.WriteLine(e); - //throw; - } - } - - } - - } -} diff --git a/DSACore/Hubs/Login.cs b/DSACore/Hubs/Login.cs new file mode 100644 index 0000000..5f984e2 --- /dev/null +++ b/DSACore/Hubs/Login.cs @@ -0,0 +1,228 @@ +using DSACore.DSA_Game.Characters; +using DSACore.FireBase; +using DSACore.Models.Network; +using Microsoft.AspNetCore.SignalR; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace DSACore.Hubs +{ + public class Users : Hub + { + //private static Dictionary UserGroup = new Dictionary(); + + private const string ReceiveMethod = "ReceiveMessage";//receiveMethod; + + private static List DsaGroups {get; set; } + public static List Tokens { get;} = new List(); + + static Users() + { + DsaGroups = Database.GetGroups().Result; + DsaGroups.Add(new Group("login", "")); + DsaGroups.Add(new Group("online", "")); + //AddGroups(); + } + + + [Obsolete] + private static async void AddGroups() + { + await Database.AddGroup(new Models.Database.Groups.Group { Name = "HalloWelt", Password = "valid" }); + await Database.AddGroup(new Models.Database.Groups.Group { Name = "Die Krassen Gamer", Password = "valid" }); + await Database.AddGroup(new Models.Database.Groups.Group { Name = "DSA", Password = "valid" }); + await Database.AddGroup(new Models.Database.Groups.Group { Name = "Die Überhelden", Password = "valid" }); + } + + public async Task SendMessage(string user, string message) + { + try + { + string group = getGroup(Context.ConnectionId).Name; + } + catch (InvalidOperationException e) + { + //await Clients.Caller.SendCoreAsync(receiveMethod, + // new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" }); + } + + if (message[0] == '/') + { + var args = message.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList(); + + bool Timon = args.Any(x => x == "hallo"); + + var ident = args.First().Replace("/", ""); + if (args.Count > 0) + { + args.RemoveAt(0); + } + + var ret = Commands.CommandHandler.ExecuteCommand(new Command + { + CharId = 0, + CmdIdentifier = ident, + CmdTexts = args, + Name = user + }); + + switch (ret.ResponseType) + { + case ResponseType.Caller: + case ResponseType.Error: + await Clients.Caller.SendAsync(ReceiveMethod, ret.message); + break; + case ResponseType.Broadcast: + await SendToGroup(ret.message); + break; + } + + + } + else + { + await SendToGroup(message); + } + + } + + private Task SendToGroup(string message) + { + try + { + string group = getGroup(Context.ConnectionId).Name; + return Clients.Group(group).SendCoreAsync(ReceiveMethod, + new object[] {getUser(Context.ConnectionId).Name, message}); + } + catch (InvalidOperationException e) + { + return Clients.Caller.SendCoreAsync(ReceiveMethod, + new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" }); + } + } + + private Models.Network.Group getGroup(string id) + { + return DsaGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))); + } + + private User getUser(string id) + { + return DsaGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))).Users.First(z => z.ConnectionId.Equals(id)); + } + + public async Task GetGroups() + { + var test = await Database.GetGroups(); + + foreach (var group in test) + { + if (!DsaGroups.Exists(x => x.Name.Equals(group.Name))) + { + DsaGroups.Add(group); + } + } + + await Clients.Caller.SendCoreAsync("ListGroups", new object[] { DsaGroups.Select(x => x.SendGroup()) }); + //throw new NotImplementedException("add database call to get groups"); + } + + public async Task AddGroup(string group, string password) + { + DsaGroups.Add(new Group(group, password)); + var Dgroup = new Models.Database.Groups.Group { Name = group, Id = DsaGroups.Count - 1 }; + //Database.AddGroup(Dgroup); + await Clients.Caller.SendCoreAsync(ReceiveMethod, new[] { $"group {@group} sucessfully added" }); + //throw new NotImplementedException("add database call to add groups"); + } + + public async Task UploadChar(string xml) + { + var group = getGroup(Context.ConnectionId); + + await Database.AddChar(new Character(new MemoryStream(Encoding.UTF8.GetBytes(xml))), group); + //throw new NotImplementedException("add database call to add groups"); + } + + public async Task Login(string group, string user, string hash) + { + //string password = System.Text.Encoding.UTF8.GetString(hash); + if (hash == DsaGroups.First(x => x.Name == group).Password) + { + var gGroup = DsaGroups.First(x => x.Name.Equals(group)); + if (!gGroup.Users.Exists(x => x.Name.Equals(user))) + { + await Groups.RemoveFromGroupAsync(Context.ConnectionId, "login"); + await Groups.AddToGroupAsync(Context.ConnectionId, group); + gGroup.Users.Add(new User { ConnectionId = Context.ConnectionId, Name = user }); + await SendToGroup("Ein neuer Nutzer hat die Gruppe betreten"); + await Clients.Caller.SendAsync("LoginResponse", 0); + await Clients.Caller.SendAsync("PlayerStatusChanged", new[] {user, "online"}); + + Tokens.Add(new Token(group)); + await Clients.Caller.SendAsync("Token", Tokens.Last().GetHashCode()); + purgeTokens(); + } + else + { + await Clients.Caller.SendAsync("LoginResponse", 1); + } + } + else + { + await Clients.Caller.SendAsync("LoginResponse", 2); + //await Clients.Caller.SendAsync(receiveMethod, "Falsches Passwort!"); + } + } + + private void purgeTokens() + { + Tokens.RemoveAll(x => !x.IsValid()); + } + + public override Task OnDisconnectedAsync(Exception exception) + { + Disconnect().Wait(); + return base.OnDisconnectedAsync(exception); + } + + public override Task OnConnectedAsync() + { + Groups.AddToGroupAsync(Context.ConnectionId, "login").Wait(); + Groups.AddToGroupAsync(Context.ConnectionId, "online").Wait(); + return base.OnConnectedAsync(); + } + + public async Task Disconnect() + { + await Groups.RemoveFromGroupAsync(Context.ConnectionId, "online"); + if (DsaGroups.Exists(x => x.Users.Exists(y => y.ConnectionId == Context.ConnectionId))) + { + try + { + var group = getGroup(Context.ConnectionId); + + + var user = getUser(Context.ConnectionId); + + await Clients.Caller.SendAsync("PlayerStatusChanged", new[] { user.Name, "offline" }); + //await SendToGroup(user.Name + " disconnected from the Server"); + group.Users.Remove(user); + await Groups.RemoveFromGroupAsync(Context.ConnectionId, group.Name); + } + catch (Exception e) + { + Console.WriteLine(e); + //throw; + } + } + + } + + } +} diff --git a/DSACore/Models/Database/Advantage.cs b/DSACore/Models/Database/Advantage.cs deleted file mode 100644 index 67965fc..0000000 --- a/DSACore/Models/Database/Advantage.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class Advantage - { - public Advantage(string name, string value = "") - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - Value = value ?? throw new ArgumentNullException(nameof(value)); - } - - public string Name { get; set; } - public string Value { get; set; } - } -} diff --git a/DSACore/Models/Database/CharSpell.cs b/DSACore/Models/Database/CharSpell.cs deleted file mode 100644 index 670488c..0000000 --- a/DSACore/Models/Database/CharSpell.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class CharSpell - { - public CharSpell(string representation, int value) - { - this.representation = representation ?? throw new ArgumentNullException(nameof(representation)); - this.value = value; - } - - public string representation { get; set; } - public int value { get; set; } - } -} diff --git a/DSACore/Models/Database/DSA/Advantage.cs b/DSACore/Models/Database/DSA/Advantage.cs new file mode 100644 index 0000000..2f0b443 --- /dev/null +++ b/DSACore/Models/Database/DSA/Advantage.cs @@ -0,0 +1,16 @@ +using System; + +namespace DSACore.Models.Database.DSA +{ + public class Advantage + { + public Advantage(string name, string value = "") + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + Value = value ?? throw new ArgumentNullException(nameof(value)); + } + + public string Name { get; set; } + public string Value { get; set; } + } +} diff --git a/DSACore/Models/Database/DSA/CharSpell.cs b/DSACore/Models/Database/DSA/CharSpell.cs new file mode 100644 index 0000000..63d917a --- /dev/null +++ b/DSACore/Models/Database/DSA/CharSpell.cs @@ -0,0 +1,16 @@ +using System; + +namespace DSACore.Models.Database.DSA +{ + public class CharSpell + { + public CharSpell(string representation, int value) + { + this.representation = representation ?? throw new ArgumentNullException(nameof(representation)); + this.value = value; + } + + public string representation { get; set; } + public int value { get; set; } + } +} diff --git a/DSACore/Models/Database/DSA/DatabaseChar.cs b/DSACore/Models/Database/DSA/DatabaseChar.cs new file mode 100644 index 0000000..8c51821 --- /dev/null +++ b/DSACore/Models/Database/DSA/DatabaseChar.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace DSACore.Models.Database.DSA +{ + public class DatabaseChar + { + public DatabaseChar() + { + } + + public DatabaseChar(int id, string name, string rasse, List skills, List talents, List advantages, List spells, List weaponTalents) + { + Id = id; + Name = name ?? throw new ArgumentNullException(nameof(name)); + Rasse = rasse ?? throw new ArgumentNullException(nameof(rasse)); + Skills = skills ?? throw new ArgumentNullException(nameof(skills)); + Talents = talents ?? throw new ArgumentNullException(nameof(talents)); + Advantages = advantages ?? throw new ArgumentNullException(nameof(advantages)); + Spells = spells ?? throw new ArgumentNullException(nameof(spells)); + WeaponTalents = weaponTalents ?? throw new ArgumentNullException(nameof(weaponTalents)); + } + + public int Id { get; set; } + + public string Name { get; set; } + + public string Rasse { get; set; } + + public List Skills { get; set; } = new List(); + + public List Talents { get; set; } = new List(); + + public List Advantages { get; set; } = new List(); + + public List Spells { get; set; } = new List(); + + public List WeaponTalents { get; set; } = new List(); + + + public static void LoadChar(DSA_Game.Characters.Character file, out GroupChar group, out DatabaseChar data) + { + group = new GroupChar(); + data = new DatabaseChar(); + + group.Name = file.Name.Split(' ').First(); + group.Weapon = new Weapon(); + group.Lp = group.LpMax = file.Lebenspunkte_Basis; + group.As = group.AsMax = file.Astralpunkte_Basis; + group.Weapon = new Weapon(); + + data.Name = file.Name; + data.Advantages = file.Vorteile.Select(x => new Advantage(x.Name, x.Value)).ToList(); + data.Skills = file.Eigenschaften.Select(x => new Field(x.Key, x.Value)).ToList(); + data.Spells = file.Zauber.Select(x => new CharSpell(x.Representation, x.Value)).ToList(); + data.Talents = file.Talente.Select(x => new Field(x.Name, x.Value)).ToList(); + data.WeaponTalents = file.Kampftalente.Select(x => new WeaponTalent(x.Name, x.At, x.Pa)).ToList(); + } + } +} diff --git a/DSACore/Models/Database/DSA/Field.cs b/DSACore/Models/Database/DSA/Field.cs new file mode 100644 index 0000000..5022768 --- /dev/null +++ b/DSACore/Models/Database/DSA/Field.cs @@ -0,0 +1,16 @@ +using System; + +namespace DSACore.Models.Database.DSA +{ + public class Field + { + public Field(string name, int value = 0) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + this.Value = value; + } + + public string Name { get; set; } + public int Value { get; set; } + } +} diff --git a/DSACore/Models/Database/DSA/GeneralSpell.cs b/DSACore/Models/Database/DSA/GeneralSpell.cs new file mode 100644 index 0000000..74b95d7 --- /dev/null +++ b/DSACore/Models/Database/DSA/GeneralSpell.cs @@ -0,0 +1,20 @@ +namespace DSACore.Models.Database.DSA +{ + public class GeneralSpell : Talent + { + public char Comlexity = 'A'; + + public GeneralSpell(string name, string roll, char comlexity = 'A') :base(name, roll) + { + Comlexity = comlexity; + } + + public GeneralSpell(string name, string roll) : base(name, roll) + { + } + + public GeneralSpell() + { + } + } +} diff --git a/DSACore/Models/Database/DSA/GroupChar.cs b/DSACore/Models/Database/DSA/GroupChar.cs new file mode 100644 index 0000000..70b8fc1 --- /dev/null +++ b/DSACore/Models/Database/DSA/GroupChar.cs @@ -0,0 +1,13 @@ +namespace DSACore.Models.Database.DSA +{ + public class GroupChar + { + public string Name { get; set; } + public int Id { get; set; } + public int Lp { get; set; } + public int LpMax { get; set; } + public int As { get; set; } + public int AsMax { get; set; } + public Weapon Weapon { get; set; } + } +} diff --git a/DSACore/Models/Database/DSA/Inventory.cs b/DSACore/Models/Database/DSA/Inventory.cs new file mode 100644 index 0000000..69c7b08 --- /dev/null +++ b/DSACore/Models/Database/DSA/Inventory.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; + +namespace DSACore.Models.Database.DSA +{ + public class Inventory + { + public int Id { get; set; } + public Dictionary Items { get; set; } = new Dictionary(); + public Dictionary Food { get; set; } = new Dictionary(); + public List Weapons { get; set; } = new List(); + } +} diff --git a/DSACore/Models/Database/DSA/Talent.cs b/DSACore/Models/Database/DSA/Talent.cs new file mode 100644 index 0000000..a6de395 --- /dev/null +++ b/DSACore/Models/Database/DSA/Talent.cs @@ -0,0 +1,26 @@ +using System; + +namespace DSACore.Models.Database.DSA +{ + public class Talent + { + public Talent() + { + } + + public Talent(string name) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + } + + public Talent(string name, String roll) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + Roll = roll.Split('/'); + } + + public string Name { get; set; } + + public string[] Roll { get; set; } = new string[3]; + } +} diff --git a/DSACore/Models/Database/DSA/Weapon.cs b/DSACore/Models/Database/DSA/Weapon.cs new file mode 100644 index 0000000..24b334a --- /dev/null +++ b/DSACore/Models/Database/DSA/Weapon.cs @@ -0,0 +1,50 @@ +using System; + +namespace DSACore.Models.Database.DSA +{ + public class Weapon + { + public Weapon() + { + } + + public Weapon(string name, string damage, int weight, string weaponTalent, string price) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + Damage = damage ?? throw new ArgumentNullException(nameof(damage)); + Weight = weight; + WeaponTalent = weaponTalent ?? throw new ArgumentNullException(nameof(weaponTalent)); + Price = price; + } + + public string Name { get; set; } + public string Damage { get; set; } + public int Weight { get; set; } + public string WeaponTalent { get; set; } + public string Price { get; set; } + } + + public class MeleeWeapon : Weapon + { + public string TpKK { get; set; } + public int INI { get; set; } + public string MW { get; set; } + + public MeleeWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, damage, weight, weaponTalent, price) + { + } + } + + public class RangedWeapon : Weapon + { + public int AtMod { get; set; } + public int KKMod { get; set; } + public string AtReach { get; set; } + public string TpReach { get; set; } + public int LoadTime { get; set; } + + public RangedWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, damage, weight, weaponTalent, price) + { + } + } +} diff --git a/DSACore/Models/Database/DSA/WeaponTalent.cs b/DSACore/Models/Database/DSA/WeaponTalent.cs new file mode 100644 index 0000000..869cb35 --- /dev/null +++ b/DSACore/Models/Database/DSA/WeaponTalent.cs @@ -0,0 +1,18 @@ +using System; + +namespace DSACore.Models.Database.DSA +{ + public class WeaponTalent + { + public WeaponTalent(string name, int at, int pa) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + At = at; + Pa = pa; + } + + public string Name { get; set; } + public int At { get; set; } + public int Pa { get; set; } + } +} \ No newline at end of file diff --git a/DSACore/Models/Database/DatabaseChar.cs b/DSACore/Models/Database/DatabaseChar.cs deleted file mode 100644 index 9cd865f..0000000 --- a/DSACore/Models/Database/DatabaseChar.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSALib; - -namespace DSACore.Models.Database -{ - public class DatabaseChar - { - public DatabaseChar() - { - } - - public DatabaseChar(int id, string name, string rasse, List skills, List talents, List advantages, List spells, List weaponTalents) - { - Id = id; - Name = name ?? throw new ArgumentNullException(nameof(name)); - Rasse = rasse ?? throw new ArgumentNullException(nameof(rasse)); - Skills = skills ?? throw new ArgumentNullException(nameof(skills)); - Talents = talents ?? throw new ArgumentNullException(nameof(talents)); - Advantages = advantages ?? throw new ArgumentNullException(nameof(advantages)); - Spells = spells ?? throw new ArgumentNullException(nameof(spells)); - WeaponTalents = weaponTalents ?? throw new ArgumentNullException(nameof(weaponTalents)); - } - - public int Id { get; set; } - - public string Name { get; set; } - - public string Rasse { get; set; } - - public List Skills { get; set; } = new List(); - - public List Talents { get; set; } = new List(); - - public List Advantages { get; set; } = new List(); - - public List Spells { get; set; } = new List(); - - public List WeaponTalents { get; set; } = new List(); - - - public static void LoadChar(DSA_Game.Characters.Character file, out GroupChar group, out DatabaseChar data) - { - group = new GroupChar(); - data = new DatabaseChar(); - - group.Name = file.Name.Split(' ').First(); - group.Weapon = new Weapon(); - group.Lp = group.LpMax = file.Lebenspunkte_Basis; - group.As = group.AsMax = file.Astralpunkte_Basis; - group.Weapon = new Weapon(); - - data.Name = file.Name; - data.Advantages = file.Vorteile.Select(x => new Advantage(x.Name, x.Value)).ToList(); - data.Skills = file.Eigenschaften.Select(x => new Field(x.Key, x.Value)).ToList(); - data.Spells = file.Zauber.Select(x => new CharSpell(x.Representation, x.Value)).ToList(); - data.Talents = file.Talente.Select(x => new Field(x.Name, x.Value)).ToList(); - data.WeaponTalents = file.Kampftalente.Select(x => new WeaponTalent(x.Name, x.At, x.Pa)).ToList(); - } - } -} diff --git a/DSACore/Models/Database/Field.cs b/DSACore/Models/Database/Field.cs deleted file mode 100644 index b14d9da..0000000 --- a/DSACore/Models/Database/Field.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class Field - { - public Field(string name, int value = 0) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - this.Value = value; - } - - public string Name { get; set; } - public int Value { get; set; } - } -} diff --git a/DSACore/Models/Database/GeneralSpell.cs b/DSACore/Models/Database/GeneralSpell.cs deleted file mode 100644 index f53081e..0000000 --- a/DSACore/Models/Database/GeneralSpell.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class GeneralSpell : Talent - { - public char Comlexity = 'A'; - - public GeneralSpell(string name, string roll, char comlexity = 'A') :base(name, roll) - { - Comlexity = comlexity; - } - - public GeneralSpell(string name, string roll) : base(name, roll) - { - } - - public GeneralSpell() - { - } - } -} diff --git a/DSACore/Models/Database/Group.cs b/DSACore/Models/Database/Group.cs deleted file mode 100644 index a7bb929..0000000 --- a/DSACore/Models/Database/Group.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class Group - { - public string Name { get; set; } - public string Discord { get; set; } - public string Password { get; set; } - public int Id { get; set; } - public List Chars { get; set; }= new List(); - - } - - -} diff --git a/DSACore/Models/Database/GroupChar.cs b/DSACore/Models/Database/GroupChar.cs deleted file mode 100644 index 1dfc4ea..0000000 --- a/DSACore/Models/Database/GroupChar.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class GroupChar - { - public string Name { get; set; } - public int Id { get; set; } - public int Lp { get; set; } - public int LpMax { get; set; } - public int As { get; set; } - public int AsMax { get; set; } - public Weapon Weapon { get; set; } - } -} diff --git a/DSACore/Models/Database/Groups/DSAGroup.cs b/DSACore/Models/Database/Groups/DSAGroup.cs new file mode 100644 index 0000000..8f20278 --- /dev/null +++ b/DSACore/Models/Database/Groups/DSAGroup.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using DSACore.Models.Database.DSA; + +namespace DSACore.Models.Database.Groups +{ + public class DSAGroup : Group + { + public List Chars { get; set; }= new List(); + } +} \ No newline at end of file diff --git a/DSACore/Models/Database/Groups/Group.cs b/DSACore/Models/Database/Groups/Group.cs new file mode 100644 index 0000000..23e5f68 --- /dev/null +++ b/DSACore/Models/Database/Groups/Group.cs @@ -0,0 +1,13 @@ +namespace DSACore.Models.Database.Groups +{ + public class Group + { + public string Name { get; set; } + public string Discord { get; set; } + public string Password { get; set; } + public int Id { get; set; } + + } + + +} diff --git a/DSACore/Models/Database/Inventory.cs b/DSACore/Models/Database/Inventory.cs deleted file mode 100644 index e6b47ec..0000000 --- a/DSACore/Models/Database/Inventory.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class Inventory - { - public int Id { get; set; } - public Dictionary Items { get; set; } = new Dictionary(); - public Dictionary Food { get; set; } = new Dictionary(); - public List Weapons { get; set; } = new List(); - } -} diff --git a/DSACore/Models/Database/Talent.cs b/DSACore/Models/Database/Talent.cs deleted file mode 100644 index aca65a4..0000000 --- a/DSACore/Models/Database/Talent.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class Talent - { - public Talent() - { - } - - public Talent(string name) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - } - - public Talent(string name, String roll) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - Roll = roll.Split('/'); - } - - public string Name { get; set; } - - public string[] Roll { get; set; } = new string[3]; - } -} diff --git a/DSACore/Models/Database/Weapon.cs b/DSACore/Models/Database/Weapon.cs deleted file mode 100644 index b2f8a1e..0000000 --- a/DSACore/Models/Database/Weapon.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace DSACore.Models.Database -{ - public class Weapon - { - public Weapon() - { - } - - public Weapon(string name, string damage, int weight, string weaponTalent, string price) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - Damage = damage ?? throw new ArgumentNullException(nameof(damage)); - Weight = weight; - WeaponTalent = weaponTalent ?? throw new ArgumentNullException(nameof(weaponTalent)); - Price = price; - } - - public string Name { get; set; } - public string Damage { get; set; } - public int Weight { get; set; } - public string WeaponTalent { get; set; } - public string Price { get; set; } - } - - public class MeleeWeapon : Weapon - { - public string TpKK { get; set; } - public int INI { get; set; } - public string MW { get; set; } - - public MeleeWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, damage, weight, weaponTalent, price) - { - } - } - - public class RangedWeapon : Weapon - { - public int AtMod { get; set; } - public int KKMod { get; set; } - public string AtReach { get; set; } - public string TpReach { get; set; } - public int LoadTime { get; set; } - - public RangedWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, damage, weight, weaponTalent, price) - { - } - } -} diff --git a/DSACore/Models/Database/WeaponTalent.cs b/DSACore/Models/Database/WeaponTalent.cs deleted file mode 100644 index 4b98d24..0000000 --- a/DSACore/Models/Database/WeaponTalent.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace DSACore.Models.Database -{ - public class WeaponTalent - { - public WeaponTalent(string name, int at, int pa) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - At = at; - Pa = pa; - } - - public string Name { get; set; } - public int At { get; set; } - public int Pa { get; set; } - } -} \ No newline at end of file diff --git a/DSACore/Models/Network/Token.cs b/DSACore/Models/Network/Token.cs new file mode 100644 index 0000000..0021317 --- /dev/null +++ b/DSACore/Models/Network/Token.cs @@ -0,0 +1,21 @@ +using System; +using Microsoft.EntityFrameworkCore; + +namespace DSACore.Models.Network +{ + public class Token + { + public string Group { get; set; } + private DateTime creation = DateTime.Now; + + public Token(string @group) + { + Group = @group; + } + + public bool IsValid() + { + return DateTime.Now - creation < TimeSpan.FromMinutes(1); + } + } +} \ No newline at end of file diff --git a/DSACore/Startup.cs b/DSACore/Startup.cs index f8f6dfd..1dcc690 100644 --- a/DSACore/Startup.cs +++ b/DSACore/Startup.cs @@ -62,7 +62,7 @@ namespace DSACore app.UseCors("CorsPolicy"); - app.UseSignalR(routes => { routes.MapHub("/chatHub"); }); + app.UseSignalR(routes => { routes.MapHub("/login"); }); app.UseWebSockets(); diff --git a/WebInterface/NodeJSServer/src/js/modules/ui/components/modal/modal.js b/WebInterface/NodeJSServer/src/js/modules/ui/components/modal/modal.js index 10a1be5..c4c5119 100644 --- a/WebInterface/NodeJSServer/src/js/modules/ui/components/modal/modal.js +++ b/WebInterface/NodeJSServer/src/js/modules/ui/components/modal/modal.js @@ -17,7 +17,6 @@ export default class Modal { modal.className = 'modal'; title.className = 'modal-title'; body.className = 'modal-body'; - title.textContent = titleString; modal.appendChild(title); -- cgit v1.2.3-70-g09d2 From aad1d69b5e2bb0c82f657f7693462fd95a91fb9f Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Thu, 16 May 2019 01:34:10 +0200 Subject: ifx typo in api url --- WebInterface/NodeJSServer/src/js/index.js | 2 +- WebInterface/NodeJSServer/src/js/play.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/WebInterface/NodeJSServer/src/js/index.js b/WebInterface/NodeJSServer/src/js/index.js index 249adc9..c8b5ca8 100644 --- a/WebInterface/NodeJSServer/src/js/index.js +++ b/WebInterface/NodeJSServer/src/js/index.js @@ -2,7 +2,7 @@ import Interface from './modules/interface'; import UIManager from './modules/ui/uiManager'; import Networker from './modules/networking/networker'; -const SERVERURL = 'https://kobert.dev/api/Login'; +const SERVERURL = 'https://kobert.dev/api/login'; let iface = new Interface(); let uiMan = new UIManager(iface); diff --git a/WebInterface/NodeJSServer/src/js/play.js b/WebInterface/NodeJSServer/src/js/play.js index 2d4effe..93508b3 100644 --- a/WebInterface/NodeJSServer/src/js/play.js +++ b/WebInterface/NodeJSServer/src/js/play.js @@ -2,7 +2,7 @@ import Interface from './modules/interface'; import UIManager from './modules/ui/uiManager'; import Networker from './modules/networking/networker'; -const SERVERURL = 'https://kobert.dev/api/Login'; +const SERVERURL = 'https://kobert.dev/api/login'; let iface = new Interface(); let uiMan = new UIManager(iface); -- cgit v1.2.3-70-g09d2 From 921d023a7652be5b1232ac41aeb2646b5f83ceb5 Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Fri, 17 May 2019 20:59:10 +0200 Subject: Add WebSocket server functionality and a WebSocket javascript test suite --- game_server/build.sh | 6 ++-- game_server/src/gameserver.rs | 44 +++++++++++++++++++++++++++++ game_server/src/main.rs | 14 +++++++--- game_server/src/ws_test.html | 65 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 game_server/src/ws_test.html diff --git a/game_server/build.sh b/game_server/build.sh index 5929e29..1eb61a1 100755 --- a/game_server/build.sh +++ b/game_server/build.sh @@ -2,9 +2,9 @@ case $1 in ("") - if rustup run nightly cargo --color always build; then + if rustup run stable cargo --color always build; then echo build success! - RUST_LOG=info target/debug/game-server + RUST_LOG=debug target/debug/game-server else echo build failed! fi @@ -13,7 +13,7 @@ case $1 in sh build.sh &> err && cat err | tac ;; -c) - rustup run nightly cargo clean + rustup run stable cargo clean ;; *) echo invalid argument diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs index e69de29..6bc3e07 100644 --- a/game_server/src/gameserver.rs +++ b/game_server/src/gameserver.rs @@ -0,0 +1,44 @@ +use websocket::{OwnedMessage, sync::Server, server::NoTlsAcceptor}; +use std::net::{SocketAddr, ToSocketAddrs}; +use std::sync::mpsc; +use std::sync::mpsc::{Sender, Receiver}; + +#[derive(Debug)] +pub enum GameServerError { + BindError(std::io::Error), +} + +type ClientConnection = Result<(), GameServerError>; + +pub struct GameServer { + addr: SocketAddr, + rec: Receiver, +} + +impl GameServer { + pub fn new(addr: T) -> Self { + let (s, r): (Sender, Receiver) + = mpsc::channel(); + let addr = addr.to_socket_addrs().unwrap().next().unwrap(); + debug!("ws address: {}", addr); + std::thread::spawn(move || { + let server = match Server::::bind(addr) { + Ok(v) => v, + Err(e) => { + s.send(Err(GameServerError::BindError(e))).unwrap(); + return; + }, + }; + info!("webserver is being launched"); + for req in server { + //println!("{:?}", req); + println!("gotcha"); + } + info!("webserver is being shut down"); + }); + GameServer { + addr, + rec: r, + } + } +} diff --git a/game_server/src/main.rs b/game_server/src/main.rs index f7a1085..2d261d8 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -1,27 +1,33 @@ mod group; mod test_group; mod lobby; +mod gameserver; mod backend_connection; #[macro_use] extern crate log; use pretty_env_logger; -use test_group::TestGroup; use lobby::Lobby; use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); + info!("create lobby"); let mut lobby = Lobby::new(); + let addr = ("127.0.0.1", 5001); + info!("create game server on {:?}", addr); + let gameserver = gameserver::GameServer::new(addr); for group in lobby.iter() { group.run() } - let mut backend = BackendConnection::new("http://129.13.215.68:5000"); + let mut backend = BackendConnection::new("https://kobert.dev"); loop { - backend.request("/scribble").unwrap(); - println!("{:?}", backend.get_response()); + std::thread::sleep(std::time::Duration::from_millis(1000)); + + //backend.request("/api/lobby/tokens/1230").unwrap(); + //println!("{:?}", backend.get_response()); } } diff --git a/game_server/src/ws_test.html b/game_server/src/ws_test.html new file mode 100644 index 0000000..29d4d50 --- /dev/null +++ b/game_server/src/ws_test.html @@ -0,0 +1,65 @@ + + + + WS Test + + + +
connected

+
+ Server address: +
+ + + -- cgit v1.2.3-70-g09d2 From 4127395e019f5097786e477308f1cc66793a784d Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sat, 18 May 2019 04:51:16 +0200 Subject: Add custom http errors to tokens api --- DSACore/Controllers/TokensController.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/DSACore/Controllers/TokensController.cs b/DSACore/Controllers/TokensController.cs index 453d477..1d49f44 100644 --- a/DSACore/Controllers/TokensController.cs +++ b/DSACore/Controllers/TokensController.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.CodeAnalysis.CSharp.Syntax; namespace DSACore.Controllers { @@ -13,16 +9,20 @@ namespace DSACore.Controllers // GET [HttpGet("{token}")] - public async Task> Get(int token) + public ActionResult Get(string token) { + if (!int.TryParse(token, out var inttoken)) + { + return BadRequest("The token has to be a 32 bit unsigned integer"); + } - if (!Hubs.Users.Tokens.Exists(x => x.GetHashCode() == token)) + if (!Hubs.Users.Tokens.Exists(x => x.GetHashCode() == inttoken)) { return NotFound(); } - var group = Hubs.Users.Tokens.Find(x => x.GetHashCode() == token); + var group = Hubs.Users.Tokens.Find(x => x.GetHashCode() == inttoken); return Ok(group); } } -} \ No newline at end of file +} -- cgit v1.2.3-70-g09d2 From 70f46161fe0c9819d463cf612d60d4c03faabe7e Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Sat, 18 May 2019 05:27:06 +0200 Subject: Add threading and possibility to connect to socket --- game_server/Cargo.toml | 1 + game_server/src/gameserver.rs | 148 +++++++++++++++++++++++++++++++++++------- game_server/src/main.rs | 17 +---- game_server/src/ws_test.html | 5 +- 4 files changed, 131 insertions(+), 40 deletions(-) diff --git a/game_server/Cargo.toml b/game_server/Cargo.toml index baf27fa..97c0e77 100644 --- a/game_server/Cargo.toml +++ b/game_server/Cargo.toml @@ -10,3 +10,4 @@ log = "0.4" pretty_env_logger = "0.3" reqwest = "0.9" websocket = "0.22" +hyper = "0.10" diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs index 6bc3e07..377654e 100644 --- a/game_server/src/gameserver.rs +++ b/game_server/src/gameserver.rs @@ -1,44 +1,146 @@ -use websocket::{OwnedMessage, sync::Server, server::NoTlsAcceptor}; -use std::net::{SocketAddr, ToSocketAddrs}; +use websocket::{OwnedMessage, + sync::Server, + client::sync::Client, + server::{NoTlsAcceptor, InvalidConnection, + sync::AcceptResult}}; +use std::net::{SocketAddr, ToSocketAddrs, TcpStream}; use std::sync::mpsc; use std::sync::mpsc::{Sender, Receiver}; +use super::lobby::Lobby; +use super::backend_connection::BackendConnection; + +const PROTOCOL: &str = "tuesday"; + +type Token = u32; #[derive(Debug)] pub enum GameServerError { BindError(std::io::Error), + HandshakeRequestError, + InvalidProtocolError, + AcceptError(std::io::Error) } -type ClientConnection = Result<(), GameServerError>; - pub struct GameServer { addr: SocketAddr, - rec: Receiver, + lobby: Lobby, + backend: BackendConnection, +} + +pub struct GameClient { + addr: SocketAddr, + client: Client, +} + +impl GameClient { + fn from_raw(client: Client) -> Result { + let addr = client.peer_addr().map_err(|_| ())?; + info!("got a client connection from: {}", addr); + Ok(GameClient { + addr, + client, + }) + } + + fn require_token(&mut self) -> Option { + let message = self.client + .recv_message() + .ok()?; + if let OwnedMessage::Text(text) = message { + text.parse::().ok() + } else { + None + } + } } +type ClientConnection = Result; + impl GameServer { pub fn new(addr: T) -> Self { - let (s, r): (Sender, Receiver) - = mpsc::channel(); let addr = addr.to_socket_addrs().unwrap().next().unwrap(); debug!("ws address: {}", addr); - std::thread::spawn(move || { - let server = match Server::::bind(addr) { - Ok(v) => v, - Err(e) => { - s.send(Err(GameServerError::BindError(e))).unwrap(); - return; - }, - }; - info!("webserver is being launched"); - for req in server { - //println!("{:?}", req); - println!("gotcha"); - } - info!("webserver is being shut down"); - }); + info!("create lobby"); + let lobby = Lobby::new(); + let backend = BackendConnection::new("https://kobert.dev"); + info!("got a C# backend connection"); GameServer { addr, - rec: r, + lobby, + backend, + } + } + + pub fn run(&self) -> Result<(), GameServerError> { + let reader = self.read_clients(); + loop { + let mut connection = reader.recv().unwrap()?; + self.add_client(connection); + } + Ok(()) + } + + fn add_client(&self, mut client: GameClient) { + std::thread::spawn(move || { + println!("Token: {:?}", client.require_token()); + }); + } + + fn read_clients(&self) -> Receiver { + let (s, r): (Sender, Receiver) + = mpsc::channel(); + let addr = self.addr; + std::thread::spawn(move || { + let result = Self::handle_requests(addr, &s).or_else(|e| s.send(Err(e))); + }); + r + } + + fn handle_requests(addr: SocketAddr, s: &Sender) -> Result<(), GameServerError> { + let server = match Server::::bind(addr) { + Ok(v) => v, + Err(e) => { + error!("websocket binding error"); + Err(GameServerError::BindError(e))? + }, + }; + info!("webserver is being launched"); + for req in server { + s.send(Ok(Self::handle_request(req)?)).unwrap(); + } + info!("webserver is being shut down"); + Ok(()) + } + + fn handle_request(req: AcceptResult) -> ClientConnection { + match req { + Ok(req) => { + if !req.protocols().contains(&PROTOCOL.to_string()) { + warn!("a client tried to connect without {} protocol", PROTOCOL); + req.reject().unwrap(); + Err(GameServerError::InvalidProtocolError) + } else { + match req.use_protocol(PROTOCOL).accept() { + Ok(client) => { + match GameClient::from_raw(client) { + Ok(client) => Ok(client), + Err(_) => { + error!("could not create a client"); + Err(GameServerError::HandshakeRequestError) + } + } + }, + Err((_, e)) => { + warn!("client handshake failed"); + Err(GameServerError::AcceptError(e)) + } + } + } + }, + Err(e) => { + warn!("invalid client request"); + Err(GameServerError::HandshakeRequestError) + } } } } diff --git a/game_server/src/main.rs b/game_server/src/main.rs index 2d261d8..d8a7b53 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -7,27 +7,14 @@ mod backend_connection; #[macro_use] extern crate log; use pretty_env_logger; -use lobby::Lobby; use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); - info!("create lobby"); - let mut lobby = Lobby::new(); - let addr = ("127.0.0.1", 5001); + let addr = ("0.0.0.0", 5001); info!("create game server on {:?}", addr); let gameserver = gameserver::GameServer::new(addr); + gameserver.run().unwrap(); - for group in lobby.iter() { - group.run() - } - - let mut backend = BackendConnection::new("https://kobert.dev"); - loop { - std::thread::sleep(std::time::Duration::from_millis(1000)); - - //backend.request("/api/lobby/tokens/1230").unwrap(); - //println!("{:?}", backend.get_response()); - } } diff --git a/game_server/src/ws_test.html b/game_server/src/ws_test.html index 29d4d50..ea259b7 100644 --- a/game_server/src/ws_test.html +++ b/game_server/src/ws_test.html @@ -22,10 +22,11 @@ function get_addr() { function test_connection() { let a = 'ws://' + get_addr(); add_text('create a new connection at "' + a + '"'); - const ws = new WebSocket(a); + const ws = new WebSocket(a, 'tuesday'); ws.addEventListener('open', function (event) { add_text('connection established'); toggle_connected(true); + ws.send('1230123'); }); ws.addEventListener('error', function (event) { add_text('ws error occured: "' + event + '"'); @@ -36,7 +37,7 @@ function test_connection() { toggle_connected(false); }); ws.addEventListener('message', function (event) { - add_text('got ws message: ' + event); + add_text('got ws message: ' + event.data); }); } -- cgit v1.2.3-70-g09d2 From f3983341be939235c1a6cd522b3bb5cc318a6d1a Mon Sep 17 00:00:00 2001 From: natrixaeria Date: Sat, 18 May 2019 05:52:08 +0200 Subject: Keep client connections open and start the server on localhost --- game_server/src/gameserver.rs | 1 + game_server/src/main.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/game_server/src/gameserver.rs b/game_server/src/gameserver.rs index 377654e..9334a27 100644 --- a/game_server/src/gameserver.rs +++ b/game_server/src/gameserver.rs @@ -83,6 +83,7 @@ impl GameServer { fn add_client(&self, mut client: GameClient) { std::thread::spawn(move || { println!("Token: {:?}", client.require_token()); + loop { std::thread::sleep(std::time::Duration::from_millis(100)); } }); } diff --git a/game_server/src/main.rs b/game_server/src/main.rs index d8a7b53..e129283 100644 --- a/game_server/src/main.rs +++ b/game_server/src/main.rs @@ -12,7 +12,7 @@ use backend_connection::BackendConnection; fn main() { pretty_env_logger::init(); - let addr = ("0.0.0.0", 5001); + let addr = ("127.0.0.1", 5001); info!("create game server on {:?}", addr); let gameserver = gameserver::GameServer::new(addr); gameserver.run().unwrap(); -- cgit v1.2.3-70-g09d2 From f89f308c525e9deebc6d2cf6416e27dfe1a299dc Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 19 May 2019 16:03:38 +0200 Subject: Cleanup DiscoBot Project --- DSACore/Audio/Sound.cs | 8 +- DSACore/Auxiliary/Calculator/Argument.cs | 17 +- DSACore/Auxiliary/Calculator/ISolvable.cs | 2 +- DSACore/Auxiliary/Calculator/Operator.cs | 16 +- DSACore/Auxiliary/Calculator/Ops.cs | 2 +- DSACore/Auxiliary/Calculator/StringSolver.cs | 90 +++--- DSACore/Auxiliary/CommandInfo.cs | 12 +- DSACore/Auxiliary/Dice.cs | 23 +- DSACore/Auxiliary/Extensions.cs | 18 +- DSACore/Auxiliary/RandomMisc.cs | 32 +-- DSACore/Auxiliary/SpellCorrect.cs | 103 +++---- DSACore/Auxiliary/TalentEnumerableExtension.cs | 39 +-- DSACore/Auxiliary/WeaponImporter.cs | 53 ++-- DSACore/Commands/CommandHandler.cs | 21 +- DSACore/Commands/CommandTypes.cs | 2 +- DSACore/Commands/FileHandler.cs | 25 +- DSACore/Commands/Gm.cs | 2 +- DSACore/Commands/HeldList.cs | 72 ++--- DSACore/Commands/Help.cs | 29 +- DSACore/Commands/LebenUndAstral.cs | 52 ++-- DSACore/Commands/List.cs | 6 +- DSACore/Commands/MiscCommands.cs | 2 +- DSACore/Commands/NpcCommands.cs | 14 +- DSACore/Commands/ProbenTest.cs | 4 +- DSACore/Controllers/CommandsController.cs | 5 +- DSACore/Controllers/LobbyController.cs | 8 +- DSACore/Controllers/TokensController.cs | 10 +- DSACore/DSA_Game/Characters/Character.cs | 176 ++++++------ DSACore/DSA_Game/Characters/NPC.cs | 80 ++---- DSACore/DSA_Game/Characters/SaveChar.cs | 3 +- DSACore/DSA_Game/Dsa.cs | 18 +- DSACore/DSA_Game/Save/Properties.cs | 17 +- DSACore/DSA_Game/Save/SaveCommand.cs | 22 +- DSACore/DSA_Game/Save/Session.cs | 21 +- DSACore/FireBase/Database.cs | 39 ++- DSACore/Hubs/Login.cs | 71 ++--- DSACore/Models/Database/DSA/Advantage.cs | 2 +- DSACore/Models/Database/DSA/CharSpell.cs | 2 +- DSACore/Models/Database/DSA/DatabaseChar.cs | 5 +- DSACore/Models/Database/DSA/Field.cs | 4 +- DSACore/Models/Database/DSA/GeneralSpell.cs | 4 +- DSACore/Models/Database/DSA/GroupChar.cs | 2 +- DSACore/Models/Database/DSA/Inventory.cs | 2 +- DSACore/Models/Database/DSA/Talent.cs | 4 +- DSACore/Models/Database/DSA/Weapon.cs | 8 +- DSACore/Models/Database/DSA/WeaponTalent.cs | 2 +- DSACore/Models/Database/Groups/DSAGroup.cs | 2 +- DSACore/Models/Database/Groups/Group.cs | 5 +- DSACore/Models/Network/Command.cs | 4 +- DSACore/Models/Network/CommandResponse.cs | 6 +- DSACore/Models/Network/Group.cs | 10 +- DSACore/Models/Network/User.cs | 2 +- DSACore/Program.cs | 9 +- DSACore/Startup.cs | 10 +- DSALib/Characters/Being.cs | 2 +- DSALib/Characters/Critter.cs | 30 +- DSALib/Characters/Entity.cs | 4 +- DSALib/Characters/ICharacter.cs | 2 +- DSALib/Characters/ICombatant.cs | 4 +- DSALib/CritterAttack.cs | 10 +- DSALib/KampfTalent.cs | 8 +- DSALib/Talent.cs | 19 +- DSALib/Vorteil.cs | 8 +- DSALib/Zauber.cs | 6 +- DiscoBot/Audio/AudioModule.cs | 28 +- DiscoBot/Audio/AudioService.cs | 70 +++-- DiscoBot/Audio/Sound.cs | 16 +- DiscoBot/Audio/Soundeffects.cs | 93 ------- DiscoBot/Audio/Voice.cs | 69 ++--- DiscoBot/Auxiliary/Calculator/Argument.cs | 38 --- DiscoBot/Auxiliary/Calculator/ISolvable.cs | 10 - DiscoBot/Auxiliary/Calculator/Operator.cs | 50 ---- DiscoBot/Auxiliary/Calculator/Ops.cs | 13 - DiscoBot/Auxiliary/Calculator/StringSolver.cs | 207 -------------- DiscoBot/Auxiliary/CommandExtension.cs | 98 +++++++ DiscoBot/Auxiliary/CommandInfo.cs | 32 --- DiscoBot/Auxiliary/Dice.cs | 37 +-- DiscoBot/Auxiliary/Extensions.cs | 33 --- DiscoBot/Auxiliary/Permissions.cs | 32 +++ DiscoBot/Auxiliary/RandomMisc.cs | 44 +-- DiscoBot/Auxiliary/SpellCorrect.cs | 120 +++----- DiscoBot/Auxiliary/TalentEnumerableExtension.cs | 102 ------- DiscoBot/Commands/CommandTypes.cs | 13 - DiscoBot/Commands/FileHandler.cs | 38 +-- DiscoBot/Commands/Gm.cs | 187 ------------- DiscoBot/Commands/HeldList.cs | 191 ------------- DiscoBot/Commands/Help.cs | 99 ------- DiscoBot/Commands/LebenUndAstral.cs | 198 ------------- DiscoBot/Commands/List.cs | 62 ----- DiscoBot/Commands/MiscCommands.cs | 206 +++++--------- DiscoBot/Commands/NpcCommands.cs | 39 --- DiscoBot/Commands/ProbenTest.cs | 91 ------ DiscoBot/DSA_Game/Characters/Character.cs | 303 -------------------- DiscoBot/DSA_Game/Characters/NPC.cs | 112 -------- DiscoBot/DSA_Game/Characters/SaveChar.cs | 45 --- DiscoBot/DSA_Game/Dsa.cs | 72 ----- DiscoBot/DSA_Game/Save/Properties.cs | 88 ------ DiscoBot/DSA_Game/Save/SaveCommand.cs | 82 ------ DiscoBot/DSA_Game/Save/Session.cs | 60 ---- DiscoBot/DiscoBot.csproj | 31 +-- DiscoBot/Program.cs | 100 +++---- DiscoBot/Properties/AssemblyInfo.cs | 3 +- DiscoBot/ToRework/CommandExtension.cs | 119 -------- DiscoBot/ToRework/Permissions.cs | 43 --- FireBase/ExceptionEventArgs.cs | 4 +- FireBase/Extensions/ObservableExtensions.cs | 28 +- FireBase/Extensions/TaskExtensions.cs | 2 +- FireBase/FirebaseClient.cs | 18 +- FireBase/FirebaseException.cs | 44 ++- FireBase/FirebaseKeyGenerator.cs | 34 +-- FireBase/FirebaseObject.cs | 18 +- FireBase/FirebaseOptions.cs | 50 +--- FireBase/Http/HttpClientExtensions.cs | 23 +- FireBase/Http/PostResult.cs | 8 +- FireBase/ObservableExtensions.cs | 10 +- FireBase/Offline/ConcurrentOfflineDatabase.cs | 70 ++--- FireBase/Offline/DatabaseExtensions.cs | 77 +++-- FireBase/Offline/ISetHandler.cs | 5 +- FireBase/Offline/InitialPullStrategy.cs | 4 +- FireBase/Offline/Internals/MemberAccessVisitor.cs | 19 +- FireBase/Offline/OfflineCacheAdapter.cs | 69 ++--- FireBase/Offline/OfflineDatabase.cs | 71 +++-- FireBase/Offline/OfflineEntry.cs | 60 ++-- FireBase/Offline/RealtimeDatabase.cs | 324 +++++++++++----------- FireBase/Offline/SetHandler.cs | 9 +- FireBase/Offline/StreamingOptions.cs | 2 +- FireBase/Offline/SyncOptions.cs | 2 +- FireBase/Query/AuthQuery.cs | 7 +- FireBase/Query/ChildQuery.cs | 16 +- FireBase/Query/FilterQuery.cs | 36 +-- FireBase/Query/FirebaseQuery.cs | 82 +++--- FireBase/Query/IFirebaseQuery.cs | 13 +- FireBase/Query/OrderQuery.cs | 4 +- FireBase/Query/ParameterQuery.cs | 6 +- FireBase/Query/QueryExtensions.cs | 25 +- FireBase/Query/QueryFactoryExtensions.cs | 6 +- FireBase/Query/SilentQuery.cs | 4 +- FireBase/Streaming/FirebaseCache.cs | 58 ++-- FireBase/Streaming/FirebaseEvent.cs | 19 +- FireBase/Streaming/FirebaseEventSource.cs | 2 +- FireBase/Streaming/FirebaseEventType.cs | 2 +- FireBase/Streaming/FirebaseServerEventType.cs | 2 +- FireBase/Streaming/FirebaseSubscription.cs | 76 +++-- FireBase/Streaming/NonBlockingStreamReader.cs | 22 +- ZooBOTanica/CritCreate.cs | 84 +++--- ZooBOTanica/Program.cs | 6 +- ZooBOTanica/Properties/AssemblyInfo.cs | 2 +- 147 files changed, 1574 insertions(+), 4413 deletions(-) delete mode 100644 DiscoBot/Audio/Soundeffects.cs delete mode 100644 DiscoBot/Auxiliary/Calculator/Argument.cs delete mode 100644 DiscoBot/Auxiliary/Calculator/ISolvable.cs delete mode 100644 DiscoBot/Auxiliary/Calculator/Operator.cs delete mode 100644 DiscoBot/Auxiliary/Calculator/Ops.cs delete mode 100644 DiscoBot/Auxiliary/Calculator/StringSolver.cs create mode 100644 DiscoBot/Auxiliary/CommandExtension.cs delete mode 100644 DiscoBot/Auxiliary/CommandInfo.cs delete mode 100644 DiscoBot/Auxiliary/Extensions.cs create mode 100644 DiscoBot/Auxiliary/Permissions.cs delete mode 100644 DiscoBot/Auxiliary/TalentEnumerableExtension.cs delete mode 100644 DiscoBot/Commands/CommandTypes.cs delete mode 100644 DiscoBot/Commands/Gm.cs delete mode 100644 DiscoBot/Commands/HeldList.cs delete mode 100644 DiscoBot/Commands/Help.cs delete mode 100644 DiscoBot/Commands/LebenUndAstral.cs delete mode 100644 DiscoBot/Commands/List.cs delete mode 100644 DiscoBot/Commands/NpcCommands.cs delete mode 100644 DiscoBot/Commands/ProbenTest.cs delete mode 100644 DiscoBot/DSA_Game/Characters/Character.cs delete mode 100644 DiscoBot/DSA_Game/Characters/NPC.cs delete mode 100644 DiscoBot/DSA_Game/Characters/SaveChar.cs delete mode 100644 DiscoBot/DSA_Game/Dsa.cs delete mode 100644 DiscoBot/DSA_Game/Save/Properties.cs delete mode 100644 DiscoBot/DSA_Game/Save/SaveCommand.cs delete mode 100644 DiscoBot/DSA_Game/Save/Session.cs delete mode 100644 DiscoBot/ToRework/CommandExtension.cs delete mode 100644 DiscoBot/ToRework/Permissions.cs diff --git a/DSACore/Audio/Sound.cs b/DSACore/Audio/Sound.cs index d259850..aee3060 100644 --- a/DSACore/Audio/Sound.cs +++ b/DSACore/Audio/Sound.cs @@ -4,9 +4,9 @@ { public Sound(string name, string url, int volume) { - this.Name = name; - this.Url = url; - this.Volume = volume; + Name = name; + Url = url; + Volume = volume; } public string Name { get; } @@ -15,4 +15,4 @@ public int Volume { get; } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/Calculator/Argument.cs b/DSACore/Auxiliary/Calculator/Argument.cs index 52f33a9..14982aa 100644 --- a/DSACore/Auxiliary/Calculator/Argument.cs +++ b/DSACore/Auxiliary/Calculator/Argument.cs @@ -1,7 +1,7 @@ namespace DSACore.Auxiliary.Calculator { using System; - + /// /// Provides an ISolvable class to save numbers. The class handles Argument checking and conversion from string to int. /// @@ -12,27 +12,24 @@ public Argument(string value) { // check whether the value given is an empty string - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentException("Argument kann nicht mit einem leeren string instanziert werden. ", nameof(value)); - } + if (string.IsNullOrEmpty(value)) + throw new ArgumentException("Argument kann nicht mit einem leeren string instanziert werden. ", + nameof(value)); - if (!int.TryParse(value, out int result)) - { + if (!int.TryParse(value, out var result)) throw new ArgumentException($"Kann {value} nicht in Integer konvertieren"); - } this.value = result; } public int Solve() { - return this.value; + return value; } public override string ToString() { - return this.value.ToString(); + return value.ToString(); } } } \ No newline at end of file diff --git a/DSACore/Auxiliary/Calculator/ISolvable.cs b/DSACore/Auxiliary/Calculator/ISolvable.cs index 1f571d0..2acbd11 100644 --- a/DSACore/Auxiliary/Calculator/ISolvable.cs +++ b/DSACore/Auxiliary/Calculator/ISolvable.cs @@ -7,4 +7,4 @@ { int Solve(); } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/Calculator/Operator.cs b/DSACore/Auxiliary/Calculator/Operator.cs index 440e21e..ed46186 100644 --- a/DSACore/Auxiliary/Calculator/Operator.cs +++ b/DSACore/Auxiliary/Calculator/Operator.cs @@ -14,7 +14,7 @@ namespace DSACore.Auxiliary.Calculator { this.arg1 = arg1; this.arg2 = arg2; - this.OperatorType = operatorType; + OperatorType = operatorType; } public Ops OperatorType { get; set; } @@ -22,19 +22,19 @@ namespace DSACore.Auxiliary.Calculator public int Solve() { int result; - switch (this.OperatorType) + switch (OperatorType) { case Ops.Dice: - result = Dice.Roll(this.arg1.Solve(), this.arg2.Solve()); + result = Dice.Roll(arg1.Solve(), arg2.Solve()); break; case Ops.Multiply: - result = this.arg1.Solve() * this.arg2.Solve(); + result = arg1.Solve() * arg2.Solve(); break; case Ops.Add: - result = this.arg1.Solve() + this.arg2.Solve(); + result = arg1.Solve() + arg2.Solve(); break; case Ops.Subtract: - result = this.arg1.Solve() - this.arg2.Solve(); + result = arg1.Solve() - arg2.Solve(); break; default: throw new ArgumentOutOfRangeException(); @@ -45,7 +45,7 @@ namespace DSACore.Auxiliary.Calculator public override string ToString() { - return $"({this.arg1} {this.OperatorType} {this.arg2})"; + return $"({arg1} {OperatorType} {arg2})"; } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/Calculator/Ops.cs b/DSACore/Auxiliary/Calculator/Ops.cs index 702558d..c804257 100644 --- a/DSACore/Auxiliary/Calculator/Ops.cs +++ b/DSACore/Auxiliary/Calculator/Ops.cs @@ -10,4 +10,4 @@ Subtract, Add } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/Calculator/StringSolver.cs b/DSACore/Auxiliary/Calculator/StringSolver.cs index 2eff5b4..212f812 100644 --- a/DSACore/Auxiliary/Calculator/StringSolver.cs +++ b/DSACore/Auxiliary/Calculator/StringSolver.cs @@ -24,30 +24,31 @@ namespace DSACore.Auxiliary.Calculator public override string ToString() { - return "(0+" + this.input.Replace(" ", string.Empty).ToLower() + ")"; + return "(0+" + input.Replace(" ", string.Empty).ToLower() + ")"; } public int Solve() { - string workInput = "0+" + this.input.Replace(" ", string.Empty).ToLower(); + var workInput = "0+" + input.Replace(" ", string.Empty).ToLower(); workInput = ExpandParentheses(workInput); - + // Create a List of the different parts of the calculation, e.g.:{"0", "+", "(5+6)", "d", "3"}. - this.AtomizeOperations(workInput); + AtomizeOperations(workInput); // traverse the List in order of Operation to Create the binary operation tree . - this.NestOperations(); + NestOperations(); // the List now contains only the top operation node, witch can be solved recursively, - return ((ISolvable)this.arguments.First()).Solve(); + return ((ISolvable) arguments.First()).Solve(); } - private static string GetInner(ref string input) // extract the inner bracket an remove the section from the input string + private static string + GetInner(ref string input) // extract the inner bracket an remove the section from the input string { - int depth = 0; + var depth = 0; for (var index = 1; index < input.Length; index++) { - char c = input[index]; + var c = input[index]; switch (c) { case '(': @@ -92,21 +93,13 @@ namespace DSACore.Auxiliary.Calculator private static string ExpandParentheses(string input) // insert * between Parentheses and digits { - for (int i = 0; i < input.Length - 1; i++) - { + for (var i = 0; i < input.Length - 1; i++) if (input[i + 1] == '(' && char.IsNumber(input[i])) - { input = input.Insert(i + 1, "*"); - } - } - for (int i = 1; i < input.Length; i++) - { + for (var i = 1; i < input.Length; i++) if (input[i - 1] == ')' && char.IsNumber(input[i])) - { input = input.Insert(i, "*"); - } - } return input; } @@ -115,16 +108,14 @@ namespace DSACore.Auxiliary.Calculator { for (var index = 0; index < workInput.Length; index++) { - char c = workInput[index]; + var c = workInput[index]; if (char.IsNumber(c)) { // if char number, check if at end of string, else continue looping if (index == workInput.Length - 1) - { // if at end of string; add remaining number to arguments - this.arguments.Add(new Argument(workInput.Substring(0, index + 1))); - } + arguments.Add(new Argument(workInput.Substring(0, index + 1))); continue; } @@ -134,16 +125,13 @@ namespace DSACore.Auxiliary.Calculator case ')': throw new ArgumentException($"Unmögliche Anordnung von Klammern"); case '(': - this.arguments.Add(new StringSolver(GetInner(ref workInput))); + arguments.Add(new StringSolver(GetInner(ref workInput))); index = -1; break; default: - if (index > 0) - { - this.arguments.Add(new Argument(workInput.Substring(0, index))); - } + if (index > 0) arguments.Add(new Argument(workInput.Substring(0, index))); - this.arguments.Add(GetOps(c)); + arguments.Add(GetOps(c)); workInput = workInput.Remove(0, index + 1); index = -1; break; @@ -154,58 +142,44 @@ namespace DSACore.Auxiliary.Calculator private void NestOperations() { foreach (Ops currentOp in Enum.GetValues(typeof(Ops))) - { // cycle through operators in operational order - for (var index = 0; index < this.arguments.Count; index++) + for (var index = 0; index < arguments.Count; index++) { - var arg = this.arguments[index]; + var arg = arguments[index]; - if (arg.GetType() != typeof(Ops)) - { - continue; - } + if (arg.GetType() != typeof(Ops)) continue; // arg is of type Ops - var op = (Ops)arg; + var op = (Ops) arg; - if (op != currentOp) - { - continue; - } + if (op != currentOp) continue; // arg describes the current operation - this.HandleSpecialFormatting(ref index, op); // Deal with special needs... + HandleSpecialFormatting(ref index, op); // Deal with special needs... // replace the previous current and next Element in the List with one Operation object - var temp = new Operator((ISolvable)this.arguments[index - 1], (ISolvable)this.arguments[index + 1], op); - this.arguments[index - 1] = temp; - this.arguments.RemoveRange(index, 2); + var temp = new Operator((ISolvable) arguments[index - 1], (ISolvable) arguments[index + 1], op); + arguments[index - 1] = temp; + arguments.RemoveRange(index, 2); index--; } - } } private void HandleSpecialFormatting(ref int index, Ops op) { - var arg1 = this.arguments[index - 1]; + var arg1 = arguments[index - 1]; if (arg1.GetType() == typeof(Ops)) { - if (op == Ops.Dice) - { - this.arguments.Insert(index++, new Argument("1")); // w6 -> 1w6 - } + if (op == Ops.Dice) arguments.Insert(index++, new Argument("1")); // w6 -> 1w6 - if (op == Ops.Subtract) - { - this.arguments.Insert(index++, new Argument("0")); // +-3 -> +0-3 - } + if (op == Ops.Subtract) arguments.Insert(index++, new Argument("0")); // +-3 -> +0-3 } - var arg2 = this.arguments[index + 1]; // 3+-5 -> 3+(0-5) + var arg2 = arguments[index + 1]; // 3+-5 -> 3+(0-5) if (arg2.GetType() == typeof(Ops)) { - this.arguments[index + 1] = new Operator(new Argument("0"), (ISolvable)this.arguments[index + 2], (Ops)arg2); - this.arguments.RemoveAt(index + 2); + arguments[index + 1] = new Operator(new Argument("0"), (ISolvable) arguments[index + 2], (Ops) arg2); + arguments.RemoveAt(index + 2); } } } diff --git a/DSACore/Auxiliary/CommandInfo.cs b/DSACore/Auxiliary/CommandInfo.cs index a83e30a..9afe6c0 100644 --- a/DSACore/Auxiliary/CommandInfo.cs +++ b/DSACore/Auxiliary/CommandInfo.cs @@ -10,10 +10,10 @@ namespace DSACore.Auxiliary { public CommandInfo(string name, string brief, string[] description, string scope) { - this.Name = name; - this.Scope = scope; - this.Brief = brief; - this.Description = description; + Name = name; + Scope = scope; + Brief = brief; + Description = description; } public string Name { get; } @@ -26,7 +26,7 @@ namespace DSACore.Auxiliary public string GetDescription() { - return this.Description.Aggregate((s, c) => s + c); + return Description.Aggregate((s, c) => s + c); } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/Dice.cs b/DSACore/Auxiliary/Dice.cs index 2df8aa7..3dd6562 100644 --- a/DSACore/Auxiliary/Dice.cs +++ b/DSACore/Auxiliary/Dice.cs @@ -5,7 +5,7 @@ namespace DSACore.Auxiliary { public static class Dice // roll it! { - private static readonly System.Random Rnd = new System.Random(); + private static readonly Random Rnd = new Random(); public static int Roll(int d = 20) { @@ -14,29 +14,24 @@ namespace DSACore.Auxiliary public static int Roll(string input) { - var strings = input.ToLower().Split(new[] { 'w', 'd' }, 2, StringSplitOptions.RemoveEmptyEntries).ToList(); - int count = Convert.ToInt32(strings[0]); - int d = Convert.ToInt32(strings[0]); + var strings = input.ToLower().Split(new[] {'w', 'd'}, 2, StringSplitOptions.RemoveEmptyEntries).ToList(); + var count = Convert.ToInt32(strings[0]); + var d = Convert.ToInt32(strings[0]); if (strings.Count != 2) - { throw new ArgumentException($"{input}: erfüllt nicht die Formatvogaben( Anzahl d Augenzahl)"); - } return Roll(count, d); } public static int Roll(int count, int d) { - if (d <= 0) - { - return 0; - } + if (d <= 0) return 0; - int sum = 0; - for (int i = 0; i < Math.Abs(count); i++) + var sum = 0; + for (var i = 0; i < Math.Abs(count); i++) { - var roll = Dice.Roll(d); + var roll = Roll(d); sum += roll; } @@ -45,4 +40,4 @@ namespace DSACore.Auxiliary return sum; } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/Extensions.cs b/DSACore/Auxiliary/Extensions.cs index 8ef6298..f8e9d8e 100644 --- a/DSACore/Auxiliary/Extensions.cs +++ b/DSACore/Auxiliary/Extensions.cs @@ -6,14 +6,10 @@ //If the original string is already longer, it is returner unmodified. public static string AddSpaces(this string str, int length) { - string temp = str; - for(int i = str.Length; i < length; i++) - { - temp += " "; - } + var temp = str; + for (var i = str.Length; i < length; i++) temp += " "; return temp; } - //This mehod extends string. @@ -21,13 +17,9 @@ //If the original string is already longer, it is returner unmodified. public static string AddSpacesAtHead(this string str, int length) { - string temp = ""; - for (int i = str.Length; i < length; i++) - { - temp += " "; - } + var temp = ""; + for (var i = str.Length; i < length; i++) temp += " "; return temp + str; } } - -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/RandomMisc.cs b/DSACore/Auxiliary/RandomMisc.cs index 1295f02..72c2234 100644 --- a/DSACore/Auxiliary/RandomMisc.cs +++ b/DSACore/Auxiliary/RandomMisc.cs @@ -13,40 +13,40 @@ namespace DSACore.Auxiliary { var output = new StringBuilder(); var strings = input.Split('w', 'd').ToList(); - int count = Convert.ToInt32(strings[0]); + var count = Convert.ToInt32(strings[0]); strings = strings[1].Split(' ').ToList(); - int d = Convert.ToInt32(strings[0]); + var d = Convert.ToInt32(strings[0]); if (strings.Count > 0) { } - int sum = 0; - for (int i = 0; i < count; i++) + var sum = 0; + for (var i = 0; i < count; i++) { var roll = Dice.Roll(d); sum += roll; output.Append("[" + roll + "] "); } - - if (strings.Count > 1) - { - sum += Convert.ToInt32(strings[1]); - output.Append("sum: " + sum); - } + + if (strings.Count > 1) + { + sum += Convert.ToInt32(strings[1]); + output.Append("sum: " + sum); + } return output.ToString(); } public static double Random(double stdDev = 1, double mean = 0) { - double u1 = Rand.NextDouble(); // uniform(0,1) random doubles - double u2 = Rand.NextDouble(); - double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * - Math.Sin(2.0 * Math.PI * u2); // random normal(0,1) - double randNormal = + var u1 = Rand.NextDouble(); // uniform(0,1) random doubles + var u2 = Rand.NextDouble(); + var randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * + Math.Sin(2.0 * Math.PI * u2); // random normal(0,1) + var randNormal = mean + stdDev * randStdNormal; // random normal(mean,stdDev^2) return randNormal; } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/SpellCorrect.cs b/DSACore/Auxiliary/SpellCorrect.cs index c9603f6..3ef7bb6 100644 --- a/DSACore/Auxiliary/SpellCorrect.cs +++ b/DSACore/Auxiliary/SpellCorrect.cs @@ -15,44 +15,25 @@ public static int CompareEasy(string x, string y) { - if (string.IsNullOrEmpty(x)) - { - throw new ArgumentException("message", nameof(x)); - } + if (string.IsNullOrEmpty(x)) throw new ArgumentException("message", nameof(x)); - if (string.IsNullOrEmpty(y)) - { - throw new ArgumentException("message", nameof(y)); - } + if (string.IsNullOrEmpty(y)) throw new ArgumentException("message", nameof(y)); - if (x.Equals(y)) - { - return 0; - } + if (x.Equals(y)) return 0; x = x.ToLower(); y = y.ToLower(); - if (x.Equals(y)) - { - return 1; - } + if (x.Equals(y)) return 1; var subs = y.Split(' ', '/'); - int score = subs.Count(); - foreach (string s in subs) - { + var score = subs.Count(); + foreach (var s in subs) if (s.Equals(x)) - { score--; - } - } - if (score < subs.Count()) - { - return score + 1; - } + if (score < subs.Count()) return score + 1; - return 100000 - (int)(CompareExact(x, y) * 1000.0); + return 100000 - (int) (CompareExact(x, y) * 1000.0); /*if (y.Contains(x)) return 6;*/ } @@ -70,7 +51,6 @@ public static double CompareExact(string s, string q) { - s = s.ToLower(); q = q.ToLower(); @@ -81,67 +61,46 @@ double decay; - double[,] matrix = new double[s.Length + 1, q.Length + 1]; - double max = 0.0; + var matrix = new double[s.Length + 1, q.Length + 1]; + var max = 0.0; matrix[0, 0] = 0.0; - + for (i = 1; i < s.Length; i++) - { - // matrix[i, 0] = 0.0; + // matrix[i, 0] = 0.0; matrix[i, 0] = i * Gap; - } - for (i = 1; i < q.Length; i++) - { - matrix[0, i] = 0.0; - } + for (i = 1; i < q.Length; i++) matrix[0, i] = 0.0; for (i = 1; i <= s.Length; i++) + for (j = 1; j <= q.Length; j++) { - for (j = 1; j <= q.Length; j++) - { - decay = j / (double)(s.Length * 1000); - double add = s[i - 1] == q[j - 1] ? (Match - decay) : Mismatch; - double score = matrix[i - 1, j - 1] + add; + decay = j / (double) (s.Length * 1000); + var add = s[i - 1] == q[j - 1] ? Match - decay : Mismatch; + var score = matrix[i - 1, j - 1] + add; - if (score < (matrix[i - 1, j] + Gap)) - { - score = matrix[i - 1, j] + Gap; - } + if (score < matrix[i - 1, j] + Gap) score = matrix[i - 1, j] + Gap; - if (score < (matrix[i, j - 1] + Gap)) - { - score = matrix[i, j - 1] + Gap; - } + if (score < matrix[i, j - 1] + Gap) score = matrix[i, j - 1] + Gap; - if (i > 1 && j > 1) + if (i > 1 && j > 1) + if (s[i - 1] == q[j - 2] && s[i - 2] == q[j - 1]) { - if (s[i - 1] == q[j - 2] && s[i - 2] == q[j - 1]) - { - add = (3 / 2.0) * Match - decay; - if (score < matrix[i - 2, j - 2] + add) - { - score = matrix[i - 2, j - 2] + add; - } - } + add = 3 / 2.0 * Match - decay; + if (score < matrix[i - 2, j - 2] + add) score = matrix[i - 2, j - 2] + add; } - - // if (score < 0) - // { - // score = 0; - // } - if (max < score && i == s.Length) - { - max = score; - } + // if (score < 0) + // { + // score = 0; + // } + + if (max < score && i == s.Length) max = score; - matrix[i, j] = score; - } + matrix[i, j] = score; } return max; } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/TalentEnumerableExtension.cs b/DSACore/Auxiliary/TalentEnumerableExtension.cs index a4ace2f..159480d 100644 --- a/DSACore/Auxiliary/TalentEnumerableExtension.cs +++ b/DSACore/Auxiliary/TalentEnumerableExtension.cs @@ -15,12 +15,10 @@ namespace DSACore.Auxiliary var tTalent = List.OrderBy(x => sc.Compare(talent, x.Name)).First(); if (sc.Compare(talent, tTalent.Name) > SpellCorrect.ErrorThreshold) - { return $"{c.Name} kann nicht {talent}..."; - } var props = tTalent.GetEigenschaften(); // get the required properties - int tap = tTalent.Value; // get taw + var tap = tTalent.Value; // get taw var werte = props.Select(p => c.Eigenschaften[c.PropTable[p]]).ToList(); output.AppendFormat( @@ -34,51 +32,42 @@ namespace DSACore.Auxiliary output.Append(" "); tap -= erschwernis; - int gesamtErschwernis = tap; + var gesamtErschwernis = tap; if (gesamtErschwernis < 0) { tap = 0; - for (int i = 0; i <= 2; i++) + for (var i = 0; i <= 2; i++) { // foreach property, dice and tap - int temp = Dice.Roll(); - int eigenschaft = c.Eigenschaften[c.PropTable[props[i]]]; + var temp = Dice.Roll(); + var eigenschaft = c.Eigenschaften[c.PropTable[props[i]]]; - if (eigenschaft + gesamtErschwernis < temp) - { - tap -= temp - (eigenschaft + gesamtErschwernis); - } + if (eigenschaft + gesamtErschwernis < temp) tap -= temp - (eigenschaft + gesamtErschwernis); output.Append($"[{temp}]"); // add to string } - if (tap >= 0) - { - tap = 1; - } + if (tap >= 0) tap = 1; } else { - for (int i = 0; i <= 2; i++) + for (var i = 0; i <= 2; i++) { // foreach property, dice and tap - int temp = Dice.Roll(); - int eigenschaft = c.Eigenschaften[c.PropTable[props[i]]]; + var temp = Dice.Roll(); + var eigenschaft = c.Eigenschaften[c.PropTable[props[i]]]; - if (eigenschaft < temp) - { - tap -= temp - eigenschaft; - } + if (eigenschaft < temp) tap -= temp - eigenschaft; output.Append($"[{temp}]"); // add to string } } - tap = (tap == 0) ? 1 : tap; - + tap = tap == 0 ? 1 : tap; + output.AppendFormat(" tap: {0,2}", tap); return output.ToString(); // return output } } -} +} \ No newline at end of file diff --git a/DSACore/Auxiliary/WeaponImporter.cs b/DSACore/Auxiliary/WeaponImporter.cs index 635d477..ab51efb 100644 --- a/DSACore/Auxiliary/WeaponImporter.cs +++ b/DSACore/Auxiliary/WeaponImporter.cs @@ -20,13 +20,13 @@ namespace DSACore.Auxiliary { var client = new HttpClient(); - - for (int i = 1; i <= 25; i++) + for (var i = 1; i <= 25; i++) { - var responseString = await client.GetStringAsync("http://diarium.eu/dsa4-forge/ajax/categoryChanged/" + i); + var responseString = + await client.GetStringAsync("http://diarium.eu/dsa4-forge/ajax/categoryChanged/" + i); - Regex talentRegex = new Regex(@"(?<=