Skip to content

Commit

Permalink
add leaderboard api
Browse files Browse the repository at this point in the history
  • Loading branch information
LIU9293 committed Jul 12, 2023
1 parent af62862 commit 800af7c
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 19 deletions.
2 changes: 1 addition & 1 deletion packages/client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fn main() {
);

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

Expand Down
20 changes: 11 additions & 9 deletions packages/client/src/pages/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ pub fn Game(cx: Scope) -> Element {
}
});
};

let restart_game = |_| -> () {
board_data.set(get_initial_board_data());
game_status.set(GameStatus::Playing);

// reset game uuid
let uuid = Uuid::new_v4();
LocalStorage::set("uuid", uuid.to_string()).unwrap();
};

let total_score = board_data.get().iter().flatten().sum::<i32>();
let highest_score = board_data.get().iter().flatten().max().unwrap_or(&0);
Expand Down Expand Up @@ -157,13 +166,9 @@ pub fn Game(cx: Scope) -> Element {
}
button {
class: "bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded",
onclick: |_| {
board_data.set(get_initial_board_data());
game_status.set(GameStatus::Playing);
},
onclick: restart_game,
"Restart"
}

} ),
GameStatus::Fail => rsx!( div {
class: "flex flex-col items-center mt-8",
Expand All @@ -173,10 +178,7 @@ pub fn Game(cx: Scope) -> Element {
}
button {
class: "btn btn-primary mt-4",
onclick: |_| {
board_data.set(get_initial_board_data());
game_status.set(GameStatus::Playing);
},
onclick: restart_game,
"Restart"
}
} ),
Expand Down
57 changes: 54 additions & 3 deletions packages/server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ use shared::types::{
GetProgressResponse,
SaveProgressResponse,
ProgressReqeust,
DbBoard};
DbBoard,
LeaderboardRow,
LeaderboardResponse
};
use shared::logic::get_initial_board_data;
use postgrest::Postgrest;
use dotenv::dotenv;
Expand Down Expand Up @@ -54,6 +57,7 @@ async fn main() {
let app = Router::new()
.route("/", get(ping))
.route("/progress", get(get_user_progress).post(save_user_progress))
.route("/leaderboard", get(get_leaderboard))
.layer(
tower_http::cors::CorsLayer::new()
.allow_origin(Any)
Expand Down Expand Up @@ -81,9 +85,19 @@ async fn save_user_progress(
Some(uuid) => {
let client = &app_state.supabase_client;
let board_str = serde_json::to_string(&input.board).unwrap();
let s = format!("[{{ \"uuid\": \"{}\", \"progress\": {} }}]",
let score = input.board
.iter()
.fold(0, |acc, row| {
acc + row.iter().fold(0, |acc, cell| {
acc + cell
})
});

let s = format!("[{{ \"uuid\": \"{}\", \"progress\": {}, \"score\": {} }}]",
uuid,
board_str);
board_str,
score);

match client
.from("user_progress")
.upsert(s)
Expand Down Expand Up @@ -152,3 +166,40 @@ fn get_default_progress() -> (StatusCode, Json<GetProgressResponse>) {
board: Some(get_initial_board_data()),
}))
}


async fn get_leaderboard(
State(app_state): State<Arc<AppState>>,
) -> impl IntoResponse {
let client = &app_state.supabase_client;

match client
.from("user_progress")
.select("*")
.order("score.desc")
.limit(20)
.execute()
.await {
Ok(res) => match res.text().await {
Ok(resp) => {
let leadboard_data: Vec<LeaderboardRow> = serde_json::from_str(&resp).unwrap();
(StatusCode::OK, Json(LeaderboardResponse {
success: true,
leaderboard: leadboard_data
}))
},
Err(_) => {
(StatusCode::OK, Json(LeaderboardResponse {
success: false,
leaderboard: vec![]
}))
}
}
Err(_) => {
(StatusCode::OK, Json(LeaderboardResponse {
success: false,
leaderboard: vec![]
}))
},
}
}
7 changes: 2 additions & 5 deletions packages/server/src/sql/schema.sql
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
CREATE TABLE `user_progress` (
`uuid` VARCHAR(36) NOT NULL,
`progress` JSON,
`score` INT,
`user_name` VARCHAR(36),
PRIMARY KEY (`uuid`)
);

CREATE TABLE `user_score` (
`name` VARCHAR(36) NOT NULL,
`score` INT NOT NULL
);
13 changes: 12 additions & 1 deletion packages/shared/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,15 @@ pub struct DbBoardRow {
}

pub type DbBoard = Vec<DbBoardRow>;


#[derive(Debug, Serialize, Deserialize)]
pub struct LeaderboardRow {
pub uuid: String,
pub score: i32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LeaderboardResponse {
pub success: bool,
pub leaderboard: Vec<LeaderboardRow>,
}

0 comments on commit 800af7c

Please sign in to comment.