From b5a52fc0312afdf5d5fbe53275dc88d6d881c2ff Mon Sep 17 00:00:00 2001 From: salmonik Date: Thu, 29 Oct 2026 18:22:40 +0100 Subject: v2.2.0: add blackjack with reserved bets and hit/stand/double --- src/server/database.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) (limited to 'src/server/database.rs') diff --git a/src/server/database.rs b/src/server/database.rs index 2a1fc40..99e0dde 100644 --- a/src/server/database.rs +++ b/src/server/database.rs @@ -177,3 +177,84 @@ pub fn count_plays(conn: &Connection, username: &str) -> i64 { ) .unwrap_or(0) } + +/// Reserve a bet before a multi-step hand starts. +pub fn debit(conn: &mut Connection, username: &str, amount: i64) -> rusqlite::Result { + let tx = conn.transaction()?; + let updated = tx.execute( + "UPDATE users SET balance = balance - ?1 + WHERE username = ?2 AND balance >= ?1", + params![amount, username], + )?; + if updated != 1 { + return Err(rusqlite::Error::QueryReturnedNoRows); + } + let balance = tx.query_row( + "SELECT balance FROM users WHERE username = ?1", + [username], + |row| row.get(0), + )?; + tx.commit()?; + Ok(balance) +} + +/// Put a reserved bet back (disconnect or cancel). +pub fn credit(conn: &mut Connection, username: &str, amount: i64) -> rusqlite::Result { + let tx = conn.transaction()?; + tx.execute( + "UPDATE users SET balance = balance + ?1 WHERE username = ?2", + params![amount, username], + )?; + let balance = tx.query_row( + "SELECT balance FROM users WHERE username = ?1", + [username], + |row| row.get(0), + )?; + tx.commit()?; + Ok(balance) +} + +/// Settle a hand whose bet was already reserved: credit winnings, write the +/// audit row, and return the new balance. +#[allow(clippy::too_many_arguments)] +pub fn settle_play( + conn: &mut Connection, + session_id: &str, + username: &str, + game_type: &str, + bet_amount: i64, + winnings: i64, + details: &str, +) -> rusqlite::Result { + let tx = conn.transaction()?; + + tx.execute( + "UPDATE users SET balance = balance + ?1 WHERE username = ?2", + params![winnings, username], + )?; + + let balance_after: i64 = tx.query_row( + "SELECT balance FROM users WHERE username = ?1", + [username], + |row| row.get(0), + )?; + + tx.execute( + "INSERT INTO plays + (session_id, username, game_type, bet_amount, winnings, + balance_after, details) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + session_id, + username, + game_type, + bet_amount, + winnings, + balance_after, + details + ], + )?; + + tx.commit()?; + Ok(balance_after) +} -- cgit v1.2.3