Compare commits

..

3 Commits

Author SHA1 Message Date
c31fb7d0ff I'm human 2024-05-24 23:15:28 +02:00
b47325a0dc progress 2024-05-24 17:43:35 +02:00
e517bed681 i don't care anymore 2024-05-24 16:43:05 +02:00
45 changed files with 5111 additions and 203 deletions

75
Cargo.lock generated
View File

@@ -1,75 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "getrandom"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "libc"
version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "rustjack"
version = "0.1.0"
dependencies = [
"rand",
]
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"

View File

@@ -1,7 +0,0 @@
[package]
name = "rustjack"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"

View File

1544
backend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

9
backend/Cargo.toml Normal file
View File

@@ -0,0 +1,9 @@
[package]
name = "rustjack"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"
rocket = { version = "0.5.0", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }

View File

@@ -1,4 +1,6 @@
use crate::{decks::new_blackjack_shoe, hand::Hand}; use crate::cards::{card::Card, decks::new_blackjack_shoe, hand::Hand};
use super::{gamestate::GameState, play_moves::PlayMoves, player::Player, playing_hand::{HandState, PlayingHand}};
pub struct BlackjackGame { pub struct BlackjackGame {
shoe: Hand, shoe: Hand,
@@ -7,73 +9,6 @@ pub struct BlackjackGame {
state: GameState, state: GameState,
} }
pub struct Player {
hands: Vec<PlayingHand>,
}
impl Player {
fn new() -> Self {
Player { hands: Vec::new() }
}
pub fn get_hands(&self) -> &Vec<PlayingHand> {
&self.hands
}
fn next_playing_hand(&self) -> Option<usize> {
self.hands
.iter()
.position(|e| e.state == HandState::Playing)
}
}
pub struct PlayingHand {
hand: Hand,
state: HandState,
}
impl PlayingHand {
fn new() -> Self {
PlayingHand {
hand: Hand::new(),
state: HandState::Playing,
}
}
pub fn get_hand(&self) -> &Hand {
&self.hand
}
pub fn get_state(&self) -> HandState {
self.state
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HandState {
Playing,
Standing,
DoubleDown,
Busted,
Blackjack,
Maxed, // Reached 21
}
#[derive(Clone, Copy, Debug)]
pub enum PlayMoves {
Hit,
Stand,
DoubleDown,
Split,
Deal(usize),
}
pub enum GameState {
Starting,
Over, // Game is over
PlayerTurn(usize, usize), // Its the turn of the player
}
impl BlackjackGame { impl BlackjackGame {
pub fn new() -> Self { pub fn new() -> Self {
BlackjackGame { BlackjackGame {
@@ -88,10 +23,18 @@ impl BlackjackGame {
&self.dealer_hand &self.dealer_hand
} }
pub fn get_dealer_upcard(&self) -> Option<&Card> {
self.dealer_hand.get_card(0)
}
pub fn get_state(&self) -> &GameState { pub fn get_state(&self) -> &GameState {
&self.state &self.state
} }
pub fn get_players(&self) -> &Vec<Player>{
&self.players
}
pub fn get_player(&self, index: usize) -> Option<&Player> { pub fn get_player(&self, index: usize) -> Option<&Player> {
self.players.get(index) self.players.get(index)
} }
@@ -102,7 +45,13 @@ impl BlackjackGame {
pub fn play(&mut self, action: PlayMoves) -> bool { pub fn play(&mut self, action: PlayMoves) -> bool {
match (&self.state, action) { match (&self.state, action) {
(GameState::PlayerTurn(player_index, hand_index), PlayMoves::Hit) => { (
GameState::PlayerTurn {
player_index,
hand_index,
},
PlayMoves::Hit,
) => {
let Some(player) = self.players.get_mut(*player_index) else { let Some(player) = self.players.get_mut(*player_index) else {
// Player does not exists // Player does not exists
return false; return false;
@@ -131,7 +80,13 @@ impl BlackjackGame {
} }
}; };
} }
(GameState::PlayerTurn(player_index, hand_index), PlayMoves::Split) => { (
GameState::PlayerTurn {
player_index,
hand_index,
},
PlayMoves::Split,
) => {
let Some(player) = self.players.get_mut(*player_index) else { let Some(player) = self.players.get_mut(*player_index) else {
// Player does not exists // Player does not exists
return false; return false;
@@ -169,7 +124,13 @@ impl BlackjackGame {
player.hands.push(new_hand); player.hands.push(new_hand);
} }
(GameState::PlayerTurn(player_index, hand_index), PlayMoves::DoubleDown) => { (
GameState::PlayerTurn {
player_index,
hand_index,
},
PlayMoves::DoubleDown,
) => {
let Some(player) = self.players.get_mut(*player_index) else { let Some(player) = self.players.get_mut(*player_index) else {
// Player does not exists // Player does not exists
return false; return false;
@@ -203,7 +164,13 @@ impl BlackjackGame {
} }
}; };
} }
(GameState::PlayerTurn(player_index, hand_index), PlayMoves::Stand) => { (
GameState::PlayerTurn {
player_index,
hand_index,
},
PlayMoves::Stand,
) => {
let Some(player) = self.players.get_mut(*player_index) else { let Some(player) = self.players.get_mut(*player_index) else {
// Player does not exists // Player does not exists
return false; return false;
@@ -221,10 +188,14 @@ impl BlackjackGame {
hand.state = HandState::Standing; hand.state = HandState::Standing;
} }
(GameState::Over, PlayMoves::Deal(player_count)) (GameState::Over, PlayMoves::Deal { players })
| (GameState::Starting, PlayMoves::Deal(player_count)) => { | (GameState::Starting, PlayMoves::Deal { players }) => {
// Reset everything
self.dealer_hand = Hand::new();
self.players = Vec::new();
// Create players // Create players
for _ in 0..player_count { for _ in 0..players {
self.players.push(Player::new()); self.players.push(Player::new());
} }
@@ -257,16 +228,22 @@ impl BlackjackGame {
// Add 2nd card to the dealer // Add 2nd card to the dealer
self.dealer_hand.add_card(self.shoe.pop_card().unwrap()); self.dealer_hand.add_card(self.shoe.pop_card().unwrap());
self.state = GameState::PlayerTurn(0, 0); self.state = GameState::PlayerTurn {
player_index: 0,
hand_index: 0,
};
} }
(_, PlayMoves::Deal(_)) | (GameState::Over, _) | (GameState::Starting, _) => { (_, PlayMoves::Deal { .. }) | (GameState::Over, _) | (GameState::Starting, _) => {
return false; return false;
} }
} }
// Find next player or dealer turn // Find next player or dealer turn
if let Some(next_turn) = self.next_player_and_hand() { if let Some(next_turn) = self.next_player_and_hand() {
self.state = GameState::PlayerTurn(next_turn.0, next_turn.1); self.state = GameState::PlayerTurn {
player_index: next_turn.0,
hand_index: next_turn.1,
};
} else { } else {
self.dealer_turn(); self.dealer_turn();
} }
@@ -294,7 +271,11 @@ impl BlackjackGame {
} }
fn next_player_and_hand(&self) -> Option<(usize, usize)> { fn next_player_and_hand(&self) -> Option<(usize, usize)> {
if let GameState::PlayerTurn(player_index, hand_index) = self.state { if let GameState::PlayerTurn {
player_index,
hand_index,
} = self.state
{
let Some(player) = self.players.get(player_index) else { let Some(player) = self.players.get(player_index) else {
// Player does not exists // Player does not exists
return None; return None;

View File

@@ -0,0 +1,12 @@
use serde::Serialize;
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(tag = "type")]
pub enum GameState {
Starting,
Over,
PlayerTurn {
player_index: usize,
hand_index: usize,
},
}

View File

@@ -0,0 +1,5 @@
pub mod blackjack_game;
pub mod gamestate;
pub mod play_moves;
pub mod player;
pub mod playing_hand;

View File

@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum PlayMoves {
Hit,
Stand,
DoubleDown,
Split,
Deal { players: usize },
}

View File

@@ -0,0 +1,24 @@
use serde::Serialize;
use super::playing_hand::{HandState, PlayingHand};
#[derive(Serialize, Clone)]
pub struct Player {
pub(super) hands: Vec<PlayingHand>,
}
impl Player {
pub(super) fn new() -> Self {
Player { hands: Vec::new() }
}
pub fn get_hands(&self) -> &Vec<PlayingHand> {
&self.hands
}
pub(super) fn next_playing_hand(&self) -> Option<usize> {
self.hands
.iter()
.position(|e| *e.get_state() == HandState::Playing)
}
}

View File

@@ -0,0 +1,36 @@
use serde::Serialize;
use crate::cards::hand::Hand;
#[derive(Serialize, Clone)]
pub struct PlayingHand {
pub(super) hand: Hand,
pub(super) state: HandState,
}
impl PlayingHand {
pub(super) fn new() -> Self {
PlayingHand {
hand: Hand::new(),
state: HandState::Playing,
}
}
pub fn get_hand(&self) -> &Hand {
&self.hand
}
pub fn get_state(&self) -> &HandState {
&self.state
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub enum HandState {
Playing,
Standing,
DoubleDown,
Busted,
Blackjack,
Maxed, // Reached 21
}

View File

@@ -1,7 +1,10 @@
use std::fmt::Display; use std::fmt::Display;
use crate::{card_index::CardIndex, card_suit::CardSuit}; use serde::{Deserialize, Serialize};
use super::{card_index::CardIndex, card_suit::CardSuit};
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct Card { pub struct Card {
pub suit: CardSuit, pub suit: CardSuit,
pub index: CardIndex, pub index: CardIndex,

View File

@@ -1,6 +1,8 @@
use std::fmt::Display; use std::fmt::Display;
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Copy)] use serde::{Deserialize, Serialize};
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Copy, Serialize, Deserialize)]
#[repr(u8)] #[repr(u8)]
pub enum CardIndex { pub enum CardIndex {
A = 14, A = 14,

View File

@@ -1,10 +1,16 @@
use std::fmt::Display; use std::fmt::Display;
#[derive(Clone, Copy)] use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum CardSuit { pub enum CardSuit {
#[serde(rename = "S")]
Spades, Spades,
#[serde(rename = "C")]
Clubs, Clubs,
#[serde(rename = "H")]
Hearts, Hearts,
#[serde(rename = "D")]
Diamonds, Diamonds,
} }

View File

@@ -1,4 +1,4 @@
use crate::{card::Card, hand::Hand, CardIndex as CI, CardSuit as CS}; use super::{card::Card, hand::Hand, card_index::CardIndex as CI, card_suit::CardSuit as CS};
pub fn new_full_deck() -> Hand { pub fn new_full_deck() -> Hand {
let mut hand = Hand::new(); let mut hand = Hand::new();

View File

@@ -1,8 +1,10 @@
use rand::{seq::SliceRandom, thread_rng}; use rand::{seq::SliceRandom, thread_rng};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::Display; use std::fmt::Display;
use crate::{card::Card, card_index::CardIndex}; use super::{card::Card, card_index::CardIndex};
#[derive(Clone)]
pub struct Hand { pub struct Hand {
cards: Vec<Card>, cards: Vec<Card>,
} }
@@ -106,19 +108,39 @@ impl Display for Hand {
} }
} }
impl Serialize for Hand {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.cards.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Hand {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let cards = Vec::<Card>::deserialize(deserializer)?;
Ok(Hand { cards })
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::super::card_suit::CardSuit;
use super::*; use super::*;
#[test] #[test]
fn is_blackjack_ace_first() { fn is_blackjack_ace_first() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::A, index: CardIndex::A,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Diamonds, suit: CardSuit::Diamonds,
index: CardIndex::N10, index: CardIndex::N10,
}); });
assert!(hand.is_backjack()); assert!(hand.is_backjack());
@@ -128,11 +150,11 @@ mod tests {
fn is_blackjack_ace_last() { fn is_blackjack_ace_last() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Diamonds, suit: CardSuit::Diamonds,
index: CardIndex::J, index: CardIndex::J,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::A, index: CardIndex::A,
}); });
assert!(hand.is_backjack()); assert!(hand.is_backjack());
@@ -142,15 +164,15 @@ mod tests {
fn is_not_blackjack_too_many() { fn is_not_blackjack_too_many() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Diamonds, suit: CardSuit::Diamonds,
index: CardIndex::J, index: CardIndex::J,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::A, index: CardIndex::A,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Spades, suit: CardSuit::Spades,
index: CardIndex::A, index: CardIndex::A,
}); });
assert!(!hand.is_backjack()); assert!(!hand.is_backjack());
@@ -160,7 +182,7 @@ mod tests {
fn is_not_blackjack_too_few() { fn is_not_blackjack_too_few() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::A, index: CardIndex::A,
}); });
assert!(!hand.is_backjack()); assert!(!hand.is_backjack());
@@ -170,15 +192,15 @@ mod tests {
fn is_not_blackjack_value_21() { fn is_not_blackjack_value_21() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::K, index: CardIndex::K,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Clubs, suit: CardSuit::Clubs,
index: CardIndex::N7, index: CardIndex::N7,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::N4, index: CardIndex::N4,
}); });
assert!(!hand.is_backjack()); assert!(!hand.is_backjack());
@@ -188,7 +210,7 @@ mod tests {
fn blackjack_value() { fn blackjack_value() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Hearts, suit: CardSuit::Hearts,
index: CardIndex::K, index: CardIndex::K,
}); });
assert_eq!(hand.get_blackjack_value(), 10); assert_eq!(hand.get_blackjack_value(), 10);
@@ -198,17 +220,17 @@ mod tests {
fn merge_hands() { fn merge_hands() {
let mut hand = Hand::new(); let mut hand = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Diamonds, suit: CardSuit::Diamonds,
index: CardIndex::N5, index: CardIndex::N5,
}); });
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Spades, suit: CardSuit::Spades,
index: CardIndex::Q, index: CardIndex::Q,
}); });
let mut other = Hand::new(); let mut other = Hand::new();
hand.add_card(Card { hand.add_card(Card {
suit: crate::card_suit::CardSuit::Spades, suit: CardSuit::Spades,
index: CardIndex::K, index: CardIndex::K,
}); });

5
backend/src/cards/mod.rs Normal file
View File

@@ -0,0 +1,5 @@
pub mod card;
pub mod card_index;
pub mod card_suit;
pub mod decks;
pub mod hand;

View File

@@ -1,13 +1,13 @@
use std::io::{self, stdin}; use std::io::{self, stdin};
use crate::blackjack::{BlackjackGame, GameState, PlayMoves}; use crate::blackjack::{blackjack_game::BlackjackGame, gamestate::GameState, play_moves::PlayMoves};
pub fn play() -> Result<(), Box<dyn std::error::Error>> { pub fn play() -> Result<(), Box<dyn std::error::Error>> {
let mut game = BlackjackGame::new(); let mut game = BlackjackGame::new();
loop { loop {
match game.get_state() { match game.get_state() {
GameState::PlayerTurn(player_index, _) => { GameState::PlayerTurn{player_index, ..} => {
print_full_state(&game); print_full_state(&game);
let play_move = get_move(*player_index)?; let play_move = get_move(*player_index)?;
if !game.play(play_move) { if !game.play(play_move) {
@@ -20,7 +20,7 @@ pub fn play() -> Result<(), Box<dyn std::error::Error>> {
return Ok(()); return Ok(());
} }
GameState::Starting => { GameState::Starting => {
game.play(PlayMoves::Deal(2)); game.play(PlayMoves::Deal{players: 2});
} }
} }
} }

13
backend/src/main.rs Normal file
View File

@@ -0,0 +1,13 @@
#![allow(dead_code)]
#[macro_use] extern crate rocket;
use webserver::build;
mod blackjack;
mod cards;
mod console_blackjack;
mod webserver;
#[launch]
fn launch() -> _ {
build()
}

82
backend/src/webserver.rs Normal file
View File

@@ -0,0 +1,82 @@
use std::sync::Mutex;
use rocket::{
http::Status,
serde::{json::Json, Serialize},
Build, Rocket, State,
};
use crate::{
blackjack::{
blackjack_game::BlackjackGame, gamestate::GameState, play_moves::PlayMoves, player::Player,
},
cards::{card::Card, hand::Hand},
};
#[get("/state")]
fn get_state(state: &State<MyState>) -> Json<ExtendedGameState> {
Json(gamestate_as_json(&state.game.lock().unwrap()))
}
#[post("/state", data = "<request>", format = "application/json")]
fn post_move(
state: &State<MyState>,
request: Json<PlayMoves>,
) -> Result<Json<ExtendedGameState>, Status> {
let action = request.into_inner();
if state.game.lock().unwrap().play(action) {
Ok(Json(gamestate_as_json(&state.game.lock().unwrap())))
} else {
Err(Status::BadRequest)
}
}
struct MyState {
game: Mutex<BlackjackGame>,
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum ExtendedGameState {
Over {
dealer_hand: Hand,
players: Vec<Player>,
},
Playing {
dealer_upcard: Card,
player_turn: usize,
hand_turn: usize,
players: Vec<Player>,
},
Starting,
}
fn gamestate_as_json(game: &BlackjackGame) -> ExtendedGameState {
match game.get_state() {
GameState::Starting => ExtendedGameState::Starting,
GameState::Over => ExtendedGameState::Over {
dealer_hand: game.get_dealer_hand().clone(),
players: game.get_players().clone(),
},
GameState::PlayerTurn {
player_index,
hand_index,
} => ExtendedGameState::Playing {
dealer_upcard: *game.get_dealer_upcard().unwrap(),
player_turn: *player_index,
hand_turn: *hand_index,
players: game.get_players().clone(),
},
}
}
pub fn build() -> Rocket<Build> {
let state = MyState {
game: Mutex::new(BlackjackGame::new()),
};
rocket::build()
.manage(state)
.mount("/api", routes![get_state, post_move])
}

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

12
frontend/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blackjack</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

2898
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

24
frontend/package.json Normal file
View File

@@ -0,0 +1,24 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^3.0.2",
"@tsconfig/svelte": "^5.0.2",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.38",
"svelte": "^4.2.12",
"svelte-check": "^3.6.7",
"tailwindcss": "^3.4.3",
"tslib": "^2.6.2",
"typescript": "^5.2.2",
"vite": "^5.2.0"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

9
frontend/src/App.svelte Normal file
View File

@@ -0,0 +1,9 @@
<script lang="ts">
import Blackjack from "./lib/Blackjack.svelte";
</script>
<main>
<Blackjack/>
</main>

View File

@@ -0,0 +1,15 @@
import type { Action } from "../types/Action";
import type { Gamestate } from "../types/Gamestate";
export async function doAction(action: Action): Promise<Gamestate> {
let res = await fetch("/api/state", {
method: "POST",
body: JSON.stringify(action),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
});
return await res.json();
}

View File

@@ -0,0 +1,6 @@
import type { Gamestate } from "../types/Gamestate";
export async function fetchState(): Promise<Gamestate>{
let res = await fetch("/api/state");
return await res.json();
}

7
frontend/src/index.css Normal file
View File

@@ -0,0 +1,7 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
@apply bg-blue-950 text-white;
}

View File

@@ -0,0 +1,74 @@
<script lang="ts">
import { onMount } from "svelte";
import { doAction } from "../functions/doAction";
import type { Action } from "../types/Action";
import type { Gamestate } from "./../types/Gamestate";
import { fetchState } from "../functions/fetchState";
import Card from "./Card.svelte";
import PlayerHand from "./PlayerHand.svelte";
let state: Gamestate;
onMount(async () => {
state = await fetchState();
});
async function actionBtn(action: Action) {
state = await doAction(action);
}
</script>
{#if state}
{#if state.type == "starting"}
Game has not yet started. Press "Deal" to start.
{:else if state.type == "over"}
Game over. Press "Deal" to start again.
<br>
Player:
{#each state.players as player}
{#each player.hands as hand}
<PlayerHand playingHand={hand}/>
{/each}
{/each}
{:else if state.type == "playing"}
Dealer: <Card card={state.dealerUpcard} />
Player:
{#each state.players as player}
{#each player.hands as hand}
<PlayerHand playingHand={hand}/>
{/each}
{/each}
{/if}
{:else}
Loading...
{/if}
<div>
<button
class="action-btn bg-blue-700 hover:bg-blue-600"
on:click={() => actionBtn({ type: "Deal", players: 1 })}>Deal</button
>
<button
class="action-btn bg-green-700 hover:bg-green-600"
on:click={() => actionBtn({ type: "Hit" })}>Hit</button
>
<button
class="action-btn bg-red-700 hover:bg-red-600"
on:click={() => actionBtn({ type: "Stand" })}>Stand</button
>
<button
class="action-btn bg-orange-700 hover:bg-orange-600"
on:click={() => actionBtn({ type: "DoubleDown" })}>Double down</button
>
<button
class="action-btn bg-cyan-700 hover:bg-cyan-600"
on:click={() => actionBtn({ type: "Split" })}>Split</button
>
</div>
<style>
.action-btn {
@apply py-2 px-4 rounded text-white;
}
</style>

View File

@@ -0,0 +1,10 @@
<script lang="ts">
import type { Card } from "../types/Card";
export let card: Card;
console.debug(card);
</script>
<div class="w-32 h-36 bg-slate-400 m-1 p-2">
{card.index} of {card.suit}
</div>

View File

@@ -0,0 +1,11 @@
<script lang="ts">
import type { PlayingHand } from "../types/Gamestate";
import Card from "./Card.svelte";
export let playingHand: PlayingHand;
</script>
{#each playingHand.hand as hand}
<Card card={hand}/>
{/each}

8
frontend/src/main.ts Normal file
View File

@@ -0,0 +1,8 @@
import "./index.css"
import App from './App.svelte'
const app = new App({
target: document.getElementById('app')!,
})
export default app

View File

@@ -0,0 +1,22 @@
export interface Deal {
type: "Deal",
players: Number
}
export interface Hit {
type: "Hit"
}
export interface Stand {
type: "Stand"
}
export interface DoubleDown{
type: "DoubleDown"
}
export interface Split {
type: "Split"
}
export type Action = Deal | Hit | Stand | DoubleDown | Split;

View File

@@ -0,0 +1,7 @@
import type { CardIndex } from "./CardIndex";
import type { CardSuit } from "./CardSuit";
export interface Card {
suit: CardSuit,
index: CardIndex,
}

View File

@@ -0,0 +1,15 @@
export enum CardIndex {
A = "A",
K = "K",
Q = "Q",
J = "J",
N10 = "N10",
N9 = "N9",
N8 = "N8",
N7 = "N7",
N6 = "N6",
N5 = "N5",
N4 = "N4",
N3 = "N3",
N2 = "N2",
}

View File

@@ -0,0 +1,6 @@
export enum CardSuit {
Spades = "S",
Clubs = "C",
Hearts = "H",
Diamonds = "D",
}

View File

@@ -0,0 +1,37 @@
import type { Card } from "./Card";
export interface Player {
hands: [PlayingHand]
}
export enum PlayingHandState {
Playing = "Playing",
Standing = "Standing",
DoubleDown = "DoubleDown",
Busted = "Busted",
Blackjack = "Blackjack",
Maxed = "Maxed",
}
export interface PlayingHand {
state: PlayingHandState,
hand: [Card]
}
export interface Over {
type: "over",
dealerHand: [Card],
players: [Player],
}
export interface Starting {
type: "starting",
}
export interface Playing {
type: "playing",
dealerUpcard: Card,
players: [Player],
}
export type Gamestate = Over | Starting | Playing;

2
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />

View File

@@ -0,0 +1,7 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
export default {
// Consult https://svelte.dev/docs#compile-time-svelte-preprocess
// for more information about preprocessors
preprocess: vitePreprocess(),
}

View File

@@ -0,0 +1,12 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx,svelte}",
],
theme: {
extend: {},
},
plugins: [],
}

20
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,20 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"resolveJsonModule": true,
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable checkJs if you'd like to use dynamic types in JS.
* Note that setting allowJs false does not prevent the use
* of JS in `.svelte` files.
*/
"allowJs": true,
"checkJs": true,
"isolatedModules": true
},
"include": ["src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true
},
"include": ["vite.config.ts"]
}

12
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,12 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte()],
server: {
proxy: {
"/api" : "http://127.0.0.1:8000"
}
}
})

View File

@@ -1,19 +0,0 @@
#![allow(dead_code)]
use std::error::Error;
use console_blackjack::play;
use crate::{card_index::CardIndex, card_suit::CardSuit};
mod blackjack;
mod card;
mod card_index;
mod card_suit;
mod console_blackjack;
mod decks;
mod hand;
fn main() -> Result<(), Box<dyn Error>> {
play()
}