Skip to content

Commit

Permalink
high/low roll + font
Browse files Browse the repository at this point in the history
  • Loading branch information
Powerock38 committed Sep 20, 2024
1 parent a6abb8b commit 65b9a80
Show file tree
Hide file tree
Showing 6 changed files with 116 additions and 57 deletions.
Binary file added assets/JqkasWild.ttf
Binary file not shown.
82 changes: 52 additions & 30 deletions src/combination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,22 @@ pub type DiceResult = u8;
#[derive(Resource)]
pub struct LastCombination {
pub combination: Combination,
pub enough: bool,
pub win: bool,
}

//TODO: 421 with more than 3 dices is easy to get
// add full house, 2 pairs, 1 pair, small straight
// high roll: all dices > 3, low roll < 3 Highest roll: > 6 (with special dices)
//TODO
// add full house (50/50 with at least a pair of each), 2 pairs, 1 pair, small straight
// Highest roll: > 6 (with special dices)

#[derive(PartialEq, Eq)]
#[repr(u8)]
pub enum Combination {
Any(Vec<DiceResult>) = 0,
Any(Vec<DiceResult>),
LowRoll(Vec<DiceResult>),
HighRoll(Vec<DiceResult>),
Straight(DiceResult, usize), // highest dice in the serie, length
Strike(DiceResult),
Ace(DiceResult), // can't be 1
FourTwoOne,
FourTwoOne(usize),
}

impl Combination {
Expand All @@ -49,19 +50,31 @@ impl Combination {

// 421
if results.contains(&4) && results.contains(&2) && results.contains(&1) {
return Combination::FourTwoOne;
return Combination::FourTwoOne(results.len());
}

// "High roll": all dices > 3
if results.iter().all(|&d| d > 3) {
return Combination::HighRoll(results);
}

// "Low roll": all dices < 3
if results.iter().all(|&d| d < 3) {
return Combination::LowRoll(results);
}

// Default to "Any" combination
Combination::Any(results)
}

pub fn score(&self) -> u8 {
pub fn score(&self) -> u32 {
match self {
Combination::FourTwoOne => 8,
Combination::FourTwoOne(len) => 10 * (3.0 / *len as f32) as u32,
Combination::Strike(dice) if *dice == 1 => 7,
Combination::Ace(dice) | Combination::Strike(dice) => *dice,
Combination::Straight(_, _) => 2,
Combination::Ace(dice) | Combination::Strike(dice) => (*dice).into(),
Combination::Straight(_, _) => 4,
Combination::HighRoll(_) => 3,
Combination::LowRoll(_) => 2,
Combination::Any(_) => 1,
}
}
Expand Down Expand Up @@ -103,24 +116,33 @@ impl Ord for Combination {

impl fmt::Display for Combination {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Combination::FourTwoOne => write!(f, "Four-Two-One!"),
Combination::Ace(dice) => write!(f, "{dice} Ace"),
Combination::Strike(dice) => write!(f, "{dice} Strike"),
Combination::Straight(dice, len) => write!(f, "Straight {}", {
(0..*len)
.rev()
.map(|i| (dice - i as u8).to_string())
.collect::<Vec<String>>()
.join(",")
}),
Combination::Any(dices) => {
write!(
f,
"{}",
write!(
f,
"{} [{}¢]",
match self {
Combination::FourTwoOne(_) => "Four-Two-One!".to_string(),
Combination::Ace(dice) => format!("{dice} Ace"),
Combination::Strike(dice) => format!("{dice} Strike"),
Combination::Straight(dice, len) => format!("Straight {}", {
(0..*len)
.rev()
.map(|i| (dice - i as u8).to_string())
.collect::<Vec<String>>()
.join(",")
}),
Combination::HighRoll(dices) => format!(
"High Roll {}",
dices.iter().map(ToString::to_string).collect::<String>()
)
}
}
),
Combination::LowRoll(dices) => format!(
"Low Roll {}",
dices.iter().map(ToString::to_string).collect::<String>()
),
Combination::Any(dices) => {
dices.iter().map(ToString::to_string).collect::<String>()
}
},
self.score()
)
}
}
18 changes: 10 additions & 8 deletions src/dice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,10 @@ pub fn analyze_dices(
last_combination: Option<Res<LastCombination>>,
mut tries: ResMut<Tries>,
to_beat: Res<ToBeat>,
collisions: Res<Collisions>,
q_table_parts: Query<Entity, With<TablePart>>,
q_dices_on_table: Query<
(&Dice, &Transform, &AngularVelocity, &LinearVelocity),
(Entity, &Dice, &Transform, &AngularVelocity, &LinearVelocity),
Without<InHand>,
>,
q_dices_in_hand: Query<(), (With<Dice>, With<InHand>)>,
Expand All @@ -155,9 +157,12 @@ pub fn analyze_dices(
let nb_dices_total = q_dices_on_table.iter().count() + q_dices_in_hand.iter().count();
let mut results = vec![];

for (dice, transform, angular_velocity, linear_velocity) in &q_dices_on_table {
for (entity, dice, transform, angular_velocity, linear_velocity) in &q_dices_on_table {
if linear_velocity.0.length() < MIN_MOVEMENT
&& angular_velocity.0.length() < MIN_MOVEMENT
&& q_table_parts
.iter()
.any(|table_part| collisions.contains(entity, table_part))
{
// Determine which face is most aligned with the world up vector
let mut max_dot = -1.0;
Expand Down Expand Up @@ -187,17 +192,14 @@ pub fn analyze_dices(
// Update the player's tries
tries.0 += 1;

let enough = combination >= to_beat.combination;
let win = to_beat.is_won(&combination);

if combination >= to_beat.combination || tries.0 >= to_beat.tries {
if win || tries.0 >= to_beat.tries {
commands.insert_resource(ToBeat::roll());
tries.0 = 0;
}

commands.insert_resource(LastCombination {
combination,
enough,
});
commands.insert_resource(LastCombination { combination, win });
}
}
}
Expand Down
48 changes: 47 additions & 1 deletion src/game.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use bevy::prelude::*;
use core::fmt;
use rand::prelude::*;

use crate::{combination::Combination, dice::NB_DICES};
Expand All @@ -10,6 +11,24 @@ pub struct Tries(pub u8);
pub struct ToBeat {
pub combination: Combination,
pub tries: u8,
challenge: ToBeatChallenge,
}

enum ToBeatChallenge {
HigherOrEqual,
Higher,
Equal,
}

impl ToBeatChallenge {
fn random() -> Self {
let mut rng = thread_rng();
match rng.gen_range(0..3) {
0 => Self::HigherOrEqual,
1 => Self::Higher,
_ => Self::Equal,
}
}
}

impl ToBeat {
Expand All @@ -34,6 +53,33 @@ impl ToBeat {
}
};

Self { combination, tries }
Self {
combination,
tries,
challenge: ToBeatChallenge::random(),
}
}

pub fn is_won(&self, combination: &Combination) -> bool {
match self.challenge {
ToBeatChallenge::HigherOrEqual => *combination >= self.combination,
ToBeatChallenge::Higher => *combination > self.combination,
ToBeatChallenge::Equal => *combination == self.combination,
}
}
}

impl fmt::Display for ToBeat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Score {}: {}",
match self.challenge {
ToBeatChallenge::HigherOrEqual => "higher or equal to",
ToBeatChallenge::Higher => "higher than",
ToBeatChallenge::Equal => "exactly",
},
self.combination,
)
}
}
13 changes: 1 addition & 12 deletions src/table.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use avian3d::prelude::*;
use bevy::{color::palettes::css::RED, prelude::*};

use crate::{
combination::LastCombination,
dice::{Dice, InHand},
};
use crate::dice::{Dice, InHand};

pub const TABLE_RADIUS: f32 = 10.0;
pub const TABLE_THICKNESS: f32 = 0.1;
Expand Down Expand Up @@ -60,27 +57,19 @@ pub fn setup(
}

pub fn punch_table(
mut commands: Commands,
button_input: Res<ButtonInput<MouseButton>>,
collisions: Res<Collisions>,
q_table_parts: Query<Entity, With<TablePart>>,
mut q_dices: Query<(Entity, &mut LinearVelocity), (With<Dice>, Without<InHand>)>,
) {
if button_input.just_pressed(MouseButton::Right) {
let mut moved = false;

for (entity, mut linear_velocity) in &mut q_dices {
if q_table_parts
.iter()
.any(|table_part| collisions.contains(entity, table_part))
{
linear_velocity.0 += Vec3::new(0.0, 5.0, 0.0);
moved = true;
}
}

if moved {
commands.remove_resource::<LastCombination>();
}
}
}
12 changes: 6 additions & 6 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ impl LastCombinationText {
#[derive(Component)]
struct ToBeatText;

fn setup_ui(mut commands: Commands) {
fn setup_ui(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn((
ToBeatText,
TextBundle::from_section(
"",
TextStyle {
font_size: 50.0,
font: assets_server.load("JqkasWild.ttf"),
..default()
},
),
Expand All @@ -33,6 +34,7 @@ fn setup_ui(mut commands: Commands) {
fn spawn_last_combination(
mut commands: Commands,
last_combination: Option<Res<LastCombination>>,
assets_server: Res<AssetServer>,
tries: Res<Tries>,
) {
if let Some(last_combination) = last_combination {
Expand All @@ -44,7 +46,7 @@ fn spawn_last_combination(
"{}\n{}",
last_combination.combination,
if tries.0 == 0 {
if last_combination.enough {
if last_combination.win {
"You win!"
} else {
"You lose!"
Expand All @@ -55,6 +57,7 @@ fn spawn_last_combination(
),
TextStyle {
font_size: 50.0,
font: assets_server.load("JqkasWild.ttf"),
..default()
},
)
Expand Down Expand Up @@ -88,10 +91,7 @@ fn update_to_beat(
let mut to_beat_text = q_to_beat_text.single_mut();

if to_beat.is_added() || to_beat.is_changed() || tries.is_added() || tries.is_changed() {
to_beat_text.sections[0].value = format!(
"Beat {} ({}/{})",
to_beat.combination, tries.0, to_beat.tries
);
to_beat_text.sections[0].value = format!("{}\n({}/{})", *to_beat, tries.0, to_beat.tries);
}
}

Expand Down

0 comments on commit 65b9a80

Please sign in to comment.