diff options
| author | historia <[not public]> | 2026-10-05 14:22:14 -0400 |
|---|---|---|
| committer | historia <[not public]> | 2026-10-05 14:22:14 -0400 |
| commit | 90ad8c0c33b519d5830c69d4128bdc984b5e9de8 (patch) | |
| tree | c10bc0bebfbed6fde01a7f08cf6e2d98809b91a7 /internal/game | |
| parent | c84a9944356f590d90d819d652bdf1349ebacd40 (diff) | |
| download | thehouseoficarus-90ad8c0c33b519d5830c69d4128bdc984b5e9de8.tar.gz | |
feat: cryptocurrency exchange added to casino
Diffstat (limited to 'internal/game')
| -rw-r--r-- | internal/game/cmd_bank.go | 30 | ||||
| -rw-r--r-- | internal/game/cmd_look.go | 9 | ||||
| -rw-r--r-- | internal/game/cmd_registry.go | 3 | ||||
| -rw-r--r-- | internal/game/cmd_use.go | 4 | ||||
| -rw-r--r-- | internal/game/cmd_verbs.go | 4 | ||||
| -rw-r--r-- | internal/game/crypto.go | 681 | ||||
| -rw-r--r-- | internal/game/crypto_test.go | 384 | ||||
| -rw-r--r-- | internal/game/crypto_ux_test.go | 147 | ||||
| -rw-r--r-- | internal/game/game.go | 4 | ||||
| -rw-r--r-- | internal/game/prediction_interface.go | 1 | ||||
| -rw-r--r-- | internal/game/render_crypto.go | 63 |
11 files changed, 1324 insertions, 6 deletions
diff --git a/internal/game/cmd_bank.go b/internal/game/cmd_bank.go index deddf0b..15ce85f 100644 --- a/internal/game/cmd_bank.go +++ b/internal/game/cmd_bank.go @@ -102,6 +102,9 @@ func (g *Game) showBankBrowse(sess *net.Session) { entries = append(entries, bankEntry{slot: i, pos: len(entries) + 1, name: itemName, id: slot.ItemID, qty: slot.Quantity}) } + if p.Crypto.Balance < 0 { + sess.WriteLine(g.colorize(sess, "casino_result_loss", fmt.Sprintf("Crypto Exchange debt: %d credits. Future credit deposits repay this first.", -p.Crypto.Balance))) + } if len(entries) == 0 && p.BankedCredits <= 0 { sess.WriteLine("Your bank is empty.") return @@ -372,13 +375,26 @@ func (g *Game) doBankDepositCredits(sess *net.Session, parts []string) { sess.WriteLine("You don't have that many credits.") return } - creditsBefore, bankedBefore := p.Credits, p.BankedCredits - p.Credits -= amount - p.BankedCredits += amount - if !g.persistBankCredits(p, creditsBefore, bankedBefore) { + var seized int64 + if err := g.cryptoTransaction(p, func() error { + // Seize from the incoming deposit before the bank cap check. This also + // permits repayment when the bank itself is already at the balance cap. + seized = min(int64(amount), max(int64(0), -p.Crypto.Balance)) + bank, err := addCreditsChecked(p.BankedCredits, amount-int(seized)) + if err != nil { + return err + } + p.Credits -= amount + p.BankedCredits = bank + p.Crypto.Balance += seized + return nil + }); err != nil { sess.WriteLine("The bank terminal could not record the transfer; nothing was moved.") return } + if seized > 0 { + sess.WriteLine(fmt.Sprintf("The Crypto Exchange seized %d deposited credits to repay debt.", seized)) + } sess.WriteLine(g.colorize(sess, "currency_pickup", fmt.Sprintf("You deposit %s credits. (Banked: %s)", formatInt(amount), formatInt(p.BankedCredits)))) g.showBankBrowse(sess) } @@ -394,6 +410,10 @@ func (g *Game) doBankWithdrawCredits(sess *net.Session, parts []string) { sess.WriteLine("Invalid amount.") return } + if p.Crypto.Balance < 0 { + sess.WriteLine("Your bank credits are subject to Crypto Exchange debt. Repay the debt before withdrawing.") + return + } if p.BankedCredits < amount { sess.WriteLine("You don't have that many banked credits.") return @@ -421,7 +441,7 @@ func (g *Game) doBankWithdrawCredits(sess *net.Session, parts []string) { // a wager taken from that phantom balance would be charged against money the // player does not durably have. Reports whether the move may be announced. func (g *Game) persistBankCredits(p *player.Player, creditsBefore, bankedBefore int) bool { - if err := g.AccountStore.SaveCharacter(p); err != nil { + if err := (casinoWallet{g: g, p: p}).save("bank credit transfer"); err != nil { log.Printf("bank credit transfer %s: %v", p.Name, err) p.Credits = creditsBefore p.BankedCredits = bankedBefore diff --git a/internal/game/cmd_look.go b/internal/game/cmd_look.go index ab01c4c..92aeea6 100644 --- a/internal/game/cmd_look.go +++ b/internal/game/cmd_look.go @@ -65,6 +65,15 @@ func (g *Game) doLook(sess *net.Session) { // Seated at a table: look keeps its room-first order, then appends the // live game state and the current hint menu. g.showCasinoGameLook(sess, p, room) + if sess.CryptoActive && room.CryptoExchange { + sess.CryptoShowHints = true + if sess.CryptoBusy { + sess.WriteLine("Updating crypto quotes...") + g.cryptoHints(sess) + } else { + g.executeCrypto(sess, "refresh", nil) + } + } if sess.PredictionActive && room.PredictionExchange { sess.WriteLine("") if sess.PredictionBusy { diff --git a/internal/game/cmd_registry.go b/internal/game/cmd_registry.go index abc1539..d10ba0e 100644 --- a/internal/game/cmd_registry.go +++ b/internal/game/cmd_registry.go @@ -398,6 +398,9 @@ func (g *Game) executeCommand(sess *net.Session, cmd string, args []string, rawI } } + if g.handleCryptoInput(sess, cmd, args) { + return + } if g.handlePredictionInput(sess, cmd, args) { return } diff --git a/internal/game/cmd_use.go b/internal/game/cmd_use.go index 54a36f5..af60204 100644 --- a/internal/game/cmd_use.go +++ b/internal/game/cmd_use.go @@ -31,6 +31,10 @@ func (g *Game) doUse(sess *net.Session, input string) { lower := strings.ToLower(strings.TrimSpace(input)) + if cryptoUseTarget(lower) && g.atCryptoCounter(p) { + g.openCryptoCounter(sess) + return + } if predictionUseTarget(lower) && g.atPredictionCounter(p) { g.openPredictionCounter(sess) return diff --git a/internal/game/cmd_verbs.go b/internal/game/cmd_verbs.go index 87e8ee0..b5b0c3d 100644 --- a/internal/game/cmd_verbs.go +++ b/internal/game/cmd_verbs.go @@ -191,6 +191,10 @@ func (g *Game) collectRoomCommands(sess *net.Session) roomCommandSections { func (g *Game) executeVerbs(sess *net.Session, args []string, rawInput string) { p := sess.Player + if sess.CryptoActive && g.atCryptoCounter(p) { + g.showCasinoHints(sess, g.cryptoCommands(sess)) + return + } if sess.PredictionActive && g.atPredictionCounter(p) { g.showCasinoHints(sess, g.predictionCommands(sess)) return diff --git a/internal/game/crypto.go b/internal/game/crypto.go new file mode 100644 index 0000000..08a6b64 --- /dev/null +++ b/internal/game/crypto.go @@ -0,0 +1,681 @@ +package game + +import ( + "context" + "fmt" + "sort" + "strconv" + "strings" + "time" + + "thehouseoficarus/internal/cryptomarket" + "thehouseoficarus/internal/net" + "thehouseoficarus/internal/player" +) + +func cryptoUseTarget(s string) bool { + switch s { + case "crypto", "cryptocurrency", "crypto exchange": + return true + } + return false +} +func (g *Game) atCryptoCounter(p *player.Player) bool { + if p == nil || g.World == nil { + return false + } + r, e := g.World.LoadRoom(p.RoomID) + return e == nil && r.CryptoExchange +} +func (g *Game) openCryptoCounter(s *net.Session) { + if !g.atCryptoCounter(s.Player) { + s.WriteLine("There is no Crypto Exchange here.") + return + } + if s.CryptoActive { + s.CryptoShowHints = true + g.executeCrypto(s, "refresh", nil) + return + } + if !g.leaveCasinoGames(s.Player) { + s.WriteLine("Finish your casino round first.") + return + } + g.closePredictionCounter(s) + g.closeCryptoCounter(s) + s.CryptoActive = true + s.CryptoShowHints = true + g.executeCrypto(s, "markets", nil) +} +func (g *Game) closeCryptoCounter(s *net.Session) { + if s.CryptoCancel != nil { + s.CryptoCancel() + s.CryptoCancel = nil + } + s.CryptoActive = false + s.CryptoBusy = false + s.CryptoEpoch++ + s.CryptoSelected = "" + s.CryptoScreen = "markets" + s.CryptoShowHints = false + s.CryptoUnavailable = false +} + +// cryptoVerbs is the counter's own vocabulary. Exact matches win, and unique +// prefixes are accepted just like every other casino and counter interface. +// Real world commands keep their meaning unless the counter explicitly owns +// them (buy, sell, option, close, rules and help are claimed on the counter). +var cryptoVerbs = []string{ + "markets", "view", "buy", "sell", "short", "cover", "option", "write", + "quote", "contracts", "close", "active", "portfolio", "closed", "fund", + "withdraw", "repay", "refresh", "back", "help", "rules", "stop", "leave", "exit", +} + +func cryptoVerb(cmd string) (string, bool) { + for _, v := range cryptoVerbs { + if cmd == v { + return v, true + } + } + if _, exists := commandRegistry[cmd]; exists { + return "", false + } + found := "" + for _, v := range cryptoVerbs { + if strings.HasPrefix(v, cmd) { + if found != "" { + return "", true + } + found = v + } + } + return found, found != "" +} +func (g *Game) cryptoInputOwned(s *net.Session, cmd string) bool { + if !s.CryptoActive || !g.atCryptoCounter(s.Player) { + return false + } + _, ok := cryptoVerb(cmd) + return ok +} +func (g *Game) handleCryptoInput(s *net.Session, cmd string, args []string) bool { + if !s.CryptoActive { + return false + } + if !g.atCryptoCounter(s.Player) { + g.closeCryptoCounter(s) + return false + } + if cmd == "help" && len(args) > 0 { + return false + } + verb, owned := cryptoVerb(cmd) + if !owned { + if cmd == "use" && cryptoUseTarget(strings.ToLower(strings.Join(args, " "))) { + return false + } + switch cmd { + case "use", "play", "bank", "quit", "logout": + g.closeCryptoCounter(s) + } + return false + } + if verb == "" { + s.WriteLine("That shortcut is ambiguous. Choose a command below.") + g.cryptoHints(s) + return true + } + // Keep the global option/options settings command reachable: only a + // real option trade (option call|put ...) belongs to the counter. The + // plural options command is the player's settings command, not ours. + if verb == "option" && !(len(args) > 0 && (args[0] == "call" || args[0] == "put")) { + return false + } + switch verb { + case "stop", "leave", "exit": + g.closeCryptoCounter(s) + s.WriteLine("You step away from the Crypto Exchange. Your positions stay open.") + case "help", "rules": + g.cryptoHelp(s) + default: + g.executeCrypto(s, verb, args) + } + return true +} +func (g *Game) cryptoHelp(s *net.Session) { + g.predictionFrame(s, "HOW TO TRADE", []string{ + "Fund your account, choose a currency, then buy coins or back a falling price with a short.", + "Try: fund 1000, view BTC, buy BTC 0.001. Sell a position with close ID.", + "Options let you bet on a price by a future date. Use quote to check the price first.", + "Shorts and written options can leave debts. The exchange collects these from your bank and future deposits.", + "Your positions are checked when you return, not while you are away. See help crypto for details.", + }) + g.cryptoHints(s, true) +} + +// A transaction snapshots only the fields it owns. Money and ledger always +// share one atomic save, including bank garnishment; uncertain renames remain +// applied using the existing casino persistence contract. +func (g *Game) cryptoTransaction(p *player.Player, mutate func() error) error { + before := p.Crypto.Clone() + credits, bank := p.Credits, p.BankedCredits + rollback := func() { p.Crypto = before; p.Credits = credits; p.BankedCredits = bank } + if e := p.Crypto.Validate(); e != nil { + return e + } + if e := mutate(); e != nil { + rollback() + return e + } + p.Crypto.SweepBank(&p.BankedCredits) + if e := p.Crypto.Validate(); e != nil { + rollback() + return e + } + if e := (casinoWallet{g: g, p: p}).save("crypto exchange"); e != nil { + rollback() + return fmt.Errorf("exchange could not save; balances unchanged: %w", e) + } + return nil +} +func (g *Game) reconcileCrypto(p *player.Player, snap cryptomarket.Snapshot, now time.Time) ([]string, error) { + work := p.Crypto.Clone() + messages, e := work.Reconcile(snap, now) + if e != nil { + return nil, e + } + bank := p.BankedCredits + paid := work.SweepBank(&bank) + if len(messages) == 0 && paid == 0 { + return nil, nil + } + e = g.cryptoTransaction(p, func() error { p.Crypto = work; p.BankedCredits = bank; return nil }) + if e != nil { + return nil, e + } + if paid > 0 { + messages = append(messages, fmt.Sprintf("The Crypto Exchange collected %d bank credits against debt.", paid)) + } + return messages, nil +} +func (g *Game) cryptoFunds(s *net.Session, action string, args []string, verified ...cryptomarket.Snapshot) { + if len(args) != 1 { + s.WriteLine(action + " CREDITS") + return + } + n, e := strconv.ParseInt(args[0], 10, 64) + if e != nil || n <= 0 || n > cryptomarket.MaxMoney { + s.WriteLine("Enter a positive whole-credit amount within the economy limit.") + return + } + p := s.Player + e = g.cryptoTransaction(p, func() error { + p.Crypto.SweepBank(&p.BankedCredits) + switch action { + case "fund", "repay": + if action == "repay" && (p.Crypto.Balance >= 0 || n > -p.Crypto.Balance) { + return fmt.Errorf("repay at most the outstanding exchange debt") + } + if int64(p.Credits) < n { + return fmt.Errorf("not enough carried credits") + } + balance, err := cryptomarket.Sum(p.Crypto.Balance, n) + if err != nil { + return err + } + p.Credits -= int(n) + p.Crypto.Balance = balance + case "withdraw": + if p.Crypto.Balance < n { + return fmt.Errorf("not enough available exchange cash") + } + // Only withdraw free cash, never collateral. Derivatives must have + // verified nonnegative close equity, even when a positive settlement + // is waiting for balance-cap room. Missing data cannot release cash. + for _, v := range p.Crypto.Positions { + if v.Status != "open" || (!v.Risky() && !v.Option()) { + continue + } + if len(verified) != 1 { + return fmt.Errorf("derivatives need current quotes before withdrawing") + } + expiry, _ := verified[0].Expiry(v.Symbol, v.Expiry) + value, err := cryptomarket.Value(v, verified[0].Quotes[v.Symbol], time.Now().UTC(), expiry) + if err != nil || value < 0 { + return fmt.Errorf("settle derivative liabilities before withdrawing; quote or expiry data may be unavailable") + } + } + v, err := addCreditsChecked(p.Credits, int(n)) + if err != nil { + return err + } + p.Credits = v + p.Crypto.Balance -= n + } + return nil + }) + if e != nil { + s.WriteLine(e.Error()) + return + } + g.cryptoBalance(s) +} +func (g *Game) cryptoBalance(s *net.Session) { + s.WriteLine(g.colorize(s, "casino_credits", fmt.Sprintf("Exchange cash: %d credits | Bank: %d | Carried: %d", s.Player.Crypto.Balance, s.Player.BankedCredits, s.Player.Credits))) + if s.Player.Crypto.Balance < 0 { + s.WriteLine(g.colorize(s, "casino_result_loss", "DEBT: future bank deposits will be seized until paid. Use repay CREDITS.")) + } +} + +func (g *Game) executeCrypto(s *net.Session, action string, args []string) { + if s.CryptoBusy { + s.WriteLine("Crypto quotes are updating; wait or stop.") + g.cryptoHints(s) + return + } + hintsHandled := false + defer func() { + if !hintsHandled { + g.cryptoHints(s) + } + }() + if action == "back" { + action = "markets" + args = nil + } + if action == "refresh" { + action = s.CryptoScreen + if action == "" { + action = "markets" + } + if action == "view" { + args = []string{s.CryptoSelected} + } + } + switch action { + case "fund", "repay": + g.cryptoFunds(s, action, args) + return + case "closed": + g.cryptoPortfolio(s, cryptomarket.Snapshot{}, true) + return + case "contracts": + g.cryptoOptions(s) + return + } + // Parse and reject malformed commands BEFORE making any HTTP requests. + symbol, kind, quantity, strike := "", "", "", "" + days := 0 + id := int64(0) + switch action { + case "withdraw": + if len(args) != 1 { + s.WriteLine("withdraw CREDITS") + return + } + n, err := strconv.ParseInt(args[0], 10, 64) + if err != nil || n <= 0 || n > cryptomarket.MaxMoney { + s.WriteLine("Enter a positive whole-credit amount within the economy limit.") + return + } + case "markets", "active", "portfolio": + if len(args) != 0 { + s.WriteLine("This command takes no arguments.") + return + } + case "view": + if len(args) != 1 { + s.WriteLine("view SYMBOL") + return + } + symbol = strings.ToUpper(args[0]) + case "buy", "short": + if len(args) != 2 { + s.WriteLine(action + " SYMBOL QUANTITY") + return + } + symbol = strings.ToUpper(args[0]) + quantity = args[1] + kind = "spot" + if action == "short" { + kind = "short" + } + case "option", "write", "quote": + validKind := len(args) > 0 && (args[0] == "call" || args[0] == "put" || (action == "quote" && (args[0] == "write-call" || args[0] == "write-put"))) + if len(args) != 5 || !validKind { + s.WriteLine(action + " call|put SYMBOL QUANTITY STRIKE DAYS") + return + } + kind = args[0] + if action == "write" { + kind = "write-" + kind + } + symbol = strings.ToUpper(args[1]) + quantity = args[2] + strike = args[3] + days, _ = strconv.Atoi(args[4]) + if days != 1 && days != 7 && days != 30 { + s.WriteLine("DAYS must be 1, 7 or 30.") + return + } + if _, e := cryptomarket.Decimal(strike); e != nil { + s.WriteLine(e.Error()) + return + } + case "sell", "cover", "close": + if len(args) != 1 { + s.WriteLine(action + " POSITION_ID") + return + } + id, _ = strconv.ParseInt(args[0], 10, 64) + found := false + for _, p := range s.Player.Crypto.Positions { + if p.ID == id && p.Status == "open" { + symbol = p.Symbol + found = true + if action == "cover" && p.Kind != "short" { + s.WriteLine("cover is for shorts; use close ID.") + return + } + } + } + if !found { + s.WriteLine("Choose an open position ID from active.") + return + } + default: + hintsHandled = true + g.cryptoHelp(s) + return + } + if symbol != "" { + if _, ok := cryptomarket.Find(symbol); !ok { + s.WriteLine("Supported currencies: BTC ETH SOL DOGE SHIB.") + return + } + } + if quantity != "" { + if _, e := cryptomarket.Decimal(quantity); e != nil { + s.WriteLine(e.Error()) + return + } + } + symbols := map[string]bool{} + for _, sym := range cryptomarket.Symbols(s.Player.Crypto) { + symbols[sym] = true + } + if symbol != "" { + symbols[symbol] = true + } + if action == "markets" { + for _, i := range cryptomarket.Instruments { + symbols[i.Symbol] = true + } + } + list := []string{} + for sym := range symbols { + list = append(list, sym) + } + sort.Strings(list) + if g.CryptoClient == nil { + g.CryptoClient = cryptomarket.NewClient() + } + client := g.CryptoClient + p, room, epoch := s.Player, s.Player.RoomID, s.CryptoEpoch + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second) + s.CryptoCancel = cancel + s.CryptoBusy = true + hintsHandled = true + s.WriteLine("Updating crypto quotes...") + work := func() { + defer cancel() + snap, fetchErr := client.Fetch(ctx, list) + if ctx.Err() != nil { + fetchErr = ctx.Err() + } + apply := func() { + if !s.CryptoActive || s.CryptoEpoch != epoch { + return + } + s.CryptoBusy = false + s.CryptoCancel = nil + if g.isShuttingDown() || s.Player != p || s.State() != net.StateGame || s.IsDisconnecting() || p.RoomID != room || !g.atCryptoCounter(p) { + return + } + if g.owner != nil && g.loggedInChars[p.Name] != s { + return + } + if g.owner != nil { + defer g.reprompt(s) + } + defer g.cryptoHints(s) + s.CryptoUnavailable = fetchErr != nil + if fetchErr != nil { + g.predictionFrame(s, "COUNTER CLOSED", []string{"Prices are unavailable. Try refresh in a moment.", "No trade was made. Your positions are unchanged."}) + g.cryptoBalance(s) + return + } + now := time.Now().UTC() + messages, e := g.reconcileCrypto(p, snap, now) + if e != nil { + s.WriteLine(e.Error()) + return + } + for _, m := range messages { + s.WriteLine(m) + } + switch action { + case "withdraw": + g.cryptoFunds(s, action, args, snap) + case "markets": + g.cryptoMarkets(s, snap) + case "view": + s.CryptoSelected = symbol + g.cryptoView(s, symbol, snap) + case "active", "portfolio": + g.cryptoPortfolio(s, snap, false) + case "quote": + preview := p.Crypto.Clone() + preview.Balance = cryptomarket.MaxMoney + receipt, err := preview.Open(symbol, kind, quantity, strike, days, snap.Quotes[symbol], now) + if err != nil { + s.WriteLine(err.Error()) + return + } + lines := []string{ + g.colorize(s, "casino_emphasis", fmt.Sprintf("%s %s x %s", kind, symbol, quantity)), + fmt.Sprintf("Debit %s | premium %s | collateral %s credits", + g.colorize(s, "casino_credits", strconv.FormatInt(receipt.Cost, 10)), + g.colorize(s, "casino_credits", strconv.FormatInt(receipt.Premium, 10)), + g.colorize(s, "casino_credits", strconv.FormatInt(receipt.Collateral, 10))), + fmt.Sprintf("Strike %s | expires %s UTC", strike, time.Unix(receipt.Expiry, 0).UTC().Format("2006-01-02")), + g.colorize(s, "casino_action", "No order placed. Actual execution reprices."), + } + g.predictionFrame(s, "INDICATIVE QUOTE", lines) + default: + var receipt cryptomarket.Position + e = g.cryptoTransaction(p, func() error { + if id > 0 { + var err error + receipt, err = p.Crypto.Close(id, snap, now, "closed") + return err + } + // No new risk while an expired contract lacks its settlement data. + for _, v := range p.Crypto.Positions { + if v.Status != "open" { + continue + } + if v.Option() && v.Expiry <= now.Unix() { + return fmt.Errorf("settlement data pending; new positions are paused") + } + if v.Risky() || v.Option() { + if _, err := cryptomarket.Value(v, snap.Quotes[v.Symbol], now, ""); err != nil { + return fmt.Errorf("existing derivative cannot be valued; new positions are paused") + } + } + } + var err error + receipt, err = p.Crypto.Open(symbol, kind, quantity, strike, days, snap.Quotes[symbol], now) + return err + }) + if e != nil { + s.WriteLine(e.Error()) + return + } + if id > 0 { + category, verb := "casino_result_push", "released" + if receipt.Proceeds > 0 { + category = "casino_result_win" + } else if receipt.Proceeds < 0 { + category, verb = "casino_result_loss", "charged" + } + s.WriteLine(g.colorize(s, category, fmt.Sprintf("Closed #%d: %+d credits %s to exchange cash.", receipt.ID, receipt.Proceeds, verb))) + } else { + s.WriteLine(fmt.Sprintf("Opened #%d %s %s %s; debited %d credits.", receipt.ID, receipt.Kind, g.colorize(s, "casino_emphasis", receipt.Symbol), receipt.Quantity, receipt.Cost)) + if receipt.Option() { + s.WriteLine(fmt.Sprintf("Strike %s; premium %d; expires %s UTC.", receipt.Strike, receipt.Premium, time.Unix(receipt.Expiry, 0).UTC().Format("2006-01-02 15:04"))) + } + } + g.cryptoBalance(s) + } + } + if g.owner == nil { + apply() + } else { + g.run(apply) + } + } + if g.owner == nil { + work() + } else { + go work() + } +} + +func (g *Game) cryptoMarkets(s *net.Session, snap cryptomarket.Snapshot) { + s.CryptoSelected = "" + s.CryptoScreen = "markets" + rows := [][]string{} + for _, i := range cryptomarket.Instruments { + q, ok := snap.Quotes[i.Symbol] + if !ok || q.Validate(time.Now()) != nil { + rows = append(rows, []string{ + g.colorize(s, "casino_emphasis", i.Symbol), + g.colorize(s, "casino_menu", "--"), + g.colorize(s, "casino_menu", "--"), + }) + continue + } + rows = append(rows, []string{ + g.colorize(s, "casino_emphasis", i.Symbol), + g.colorize(s, "casino_result_loss", q.Ask), + g.colorize(s, "casino_result_win", q.Bid), + }) + } + headers := []string{ + g.colorize(s, "casino_menu", "Currency"), + g.colorize(s, "casino_menu", "Buy"), + g.colorize(s, "casino_menu", "Sell"), + } + g.predictionTable(s, g.colorize(s, "casino_emphasis", "CRYPTO EXCHANGE"), headers, rows, 0) + g.cryptoBalance(s) +} +func (g *Game) cryptoView(s *net.Session, symbol string, snap cryptomarket.Snapshot) { + s.CryptoScreen = "view" + q, ok := snap.Quotes[symbol] + if ok { + s.WriteLine(fmt.Sprintf("%s / USD: bid %s | ask %s | fetched %s UTC", + g.colorize(s, "casino_emphasis", symbol), + g.colorize(s, "casino_result_win", q.Bid), + g.colorize(s, "casino_result_loss", q.Ask), + q.At.UTC().Format("15:04:05"))) + } else { + s.WriteLine(g.colorize(s, "casino_result_loss", symbol+": current quote unavailable")) + } + lines := cryptomarket.Chart(snap.Candles[symbol], predictionWidth(s)-4, s.Player.OptionBool("unicode"), func(text string, up bool) string { + key := "casino_result_loss" + if up { + key = "casino_result_win" + } + return g.colorize(s, key, text) + }) + g.predictionFrame(s, symbol+" DAILY CANDLES", lines) + g.cryptoBalance(s) +} +func (g *Game) cryptoPortfolio(s *net.Session, snap cryptomarket.Snapshot, closed bool) { + s.CryptoScreen = "active" + if closed { + s.CryptoScreen = "closed" + } + now := time.Now().UTC() + rows := [][]string{} + for _, p := range s.Player.Crypto.Positions { + if (p.Status != "open") != closed { + continue + } + desc := p.Kind + " " + p.Symbol + if p.Option() { + desc += " " + p.Strike + " " + time.Unix(p.Expiry, 0).UTC().Format("01-02") + } + if closed { + desc += " (" + p.Status + ")" + } + if p.Risky() { + desc += " [coll " + strconv.FormatInt(p.Collateral, 10) + "]" + } + value, valued := int64(0), false + if closed { + value, valued = p.Proceeds, true + } else { + expiry, _ := snap.Expiry(p.Symbol, p.Expiry) + if v, e := cryptomarket.Value(p, snap.Quotes[p.Symbol], now, expiry); e == nil { + value, valued = v, true + } + } + valueText, pnlText := g.colorize(s, "casino_menu", "n/a"), g.colorize(s, "casino_menu", "n/a") + if valued { + valueText = strconv.FormatInt(value, 10) + pl := value - p.Cost + category := "casino_result_push" + if pl > 0 { + category = "casino_result_win" + } else if pl < 0 { + category = "casino_result_loss" + } + pnlText = g.colorize(s, category, fmt.Sprintf("%+d", pl)) + } + rows = append(rows, []string{ + g.colorize(s, "casino_menu", strconv.FormatInt(p.ID, 10)), + g.colorize(s, "casino_emphasis", desc), + p.Quantity, + strconv.FormatInt(p.Cost, 10), + valueText, + pnlText, + }) + } + if len(rows) == 0 { + message := "No open positions. Use view SYMBOL to trade." + if closed { + message = "No completed trades yet." + } + g.predictionFrame(s, "CRYPTO PORTFOLIO", []string{message}) + g.cryptoBalance(s) + return + } + headers := []string{"#", "Position", "Qty", "Cost"} + title := "CRYPTO POSITIONS" + last := "P/L" + if closed { + headers = append(headers, "Released") + title, last = "CRYPTO TRADE HISTORY", "Net" + } else { + headers = append(headers, "Value") + } + headers = append(headers, last) + colored := make([]string, len(headers)) + for i, h := range headers { + colored[i] = g.colorize(s, "casino_menu", h) + } + g.predictionTable(s, g.colorize(s, "casino_emphasis", fmt.Sprintf("%s (%d)", title, len(rows))), colored, rows, 1) + g.cryptoBalance(s) +} diff --git a/internal/game/crypto_test.go b/internal/game/crypto_test.go new file mode 100644 index 0000000..0ad5786 --- /dev/null +++ b/internal/game/crypto_test.go @@ -0,0 +1,384 @@ +package game + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "thehouseoficarus/internal/cryptomarket" + "thehouseoficarus/internal/net" + "thehouseoficarus/internal/player" + "thehouseoficarus/internal/world" +) + +func cryptoFixture(t *testing.T) (*Game, *net.Session, *casinoTestConn) { + t.Helper() + g, s, c, _ := predictionFixture(t) + dir := t.TempDir() + if e := os.MkdirAll(filepath.Join(dir, "rooms"), 0755); e != nil { + t.Fatal(e) + } + if e := os.WriteFile(filepath.Join(dir, "rooms", "1.yaml"), []byte("name: Crypto\ncrypto_exchange: true\n"), 0644); e != nil { + t.Fatal(e) + } + g.World = world.New(dir) + s.CryptoActive = true + s.Player.Crypto.Balance = 1000 + return g, s, c +} +func gameCryptoSnapshot(price string) cryptomarket.Snapshot { + return cryptomarket.Snapshot{Quotes: map[string]cryptomarket.Quote{"BTC": {Bid: price, Ask: price, At: time.Now().UTC()}}, Candles: map[string][]cryptomarket.Candle{}} +} +func TestCryptoFundsSaveAndDebtDepositRecovery(t *testing.T) { + g, s, c := cryptoFixture(t) + p := s.Player + g.cryptoFunds(s, "fund", []string{"100"}) + if p.Credits != 9900 || p.Crypto.Balance != 1100 { + t.Fatal(p.Credits, p.Crypto) + } + g.cryptoFunds(s, "withdraw", []string{"50"}) + if p.Credits != 9950 || p.Crypto.Balance != 1050 { + t.Fatal(p.Credits, p.Crypto) + } + p.Crypto.Balance = -150 + p.BankedCredits = 0 + g.doBankDepositCredits(s, []string{"deposit", "credits", "100"}) + if p.Credits != 9850 || p.Crypto.Balance != -50 || p.BankedCredits != 0 { + t.Fatal(p.Credits, p.Crypto, p.BankedCredits) + } + if !strings.Contains(string(c.data), "seized 100") { + t.Fatal(c.data) + } + g.doBankDepositCredits(s, []string{"deposit", "credits", "100"}) + if p.Credits != 9750 || p.Crypto.Balance != 0 || p.BankedCredits != 50 { + t.Fatal(p.Credits, p.Crypto, p.BankedCredits) + } + loaded, e := g.AccountStore.LoadCharacter(p.Name) + if e != nil || loaded.Crypto.Balance != 0 || loaded.BankedCredits != 50 || loaded.Credits != 9750 { + t.Fatal(loaded, e) + } +} +func TestCryptoLiquidationBankAndPersistentNegativeBalance(t *testing.T) { + g, s, _ := cryptoFixture(t) + p := s.Player + p.Crypto.Balance = 100 + p.BankedCredits = 50 + q := gameCryptoSnapshot("100").Quotes["BTC"] + if _, e := p.Crypto.Open("BTC", "short", "1", "", 0, q, time.Now().UTC()); e != nil { + t.Fatal(e) + } + messages, e := g.reconcileCrypto(p, gameCryptoSnapshot("300"), time.Now().UTC()) + if e != nil || len(messages) != 2 { + t.Fatal(messages, e) + } + if p.Crypto.Balance != -50 || p.BankedCredits != 0 || p.Credits != 10000 { + t.Fatal(p.Crypto, p.BankedCredits, p.Credits) + } + loaded, e := g.AccountStore.LoadCharacter(p.Name) + if e != nil || loaded.Crypto.Balance != -50 || loaded.Crypto.Positions[0].Status != "liquidated" { + t.Fatal(loaded, e) + } + s.Player = loaded + g.cryptoFunds(s, "repay", []string{"50"}) + if loaded.Crypto.Balance != 0 || loaded.Credits != 9950 { + t.Fatal(loaded.Crypto, loaded.Credits) + } +} +func TestCryptoAtomicRollbackIncludingBankGarnishment(t *testing.T) { + g, s, _ := cryptoFixture(t) + p := s.Player + p.Crypto.Balance = 100 + p.BankedCredits = 50 + q := gameCryptoSnapshot("100").Quotes["BTC"] + if _, e := p.Crypto.Open("BTC", "short", "1", "", 0, q, time.Now().UTC()); e != nil { + t.Fatal(e) + } + before := p.Crypto.Clone() + bank, credits := p.BankedCredits, p.Credits + // Force failure before rename by putting a directory at the target path. + if e := os.Mkdir(g.AccountStore.CharPath(p.Name), 0700); e != nil { + t.Fatal(e) + } + if _, e := g.reconcileCrypto(p, gameCryptoSnapshot("300"), time.Now().UTC()); e == nil { + t.Fatal("save succeeded") + } + if !reflect.DeepEqual(before, p.Crypto) || bank != p.BankedCredits || credits != p.Credits { + t.Fatal("partial rollback") + } + p.Crypto = cryptomarket.Account{Balance: -100} + before = p.Crypto.Clone() + g.doBankDepositCredits(s, []string{"deposit", "credits", "100"}) + if !reflect.DeepEqual(before, p.Crypto) || p.Credits != credits || p.BankedCredits != bank { + t.Fatal("deposit rollback lost debt") + } +} +func TestCryptoWithdrawLocksAndBankCap(t *testing.T) { + g, s, c := cryptoFixture(t) + p := s.Player + q := gameCryptoSnapshot("100").Quotes["BTC"] + if _, e := p.Crypto.Open("BTC", "short", "1", "", 0, q, time.Now().UTC()); e != nil { + t.Fatal(e) + } + balance := p.Crypto.Balance + g.cryptoFunds(s, "withdraw", []string{"1"}) + if p.Crypto.Balance != balance || !strings.Contains(string(c.data), "derivatives") { + t.Fatal(c.data) + } + p.Crypto = cryptomarket.Account{Balance: -10} + p.BankedCredits = int(cryptomarket.MaxMoney) + before := p.Credits + g.doBankDepositCredits(s, []string{"deposit", "credits", "10"}) + if p.Crypto.Balance != 0 || p.BankedCredits != int(cryptomarket.MaxMoney) || p.Credits != before-10 { + t.Fatal("repayment at cap") + } + before = p.Credits + g.doBankDepositCredits(s, []string{"deposit", "credits", "1"}) + if p.Credits != before || p.BankedCredits != int(cryptomarket.MaxMoney) { + t.Fatal("bank overflow") + } +} +func TestCryptoInterfaceIsolationAndMovement(t *testing.T) { + g, s, c := cryptoFixture(t) + if !g.cryptoInputOwned(s, "short") || g.cryptoInputOwned(s, "north") || g.cryptoInputOwned(s, "look") { + t.Fatal("ownership") + } + g.handleCryptoInput(s, "buy", []string{"BTC", "NaN"}) + if !strings.Contains(string(c.data), "decimal") { + t.Fatal(c.data) + } + g.handleCryptoInput(s, "stop", nil) + if s.CryptoActive || g.cryptoInputOwned(s, "short") { + t.Fatal("stop") + } + s.CryptoActive = true + cancelled := false + s.CryptoCancel = func() { cancelled = true } + epoch := s.CryptoEpoch + h := net.NewHub() + h.EnterRoom(s, 2) + if s.CryptoActive || !cancelled || s.CryptoEpoch <= epoch { + t.Fatal("room change did not cancel") + } +} +func cryptoMockClient(t *testing.T, price string) *cryptomarket.Client { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + result := any(nil) + switch r.URL.Path { + case "/SystemStatus": + result = map[string]string{"status": "online"} + case "/AssetPairs": + m := map[string]any{} + for _, i := range cryptomarket.Instruments { + m[i.Key] = map[string]string{"status": "online"} + } + result = m + case "/Ticker": + m := map[string]any{} + for _, i := range cryptomarket.Instruments { + m[i.Key] = map[string]any{"a": []string{price}, "b": []string{price}} + } + result = m + case "/OHLC": + key := "" + for _, i := range cryptomarket.Instruments { + if i.Pair == r.URL.Query().Get("pair") { + key = i.Key + } + } + now := time.Now().UTC().Truncate(24 * time.Hour).Unix() + result = map[string]any{key: [][]any{{now - 172800, price, price, price, price, price, "1", 1}, {now - 86400, price, price, price, price, price, "1", 1}}} + default: + t.Errorf("unknown path %s", r.URL) + } + json.NewEncoder(w).Encode(map[string]any{"error": []string{}, "result": result}) + })) + t.Cleanup(srv.Close) + c := cryptomarket.NewClient() + c.Base = srv.URL + return c +} +func TestCryptoRevisitSettlesOnlyVisitorAndNoRepeatedDebt(t *testing.T) { + g, s, _ := cryptoFixture(t) + p := s.Player + p.Crypto.Balance = 100 + p.BankedCredits = 50 + q := gameCryptoSnapshot("100").Quotes["BTC"] + if _, e := p.Crypto.Open("BTC", "short", "1", "", 0, q, time.Now().UTC()); e != nil { + t.Fatal(e) + } + if e := g.AccountStore.SaveCharacter(p); e != nil { + t.Fatal(e) + } + // Another character's position is untouched when this player visits. + offline := player.New("bob") + offline.Crypto = p.Crypto.Clone() + if e := g.AccountStore.SaveCharacter(offline); e != nil { + t.Fatal(e) + } + g.CryptoClient = cryptoMockClient(t, "300") + g.doUse(s, "crypto") + loaded, e := g.AccountStore.LoadCharacter(p.Name) + if e != nil || loaded.Crypto.Balance != -50 || loaded.BankedCredits != 0 { + t.Fatal(loaded, e) + } + saved, e := g.AccountStore.LoadCharacter("bob") + if e != nil || !reflect.DeepEqual(saved.Crypto, offline.Crypto) { + t.Fatal("offline position changed", saved, e) + } + for _, system := range TickSystemOrder() { + if strings.Contains(strings.ToLower(system.Name), "crypto") { + t.Fatal("crypto background tick registered") + } + } + before := loaded.Crypto.Clone() + g.executeCrypto(s, "active", nil) + loaded, e = g.AccountStore.LoadCharacter(p.Name) + if e != nil || !reflect.DeepEqual(before, loaded.Crypto) { + t.Fatal("repeat debt", loaded, e) + } +} +func TestCryptoCommandsTradeAndRender(t *testing.T) { + g, s, c := cryptoFixture(t) + g.CryptoClient = cryptoMockClient(t, "100") + g.doUse(s, "crypto") + if !s.CryptoActive { + t.Fatal("use crypto did not open counter") + } + before := s.Player.Crypto.Clone() + g.executeCrypto(s, "quote", []string{"write-call", "BTC", "10", "100", "7"}) + if !reflect.DeepEqual(before, s.Player.Crypto) || !strings.Contains(string(c.data), "No order placed") { + t.Fatal("quote mutated ledger", string(c.data)) + } + g.executeCrypto(s, "buy", []string{"BTC", "1.005"}) + if len(s.Player.Crypto.Positions) != 1 || s.Player.Crypto.Balance != 899 { + t.Fatal(s.Player.Crypto, c.data) + } + g.executeCrypto(s, "view", []string{"BTC"}) + if !strings.Contains(string(c.data), "DAILY CANDLES") { + t.Fatal(c.data) + } + g.executeCrypto(s, "sell", []string{"1"}) + if s.Player.Crypto.Positions[0].Status != "closed" { + t.Fatal(c.data) + } + if s.Player.Crypto.Balance != 1000 { + t.Fatal(s.Player.Crypto) + } +} +func TestCryptoInteractionUsesLivePlayerNotOldFile(t *testing.T) { + g, s, _ := cryptoFixture(t) + p := s.Player + p.Crypto.Balance = 100 + q := gameCryptoSnapshot("100").Quotes["BTC"] + if _, e := p.Crypto.Open("BTC", "short", "1", "", 0, q, time.Now().UTC()); e != nil { + t.Fatal(e) + } + if e := g.AccountStore.SaveCharacter(p); e != nil { + t.Fatal(e) + } + p.Credits = 1234 + g.loggedInChars = map[string]*net.Session{p.Name: s} + g.CryptoClient = cryptoMockClient(t, "300") + g.executeCrypto(s, "active", nil) + loaded, e := g.AccountStore.LoadCharacter(p.Name) + if e != nil || loaded.Credits != 1234 || loaded.Crypto.Balance != -100 { + t.Fatal(loaded, e) + } +} +func TestCryptoAsyncMovementCancelsWithoutBlockingOwner(t *testing.T) { + g, s, _ := cryptoFixture(t) + started, release := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/SystemStatus" { + close(started) + <-release + json.NewEncoder(w).Encode(map[string]any{"error": []string{}, "result": map[string]string{"status": "online"}}) + return + } + w.WriteHeader(503) + })) + defer srv.Close() + g.CryptoClient = cryptomarket.NewClient() + g.CryptoClient.Base = srv.URL + g.owner = newOwner() + defer g.owner.stop() + g.loggedInChars = map[string]*net.Session{s.Player.Name: s} + g.run(func() { g.executeCrypto(s, "buy", []string{"BTC", "1"}) }) + select { + case <-started: + case <-time.After(time.Second): + close(release) + t.Fatal("fetch not started") + } + moved := make(chan struct{}) + go func() { g.run(func() { s.Player.RoomID = 2 }); close(moved) }() + select { + case <-moved: + case <-time.After(time.Second): + close(release) + t.Fatal("HTTP blocked owner") + } + close(release) + deadline := time.Now().Add(2 * time.Second) + for { + busy := true + g.run(func() { busy = s.CryptoBusy }) + if !busy { + break + } + if time.Now().After(deadline) { + t.Fatal("callback stalled") + } + time.Sleep(time.Millisecond) + } + g.run(func() { + if s.Player.Crypto.Balance != 1000 || len(s.Player.Crypto.Positions) != 0 { + t.Error("trade after movement") + } + }) +} +func TestCryptoVerifiedWithdrawDoesNotReleaseCollateral(t *testing.T) { + g, s, _ := cryptoFixture(t) + p := s.Player + snap := gameCryptoSnapshot("100") + if _, e := p.Crypto.Open("BTC", "short", "1", "", 0, snap.Quotes["BTC"], time.Now().UTC()); e != nil { + t.Fatal(e) + } + g.cryptoFunds(s, "withdraw", []string{"900"}, snap) + if p.Crypto.Balance != 0 || p.Crypto.Positions[0].Collateral != 100 || p.Credits != 10900 { + t.Fatal(p.Crypto, p.Credits) + } + g.cryptoFunds(s, "withdraw", []string{"1"}, snap) + if p.Crypto.Balance != 0 { + t.Fatal("withdrew collateral") + } +} +func TestCryptoSaveRoundTrip(t *testing.T) { + g, s, _ := cryptoFixture(t) + p := s.Player + p.Crypto.Balance = 100 + now := time.Now().UTC() + q := cryptomarket.Quote{Bid: "0.000006", Ask: "0.000006", At: now} + if _, e := p.Crypto.Open("SHIB", "spot", "10000000.123456789012345678", "", 0, q, now); e != nil { + t.Fatal(e) + } + if e := g.AccountStore.SaveCharacter(p); e != nil { + t.Fatal(e) + } + loaded, e := g.AccountStore.LoadCharacter(p.Name) + if e != nil || !reflect.DeepEqual(p.Crypto, loaded.Crypto) { + t.Fatal(loaded, e) + } + // Old characters without any crypto fields still have valid empty accounts. + old := player.New("old") + if e := old.Crypto.Validate(); e != nil { + t.Fatal(e) + } +} diff --git a/internal/game/crypto_ux_test.go b/internal/game/crypto_ux_test.go new file mode 100644 index 0000000..6ac4a57 --- /dev/null +++ b/internal/game/crypto_ux_test.go @@ -0,0 +1,147 @@ +package game + +import ( + "strings" + "testing" + + "thehouseoficarus/internal/casino" + "thehouseoficarus/internal/color" +) + +func TestCryptoEntryIsBoardAndSharedHintsNotRules(t *testing.T) { + g, s, conn := cryptoFixture(t) + g.CryptoClient = cryptoMockClient(t, "100") + g.doUse(s, "crypto") + out := string(conn.data) + for _, wanted := range []string{"CRYPTO EXCHANGE", "Currency", "Buy", "Sell", "BTC", "view SYMBOL", "fund CREDITS", "stop"} { + if !strings.Contains(out, wanted) { + t.Fatalf("missing %q: %s", wanted, out) + } + } + for _, unwanted := range []string{"HOW TO TRADE", "Paper trading only", "HOUSE-MODEL", "volatility", "collateral", "Black-Scholes", "0.5%", "10-credit", "1,000,000"} { + if strings.Contains(out, unwanted) { + t.Fatalf("entry dumped rules %q: %s", unwanted, out) + } + } + for _, line := range strings.Split(out, "\n") { + if color.VisibleLen(strings.TrimSuffix(line, "\r")) > 80 { + t.Fatalf("wide entry line: %q", line) + } + } +} +func TestCryptoHintPreferencesAndExplicitWhat(t *testing.T) { + for _, mode := range []string{"off", "once", "on"} { + t.Run(mode, func(t *testing.T) { + g, s, conn := cryptoFixture(t) + g.CryptoClient = cryptoMockClient(t, "100") + s.Player.Options["casino_hints"] = mode + g.doUse(s, "crypto") + if got := strings.Contains(string(conn.data), "view SYMBOL"); got != (mode != "off") { + t.Fatalf("entry hints %s: %s", mode, conn.data) + } + conn.data = nil + g.executeCrypto(s, "refresh", nil) + if got := strings.Contains(string(conn.data), "view SYMBOL"); got != (mode == "on") { + t.Fatalf("repeat hints %s: %s", mode, conn.data) + } + conn.data = nil + // Look marks the same ShowHints flag the prediction counter uses. + s.CryptoShowHints = true + g.executeCrypto(s, "refresh", nil) + if got := strings.Contains(string(conn.data), "view SYMBOL"); got != (mode != "off") { + t.Fatalf("look hints %s: %s", mode, conn.data) + } + conn.data = nil + g.handleGameCommand(s, "what") + if !strings.Contains(string(conn.data), "view SYMBOL") || strings.Contains(string(conn.data), "HOW TO TRADE") { + t.Fatalf("what did not show command menu: %s", conn.data) + } + if g.cryptoInputOwned(s, "what") || g.cryptoInputOwned(s, "verbs") || g.cryptoInputOwned(s, "north") { + t.Fatal("counter stole a world command") + } + }) + } +} +func TestCryptoContextMenusAndRefresh(t *testing.T) { + g, s, conn := cryptoFixture(t) + g.CryptoClient = cryptoMockClient(t, "100") + s.Player.Options["casino_hints"] = "on" + g.executeCrypto(s, "view", []string{"BTC"}) + if !strings.Contains(string(conn.data), "buy BTC AMOUNT") || !strings.Contains(string(conn.data), "contracts") { + t.Fatalf("missing currency hints: %s", conn.data) + } + conn.data = nil + g.executeCrypto(s, "contracts", nil) + if !strings.Contains(string(conn.data), "option TYPE BTC") || !strings.Contains(string(conn.data), "quote TYPE BTC") { + t.Fatalf("missing option hints: %s", conn.data) + } + conn.data = nil + g.executeCrypto(s, "active", nil) + g.executeCrypto(s, "refresh", nil) + if s.CryptoScreen != "active" || strings.Contains(string(conn.data), "DAILY CANDLES") || !strings.Contains(string(conn.data), "close ID") { + t.Fatalf("refresh left portfolio: %s", conn.data) + } + conn.data = nil + g.executeCrypto(s, "closed", nil) + g.executeCrypto(s, "refresh", nil) + if s.CryptoScreen != "closed" || strings.Contains(string(conn.data), "close ID") { + t.Fatalf("closed hints or refresh wrong: %s", conn.data) + } + conn.data = nil + g.executeCrypto(s, "back", nil) + if s.CryptoScreen != "markets" || !strings.Contains(string(conn.data), "view SYMBOL") { + t.Fatalf("back failed: %s", conn.data) + } + s.CryptoBusy = true + commands := g.cryptoCommands(s) + if len(commands) != 1 || commands[0] != (casino.MenuCommand{Command: "stop", Desc: "Leave and cancel the update"}) { + t.Fatal(commands) + } +} +func TestCryptoGlobalOptionCommandsStayReachable(t *testing.T) { + g, s, _ := cryptoFixture(t) + g.CryptoClient = cryptoMockClient(t, "100") + // The settings command is not claimed by the counter... + if g.cryptoInputOwned(s, "options") { + t.Fatal("counter stole the options settings command") + } + if g.handleCryptoInput(s, "option", nil) { + t.Fatal("bare option should fall through to settings") + } + // ...but a real option trade is claimed. + if !g.cryptoInputOwned(s, "option") { + t.Fatal("option trade should be owned") + } + if !g.handleCryptoInput(s, "option", []string{"call", "BTC", "0.01", "100", "7"}) { + t.Fatal("option trade was not handled") + } +} + +func TestCryptoCommandAbbreviations(t *testing.T) { + g, s, conn := cryptoFixture(t) + g.CryptoClient = cryptoMockClient(t, "100") + // Unique prefixes resolve like every other counter command. + if got, ok := cryptoVerb("mar"); !ok || got != "markets" { + t.Fatalf("mar -> %q, %v", got, ok) + } + if got, ok := cryptoVerb("opt"); !ok || got != "option" { + t.Fatalf("opt -> %q, %v", got, ok) + } + if !g.cryptoInputOwned(s, "mar") { + t.Fatal("mar should be owned") + } + // Ambiguous shortcuts are claimed and explained instead of running. + if got, ok := cryptoVerb("b"); !ok || got != "" { + t.Fatalf("b -> %q, %v", got, ok) + } + conn.data = nil + if !g.handleCryptoInput(s, "b", nil) || !strings.Contains(string(conn.data), "ambiguous") { + t.Fatalf("ambiguous shortcut: %s", conn.data) + } + // Real world commands still win over counter prefixes. + for _, cmd := range []string{"look", "north", "score", "inventory"} { + if got, ok := cryptoVerb(cmd); ok { + t.Fatalf("%s was claimed as %q", cmd, got) + } + } +} diff --git a/internal/game/game.go b/internal/game/game.go index 1ce89e5..0c550ae 100644 --- a/internal/game/game.go +++ b/internal/game/game.go @@ -15,6 +15,7 @@ import ( "thehouseoficarus/internal/casino" "thehouseoficarus/internal/combat" "thehouseoficarus/internal/config" + "thehouseoficarus/internal/cryptomarket" "thehouseoficarus/internal/engine" "thehouseoficarus/internal/game/hacking" "thehouseoficarus/internal/item" @@ -62,6 +63,7 @@ type Game struct { GlobalFlags *GlobalFlagStore Combat *combat.Tracker PredictionClient *prediction.Client + CryptoClient *cryptomarket.Client Casino *casino.Manager flagIndex *flagTriggerIndex queue *CommandQueue @@ -632,7 +634,7 @@ func (g *Game) handleGameCommand(sess *net.Session, input string) { cmd := parts[0] // Counter commands exist only while using the counter, before global prefixes. - if g.predictionInputOwned(sess, cmd) { + if g.cryptoInputOwned(sess, cmd) || g.predictionInputOwned(sess, cmd) { g.executeCommand(sess, cmd, parts[1:], input) g.writePrompt(sess) return diff --git a/internal/game/prediction_interface.go b/internal/game/prediction_interface.go index 2e37145..3281f2d 100644 --- a/internal/game/prediction_interface.go +++ b/internal/game/prediction_interface.go @@ -29,6 +29,7 @@ func (g *Game) openPredictionCounter(s *net.Session) { g.executePredictions(s, []string{"refresh"}, "") return } + g.closeCryptoCounter(s) s.PredictionActive = true s.PredictionEpoch++ s.PredictionBusy = false diff --git a/internal/game/render_crypto.go b/internal/game/render_crypto.go new file mode 100644 index 0000000..899f83b --- /dev/null +++ b/internal/game/render_crypto.go @@ -0,0 +1,63 @@ +package game + +import ( + "thehouseoficarus/internal/casino" + "thehouseoficarus/internal/net" +) + +// Use the same contextual command columns and casino_hints policy as the +// prediction counter and casino tables. Rules are opt-in, never an entry screen. +func (g *Game) cryptoCommands(s *net.Session) []casino.MenuCommand { + if s.CryptoBusy { + return []casino.MenuCommand{{Command: "stop", Desc: "Leave and cancel the update"}} + } + commands := []casino.MenuCommand{} + if !s.CryptoUnavailable { + symbol := s.CryptoSelected + if symbol == "" { + symbol = "SYMBOL" + } + switch s.CryptoScreen { + case "view": + commands = append(commands, + casino.MenuCommand{Command: "buy " + symbol + " AMOUNT", Desc: "Buy coins"}, + casino.MenuCommand{Command: "short " + symbol + " AMOUNT", Desc: "Back a falling price"}, + casino.MenuCommand{Command: "contracts", Desc: "Trade calls and puts"}, + casino.MenuCommand{Command: "back", Desc: "Return to the currencies"}) + case "contracts": + commands = append(commands, + casino.MenuCommand{Command: "quote TYPE " + symbol + " AMOUNT PRICE DAYS", Desc: "Preview a call, put, write-call or write-put"}, + casino.MenuCommand{Command: "option TYPE " + symbol + " AMOUNT PRICE DAYS", Desc: "Buy a call or put"}, + casino.MenuCommand{Command: "write TYPE " + symbol + " AMOUNT PRICE DAYS", Desc: "Write a call or put; risk of debt"}, + casino.MenuCommand{Command: "back", Desc: "Return to the currencies"}) + case "active": + commands = append(commands, casino.MenuCommand{Command: "close ID", Desc: "Close a whole position"}, casino.MenuCommand{Command: "view SYMBOL", Desc: "View a currency's chart"}) + default: + commands = append(commands, casino.MenuCommand{Command: "view SYMBOL", Desc: "Choose a currency"}) + } + commands = append(commands, casino.MenuCommand{Command: "active", Desc: "Your open positions"}, casino.MenuCommand{Command: "closed", Desc: "Your completed trades"}) + } + if s.Player.Crypto.Balance < 0 { + commands = append(commands, casino.MenuCommand{Command: "repay CREDITS", Desc: "Pay your exchange debt"}) + } else { + commands = append(commands, casino.MenuCommand{Command: "fund CREDITS", Desc: "Add trading funds"}, casino.MenuCommand{Command: "withdraw CREDITS", Desc: "Take out available credits"}) + } + return append(commands, casino.MenuCommand{Command: "rules", Desc: "How to trade"}, casino.MenuCommand{Command: "refresh", Desc: "Update this screen"}, casino.MenuCommand{Command: "stop", Desc: "Leave the counter"}) +} +func (g *Game) cryptoHints(s *net.Session, force ...bool) { + forced := len(force) > 0 && force[0] + show := g.casinoHintsVisible(s, &casino.MenuView{ShowHints: s.CryptoShowHints}) + s.CryptoShowHints = false + if !forced && !show { + return + } + s.WriteLine("") + s.WriteLine(g.renderCasinoCommands(s, "", "", g.cryptoCommands(s))) +} +func (g *Game) cryptoOptions(s *net.Session) { + s.CryptoScreen = "contracts" + g.predictionFrame(s, "OPTIONS", []string{ + "Choose a call for a rising price, or a put for a falling price. Preview with quote before buying or writing.", + "AMOUNT is coins, PRICE is your target, and DAYS is 1, 7 or 30. Writing options can leave you owing credits.", + }) +} |
