Skip to content

Commit

Permalink
Paying off debt with awards won in battles
Browse files Browse the repository at this point in the history
  • Loading branch information
Leonid Kozarin committed Apr 30, 2024
1 parent c754b7b commit 9a53a2c
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 9 deletions.
3 changes: 2 additions & 1 deletion locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ commands:
description: "Fight with your friend's dick!"
results:
start: "<b>%{name}</b> challenged the chat with a bet of <b>%{bet} cm</b>!"
finish: "The winner is <b>%{winner_name}</b>! His dick is now <b>%{winner_length} cm</b> long. The loser's one is <b>%{loser_length}</b>."
finish: "The winner is <b>%{winner_name}</b>! His dick is now <b>%{winner_length} cm</b> long. The loser's one is <b>%{loser_length}</b>.\nThe bet was <b>%{bet} cm</b>."
position:
winner: "<b>%{name}</b>'s position in the top is <b>%{pos}</b>."
loser: "<b>%{name}</b>'s position in the top is <b>%{pos}</b>."
withheld: "<b>%{payout} cm</b> were withheld from the winner to pay off the loan."
button: "Attack!"
errors:
no_args: "Call the command with a number of centimeters you're willing to bet."
Expand Down
3 changes: 2 additions & 1 deletion locales/ru.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ commands:
description: "Сражайся с пипирками друзей!"
results:
start: "<b>%{name}</b> бросил чату вызов со ставкой <b>%{bet} см</b>!"
finish: "Победитель — <b>%{winner_name}</b>! Его пипирик теперь равен <b>%{winner_length} см</b>, а проигравшего — <b>%{loser_length} см</b>."
finish: "Победитель — <b>%{winner_name}</b>! Его пипирик теперь равен <b>%{winner_length} см</b>, а проигравшего — <b>%{loser_length} см</b>.\nСтавка была <b>%{bet} см</b>."
position:
winner: "<b>%{name}</b> занимает <b>%{pos}</b> место в топе."
loser: "<b>%{name}</b> занимает <b>%{pos}</b> место в топе."
withheld: "<b>%{payout} см</b> было удержано с победителя для погашения задолженности."
button: "Атаковать!"
errors:
no_args: "Вызови команду с числом сантиметров, которые готов поставить."
Expand Down
8 changes: 4 additions & 4 deletions src/handlers/perks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Perk for HelpPussiesPerk {

let current_deepness = change_intent.current_length.abs()
.to_f64().expect("conversion is always Some");
let change = (self.coefficient * current_deepness).ceil() as i32;
let change = (self.coefficient * current_deepness).round() as i32;
AdditionalChange(change)
}

Expand Down Expand Up @@ -74,7 +74,7 @@ impl Perk for LoanPayoutPerk {

let payout = if change_intent.base_increment.is_positive() {
let base_increment = change_intent.base_increment as f32;
let payout = (base_increment * payout_coefficient).ceil() as u16;
let payout = (base_increment * payout_coefficient).round() as u16;
payout.min(debt)
} else {
0
Expand Down Expand Up @@ -153,12 +153,12 @@ mod test {
.debt;
assert_eq!(debt, 9);

assert_eq!(perk.apply(&dick_id, change_intent_positive_increment_small).await.0, -1);
assert_eq!(perk.apply(&dick_id, change_intent_positive_increment_small).await.0, 0);
assert_eq!(perk.apply(&dick_id, change_intent_negative_increment).await.0, 0);
let debt = loans.get_active_loan(USER_ID, &CHAT_ID_KIND)
.await.expect("couldn't fetch the active loan")
.expect("loan must be found")
.debt;
assert_eq!(debt, 8);
assert_eq!(debt, 9);
}
}
31 changes: 28 additions & 3 deletions src/handlers/pvp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use teloxide::types::{CallbackQuery, ChatId, ChosenInlineResult, InlineKeyboardB
use crate::handlers::{CallbackResult, ensure_lang_code, HandlerResult, reply_html, utils};
use crate::{metrics, repo};
use crate::config::{AppConfig, BattlesFeatureToggles};
use crate::repo::{ChatIdPartiality, Repositories};
use crate::repo::{ChatIdPartiality, GrowthResult, Repositories};

const CALLBACK_PREFIX: &str = "pvp:";

Expand Down Expand Up @@ -221,19 +221,28 @@ async fn pvp_impl_attack(p: BattleParams, initiator: UserId, acceptor: UserInfo,
let acceptor_uid = acceptor.clone().into();
let (winner, loser) = choose_winner(initiator, acceptor_uid);
let (loser_res, winner_res) = p.repos.dicks.move_length(&p.chat_id, loser, winner, bet).await?;

let (winner_res, withheld_part) = pay_for_loan_if_needed(&p, winner, bet).await
.inspect_err(|e| log::error!("couldn't pay for a loan from a battle award: {e}"))
.ok().flatten()
.map(|(res, withheld)| {
let withheld_part = format!("\n\n{}", t!("commands.pvp.results.withheld", locale = &p.lang_code, payout = withheld));
(res, withheld_part)
})
.unwrap_or((winner_res, String::default()));

let winner_info = get_user_info(&p.repos.users, winner, &acceptor).await?;
let loser_info = get_user_info(&p.repos.users, loser, &acceptor).await?;
let main_part = t!("commands.pvp.results.finish", locale = &p.lang_code,
winner_name = winner_info.name, winner_length = winner_res.new_length, loser_length = loser_res.new_length);
winner_name = winner_info.name, winner_length = winner_res.new_length, loser_length = loser_res.new_length, bet = bet);
let text = if let (Some(winner_pos), Some(loser_pos)) = (winner_res.pos_in_top, loser_res.pos_in_top) {
let winner_pos = t!("commands.pvp.results.position.winner", locale = &p.lang_code, name = winner_info.name, pos = winner_pos);
let loser_pos = t!("commands.pvp.results.position.loser", locale = &p.lang_code, name = loser_info.name, pos = loser_pos);
format!("{main_part}\n\n{winner_pos}\n{loser_pos}")
} else {
main_part
};
CallbackResult::EditMessage(text, None)
CallbackResult::EditMessage(format!("{text}{withheld_part}"), None)
} else if enough_acceptor {
let text = t!("commands.pvp.errors.not_enough.initiator", locale = &p.lang_code);
CallbackResult::EditMessage(text, None)
Expand Down Expand Up @@ -279,3 +288,19 @@ async fn get_user_info(users: &repo::Users, user_uid: UserId, acceptor: &UserInf
};
Ok(user)
}

async fn pay_for_loan_if_needed(p: &BattleParams, winner_id: UserId, award: u16) -> anyhow::Result<Option<(GrowthResult, u16)>> {
let chat_id_kind = p.chat_id.kind();
let loan = match p.repos.loans.get_active_loan(winner_id, &chat_id_kind).await? {
Some(loan) => loan,
None => return Ok(None)
};
let payout = (loan.payout_ratio * award as f32).round() as u16;
let payout = payout.min(loan.debt);

p.repos.loans.pay(winner_id, &chat_id_kind, payout).await?;

let withheld = -(payout as i32);
let growth_res = p.repos.dicks.create_or_grow(winner_id, &p.chat_id, withheld).await?;
Ok(Some((growth_res, payout)))
}

0 comments on commit 9a53a2c

Please sign in to comment.