Skip to content

Commit

Permalink
init server
Browse files Browse the repository at this point in the history
  • Loading branch information
LIU9293 committed Jul 3, 2023
1 parent ef1e6d1 commit 199ddf8
Show file tree
Hide file tree
Showing 23 changed files with 286 additions and 77 deletions.
Binary file removed .DS_Store
Binary file not shown.
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk


# Added by cargo

/target
/dist
.vercel
Expand Down
6 changes: 4 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"./Cargo.toml",
"./Cargo.toml",
"./Cargo.toml",
"./Cargo.toml"
]
"./Cargo.toml",
"./packages/shared/Cargo.toml"
],
"rust-analyzer.showUnlinkedFileNotification": false
}
59 changes: 33 additions & 26 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
[package]
name = "rust-2048"
version = "0.1.0"
description = "It's a 2048 game written in Rust."
authors = ["liu9293 <[email protected]>"]
edition = "2021"
# [package]
# name = "rust-2048"
# version = "0.1.0"
# description = "It's a 2048 game written in Rust."
# authors = ["liu9293 <[email protected]>"]
# edition = "2021"

[dependencies]
dioxus-router = "0.3.0"
rand = "0.8.5"
getrandom = { version = "0.2", features = ["js"] }
# [dependencies]
# dioxus-router = "0.3.0"
# rand = "0.8.5"
# getrandom = { version = "0.2", features = ["js"] }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
dioxus = "0.3.0"
dioxus-desktop = "0.3.0"
# [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# dioxus = "0.3.0"
# dioxus-desktop = "0.3.0"

[target.'cfg(target_arch = "wasm32")'.dependencies]
dioxus = "0.3.2"
dioxus-web = "0.3.2"
# [target.'cfg(target_arch = "wasm32")'.dependencies]
# dioxus = "0.3.2"
# dioxus-web = "0.3.2"

[package.metadata.bundle]
name = "Rust 2048"
identifier = "com.rust.kaixiaozao"
version = "0.0.1"
copyright = "Copyright (c) KaiXiaoZao 2023. All rights reserved."
category = "Game"
short_description = "2048 game"
long_description = """
It's a 2048 game written in Rust.
"""
# [package.metadata.bundle]
# name = "Rust 2048"
# identifier = "com.rust.kaixiaozao"
# version = "0.0.1"
# copyright = "Copyright (c) KaiXiaoZao 2023. All rights reserved."
# category = "Game"
# short_description = "2048 game"
# long_description = """
# It's a 2048 game written in Rust.
# """

[workspace]
members = [
"packages/client",
"packages/shared",
"packages/server"
]
5 changes: 3 additions & 2 deletions Dioxus.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
[application]
name = "rust-2048"
default_platform = "web"
out_dir = "dist"
asset_dir = "public"
out_dir = "../../dist"
asset_dir = "../../public"
sub_package = "packages/client"

[web.app]
title = "rust-2048"
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Live Demo -> https://rust-2048.vercel.app/

### Test and run
```
1. Run server
cargo run -p server
2. Run client
// web
dioxus serve --platform web
Expand Down Expand Up @@ -33,6 +37,8 @@ dioxus serve --platform desktop
- [ ] CI/CD
* Web -> Vercel, done
* Desktop?
- [x] Server, record game progress
- [ ] Server, record progress for multiple users

### Server

Expand Down
16 changes: 3 additions & 13 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,12 @@
<script src="https://cdn.tailwindcss.com"></script>
{style_include}
<style>
html, body {
background-color: #495057;
color: white;
}

#main {
min-height: 100vh;
width: 100%;
}
html,body { background-color: #495057; color: white; }
#main { min-height: 100vh; width: 100%; }
</style>
</head>
<body>
<div id="main"></div>
<!-- Note the usage of `type=module` here as this is an ES6 module -->
<script type="module">
import init from "/{base_path}/assets/dioxus/{app_name}.js";
init("/{base_path}/assets/dioxus/{app_name}_bg.wasm").then((wasm) => {
Expand All @@ -44,9 +36,7 @@
counter = 0
new_e = new e.constructor(e.type, e);
gamearea.dispatchEvent(new_e);
setTimeout(function() {
counter = 1
}, 100);
setTimeout(function() { counter = 1 }, 20);
}
});
</script>
Expand Down
38 changes: 38 additions & 0 deletions packages/client/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
[package]
name = "client"
version = "0.1.0"
description = "It's a 2048 game written in Rust."
authors = ["liu9293 <[email protected]>"]
edition = "2021"

[dependencies]
dioxus-router = "0.3.0"
rand = "0.8.5"
getrandom = { version = "0.2", features = ["js"] }
futures = "0.3"
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
shared = { path = "../shared" }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
dioxus = "0.3.0"
dioxus-desktop = "0.3.0"

[target.'cfg(target_arch = "wasm32")'.dependencies]
dioxus = "0.3.2"
dioxus-web = "0.3.2"
wasm-logger = "0.2.0"
console_error_panic_hook = "0.1.7"

[package.metadata.bundle]
name = "Rust 2048"
identifier = "com.rust.kaixiaozao"
version = "0.0.1"
copyright = "Copyright (c) KaiXiaoZao 2023. All rights reserved."
category = "Game"
short_description = "2048 game"
long_description = """
It's a 2048 game written in Rust.
"""
File renamed without changes.
File renamed without changes.
File renamed without changes.
24 changes: 7 additions & 17 deletions src/main.rs → packages/client/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![allow(non_snake_case)]
mod pages;
mod components;
mod utils;
// mod utils;
use dioxus::prelude::*;
use dioxus_router::{Route, Router};
use crate::pages::game::Game;
Expand All @@ -24,15 +24,8 @@ fn main() {
<script src="https://cdn.tailwindcss.com"></script>
<style>
html,
body {
background-color: #495057;
color: white;
}
#main {
min-height: 100vh;
width: 100%;
}
body { background-color: #495057; color: white; }
#main { min-height: 100vh; width: 100%; }
</style>
</head>
<body>
Expand All @@ -45,12 +38,10 @@ fn main() {
return
}
if (counter === 1) {
counter = 0
new_e = new e.constructor(e.type, e);
gamearea.dispatchEvent(new_e);
setTimeout(function() {
counter = 1
}, 100);
counter = 0
new_e = new e.constructor(e.type, e);
gamearea.dispatchEvent(new_e);
setTimeout(function() { counter = 1 }, 20);
}
});
</script>
Expand All @@ -63,7 +54,6 @@ fn main() {

#[cfg(target_arch = "wasm32")]
// wasm_logger::init(wasm_logger::Config::default());
// console_error_panic_hook::set_once();
dioxus_web::launch(app);
}

Expand Down
56 changes: 52 additions & 4 deletions src/pages/game.rs → packages/client/src/pages/game.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,43 @@
use dioxus::prelude::*;
use dioxus::html::input_data::keyboard_types::Key;
use dioxus::html::KeyboardEvent;
use shared::types::{Board, GameStatus, ProgressReqeust};
use reqwest;
use shared::logic::{get_initial_board_data, add_random, move_up, move_down, move_left, move_right, check_and_do_next};
use log;
use crate::components::row::Row;
use crate::utils::types::{Board, GameStatus};
use crate::utils::logic::{get_initial_board_data, add_random, move_up, move_down, move_left, move_right, check_and_do_next};

pub fn Game(cx: Scope) -> Element {
let game_status = use_state(cx, || GameStatus::Playing);
let board_data: &UseState<Board> = use_state(cx, || get_initial_board_data());

let is_first_load = use_state(cx, || true);

use_effect(cx, (is_first_load, board_data), |(is_first_load, board_data)| async move {
if !is_first_load.get() {
return;
}

let client = reqwest::Client::new();
let res = client.get("http://localhost:3000/progress").send().await;
match res {
Ok(response) => {
let payload = response.json::<ProgressReqeust>().await;
match payload {
Ok(data) => {
is_first_load.set(false);
board_data.set(data.board);
},
Err(err) => {
log::error!("Failed to parse JSON: {}", err);
}
}
},
Err(err) => {
log::error!("Failed to send request: {}", err);
}
}
});

let handle_key_down_event = move |evt: KeyboardEvent| -> () {
if *game_status.get() != GameStatus::Playing {
return;
Expand Down Expand Up @@ -36,7 +65,26 @@ pub fn Game(cx: Scope) -> Element {
game_status.set(GameStatus::Fail);
},
GameStatus::Playing => { board_data.set(new_data); },
}
}

cx.spawn({
async move {
let client = reqwest::Client::new();
let res = client.post("http://localhost:3000/progress")
.json(&ProgressReqeust {
board: new_data
})
.send()
.await;

match res {
Ok(_) => {},
Err(err) => {
log::error!("Failed to record progress: {}", err);
}
}
}
});
};

let total_score = board_data.get().iter().flatten().sum::<i32>();
Expand Down
File renamed without changes.
File renamed without changes.
13 changes: 13 additions & 0 deletions packages/server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "server"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
axum = { version = "0.6" }
tokio = { version = "1.0", features = ["full"] }
tower-http = { version = "0.3.0", features = ["cors"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
shared = { path = "../shared" }
Loading

0 comments on commit 199ddf8

Please sign in to comment.