Skip to content

Commit

Permalink
Merge pull request #49 from pilksoc/redux-game-client
Browse files Browse the repository at this point in the history
working websockete uwuwuwuuw
  • Loading branch information
djpiper28 authored May 6, 2024
2 parents 8a11aae + 7cdd647 commit 1fc2645
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 14 deletions.
2 changes: 2 additions & 0 deletions backend/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
rustflags = ["--cfg", "tokio_unstable"]
5 changes: 2 additions & 3 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
openai_api_rust = "0.1.8"
diesel = { version = "2.1.0", features = ["postgres"] }
dotenvy = "0.15"
uuid = { version = "1.7.0", features = ["serde", "v4", "fast-rng", "macro-diagnostics"] }
tokio = { version = "1", features = ["full"] }
tokio = { version = "1.15", features = ["full", "tracing", "rt"] }
tokio-stream = "0.1.6"
async-trait = "0.1.77"
thiserror = "1.0.57"
Expand All @@ -23,3 +21,4 @@ reqwest = "0.11.24"
url = "2.5.0"
rand = "0.8.5"
lazy_static = "1.4.0"
console-subscriber = "0.2.0"
14 changes: 13 additions & 1 deletion backend/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#![feature(async_closure)]
use std::convert::Infallible;
use cosmic_kube::{Clients, CLIENTS};
use warp::{Filter, Rejection};
use std::backtrace::Backtrace;
use std::panic;

mod handlers;
mod ws;
Expand All @@ -9,9 +12,18 @@ mod ws;
type Result<T> = std::result::Result<T, Rejection>;


#[tokio::main]
#[tokio::main(flavor = "multi_thread")]
async fn main() {
panic::set_hook(Box::new(|info| {
//let stacktrace = Backtrace::capture();
let stacktrace = Backtrace::force_capture();
println!("Got panic. @info:{}\n@stackTrace:{}", info, stacktrace);
std::process::abort();
}));

//initialise a hashmap to store currently connected clients. We may want some more logic here if we want currently connected clients to be stored somewhere
println!("Turning console on"); //debug
console_subscriber::init();

println!("Configuring websocket route"); //debug
let ws_route = warp::path("ws")
Expand Down
17 changes: 15 additions & 2 deletions backend/src/modify_gamestate.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// methods here are solely for modifying the state of the game!

use std::fmt;

use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -50,10 +49,12 @@ pub struct Action {
}

pub async fn modify_gamestate(player_state: PlayerInfo) {
println!("Moving player");
// move the player's position on the grid
move_player(player_state.old_coordinates, player_state.coordinates, player_state.player).await;

// then we want to update the grid by performing action
println!("Performing action");
match player_state.action {
Some(p) => perform_action(p).await,
None => (),
Expand All @@ -75,18 +76,30 @@ pub async fn perform_action(action: Action) {
pub async fn move_player(old_pos: Option<[u64; 2]>, new_pos: [u64; 2], player: Player) {
let player_key = player.uuid.to_string();

println!("Removing old position");
//remove the players old location in the world, if provided
match old_pos {
Some(c) => WORLD.lock().await.insert(Space::new(c, SpaceKind::EmptySpace)),
_ => (),
}

println!("Adding new position");
// store the players location in the world
let playerspace: Space = Space::new(new_pos, SpaceKind::Player(player));
WORLD.lock().await.insert(playerspace);

println!("Updating player position");
//we now store the player's last known location in the 'active clients' hashmap
CLIENTS.lock().await.entry(player_key).and_modify(|client| client.last_position = new_pos);
tokio::spawn(
async move {
CLIENTS.lock().await
.entry(player_key)
.and_modify(|client| client.last_position = new_pos);
Ok::<(), ()>(())
}
);

println!("Updated that bastard of a player!!");
}

pub async fn remove_player(player_location: Coordinate) {
Expand Down
13 changes: 5 additions & 8 deletions backend/src/ws.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::ws::gen_json::create_response;
use cosmic_kube::{modify_gamestate::remove_player, CLIENTS, Client, Coordinate};
use futures::{FutureExt, StreamExt};
use futures::StreamExt;
use rand::Rng;
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use uuid::Uuid;
use warp::ws::{Message, WebSocket};

mod gen_json;

pub async fn client_connection(ws: WebSocket) {
Expand All @@ -20,13 +21,9 @@ pub async fn client_connection(ws: WebSocket) {
let (client_sender, client_rcv) = mpsc::unbounded_channel();

let client_rcv = UnboundedReceiverStream::new(client_rcv);

// 'spawns' a new task, that stays alive until the client has disconnected.
tokio::task::spawn(client_rcv.forward(client_ws_sender).map(|result| {
if let Err(e) = result {
println!("error sending websocket msg: {}", e);
}
}));
tokio::spawn(client_rcv.forward(client_ws_sender));

// creating a new uuid to use as the key in the 'clients' hashmap, and a new instance of a 'client'
// this might be clapped
Expand Down Expand Up @@ -79,7 +76,7 @@ async fn call_remove_player(uuid: &str) {
// ->recieve client game info <- send back client game state
// wwwwwwwwwwwwwwwwwwwww i am so tired
async fn client_msg(client_id: &str, msg: Message) {
//println!("received message from {}: {:?}", client_id, msg); //debug
println!("Received message from {client_id}"); //debug

let Ok(message) = msg.to_str() else { return };

Expand Down
1 change: 1 addition & 0 deletions backend/src/ws/gen_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ async fn recalculate_game(state: PlayerInfo, id: &str) -> String {
println!("Generating new game state for {id}");
modify_gamestate(state).await;

println!("Updating world data for {id}");
// The dereferencing looks a little weird. Here's what's going on:
// Tokio's Mutex when locking returns a MutexGuard.
// This is the same behaviour as std::sync::Mutex.
Expand Down
1 change: 1 addition & 0 deletions game-source-redux/src/lib/websockets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { v4 } from "uuid";

const baseUrl = "wss://hack.djpiper28.co.uk/ws/";
// const baseUrl = "ws://localhost:8000/ws/";

export const ERR_VAL = -9999999;

Expand Down

0 comments on commit 1fc2645

Please sign in to comment.