move team to game client

This commit is contained in:
Arkitu 2025-04-11 18:15:53 +02:00
parent 14ce0ebf7e
commit f3124bcf03
2 changed files with 11 additions and 9 deletions

View File

@ -11,21 +11,23 @@ static TURN: AtomicBool = AtomicBool::new(false);
static BOARD: AtomicU32 = AtomicU32::new(0);
pub struct GameClient {
res_buf: Vec<u8, 4096>
res_buf: Vec<u8, 4096>,
team: Team
}
impl GameClient {
pub fn new() -> Self {
pub fn new(team: Team) -> Self {
Self {
res_buf: Vec::new(),
team
}
}
pub async fn handle_request<'a>(&'a mut self, path: &str, team: Team) -> (HttpResCode, &'static str, &'a [u8]) {
pub async fn handle_request<'a>(&'a mut self, path: &str) -> (HttpResCode, &'static str, &'a [u8]) {
if (path.starts_with("/ttt/cell") && path.len() == 10) || path == "/ttt/board" {
let mut board = BOARD.load(Ordering::Acquire);
let mut turn = TURN.load(Ordering::Acquire);
// just return correct board in case of unauthorized move
if path.starts_with("/ttt/cell") && team == turn.into() {
if path.starts_with("/ttt/cell") && self.team == turn.into() {
let clicked_c: Cell = match TryInto::<Cell>::try_into(
unwrap(path.chars().nth(9).ok_or("no 9th char")).await,
) {
@ -39,8 +41,8 @@ impl GameClient {
{
return (HttpResCode::Forbidden, "", &[]);
}
board = board | 2_u32.pow((team as u32 * 9) + clicked_c as u32);
turn = (!team).into();
board = board | 2_u32.pow((self.team as u32 * 9) + clicked_c as u32);
turn = (!self.team).into();
BOARD.store(board, Ordering::Release);
TURN.store(turn, Ordering::Release);
}
@ -66,7 +68,7 @@ impl GameClient {
b"<div class=\"cell\" style=\"background-color:red\"></div>",
)).await;
}
None => if team == turn.into() {
None => if self.team == turn.into() {
unwrap(write!(
self.res_buf,
"<button class=\"cell\" hx-post=\"/ttt/cell{}\" hx-trigger=\"click\" hx-target=\"#grid\" hx-swap=\"innerHTML\"></button>",

View File

@ -20,7 +20,7 @@ pub async fn listen_task(stack: embassy_net::Stack<'static>, team: Team, port: u
let mut buf = [0; 4096];
let mut res_head_buf = Vec::<u8, 4096>::new();
let mut game_client = GameClient::new();
let mut game_client = GameClient::new(team);
loop {
Timer::after_secs(0).await;
@ -116,7 +116,7 @@ pub async fn listen_task(stack: embassy_net::Stack<'static>, team: Team, port: u
"javascript",
include_bytes!("../web/htmx.js"),
),
p => game_client.handle_request(p, team).await
p => game_client.handle_request(p).await
};
res_head_buf.clear();