using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Fateforge { public sealed partial class Game { public static readonly string[] Symbols={"citron","pasteque","cloche","trefle","mime","clown","diamant","fer_a_cheval","lucky_7","couronne","crane","coffre_tresor","diable","pierre"}; public static readonly int[] Values={15,20,25,30,50,100,80,160,320,640,10,50,100,0}; public static readonly string[] Basics={"citron","pasteque","cloche","trefle","diamant","fer_a_cheval"}; public static readonly double[] Families={1.75,2,2.25}; public static readonly string[] Bosses={"flambeuse","gambler","plein_aux_as","sosie_elvis","croque_mort","cowboy_alcoolique","charlatan","mineur"}; public static readonly string[] Reference={"trefle","citron","mime","citron","citron","pasteque","citron","trefle","trefle","citron","trefle","trefle"}; public RunState State { get; private set; } public BoardState Board => State.board; public event Action Drawn; public List DealtCells=new List(); public int DealtWidth,DealtHeight; public readonly List Expansions=new List(); public string Boss => !State.endless ? State.bosses[State.level] ?? "" : State.level % 6 == 3 ? State.firstFloorBoss : State.level % 6 == 0 ? State.lastFloorBoss : ""; public long TotalScore => TotalScoreAt(Board.score); internal long TotalScoreAt(long levelScore) => AddScore(State.clearedScore, levelScore); static long AddScore(long a, long b) => b >= long.MaxValue - a ? long.MaxValue : a + b; public static readonly IReadOnlyList StartingTricks = Array.AsReadOnly(new[]{"swap","discard"}); public Game(RunState state) { State=state; if (!state.hasClearedScore) { // The current board still holds its final score throughout rewards and the shop. foreach (var entry in state.history.Where(entry => entry.level < state.level)) state.clearedScore = AddScore(state.clearedScore, entry.score); state.hasClearedScore = true; } if (!string.IsNullOrEmpty(Board.operation) && !StartingTricks.Contains(Board.operation)) EndOperation(); if (State.stage==Stage.LegacyPact) { State.pendingLevel=State.level+1; Route(); } if ((State.stage==Stage.Shop || State.stage==Stage.Purchase) && State.shop?.special.Count>1 && State.shop.special[1].kind=="trick") { var old=State.shop.special[1]; State.shop.special[1]=old.sold ? new Item{kind="empty",sold=true} : ElixirPack(); } } public static long Round(double n) { if (double.IsNaN(n)) return 0; if (n >= long.MaxValue) return long.MaxValue; return n <= long.MinValue ? long.MinValue : (long)Math.Floor(n+.5); } public static long Snap(double n) { if(n >= long.MaxValue)return long.MaxValue;double p=Math.Pow(10,Math.Floor(Math.Log10(Math.Max(1,n))-1));return Round(Round(n/p)*p); } public static int ValueOf(string symbol) { int i=Array.IndexOf(Symbols,symbol);return i<0?0:Values[i]; } public static double Random(ref uint state) { uint x=state;x^=x<<13;x^=x>>17;x^=x<<5;state=x;return x/4294967296d; } public double Next() => Random(ref State.random); public T Pick(IList a) => a.Count==0?default(T):a[(int)(Next()*a.Count)]; public List Sample(IEnumerable source,int count) { var a=source.ToList();var result=new List();while(a.Count>0&&result.Count State.cards.FirstOrDefault(x=>x.id==c.source); public string Sticker(Cell c) => State.disabledStickers.Contains(c.source)?null:Source(c)?.sticker; public double CardValue(Cell c) {int index=Array.IndexOf(Symbols,c.symbol);return Round((ValueOf(c.symbol)+(Source(c)?.growth??0))*(1+(index<0?0:State.symbolBoost[index]))*(State.debuff==c.symbol?.5:1));} public double FamilyMultiplier(int family) => (Families[family]+State.families[family]+State.ticketMultiplier)*(Boss=="plein_aux_as"?Math.Min(1,.25+State.richRestored):1); public void BeginLevel() { var s=State;s.stage=Stage.Battle;s.ticketMultiplier=s.richRestored=0;s.reprieved=false;s.debuff="";s.turn=0; double ratio=Boss=="flambeuse"?.5:Boss=="gambler"?1.5:Boss=="plein_aux_as"?1.25:Boss=="sosie_elvis"?.75:1; s.target=Snap(4000*Math.Pow(4,(s.level-1)/6)*(1+.5*((s.level-1)%6))*ratio*s.nextTarget);s.nextTarget=1; s.battleSpins=Boss=="gambler"?1:s.spins;s.disabledStickers=Boss=="charlatan"?s.cards.Select(c=>c.id).ToList():new List(); foreach(var m in s.magnets)if(m.id=="encens")m.bonus=200; s.board=new BoardState{width=Boss=="croque_mort"?5:4,energy=s.maxEnergy,random=s.random};Refill();Deal(); } public void Refill() { Board.stock=State.cards.Select(c=>new StockCard{symbol=c.symbol,source=c.id}).ToList(); for(int pass=0;pass<3;pass++)for(int i=Board.stock.Count-1;i>0;i--){int j=(int)(Random(ref Board.random)*(i+1));var tmp=Board.stock[i];Board.stock[i]=Board.stock[j];Board.stock[j]=tmp;} Board.generation++;NotifyDraw(null); } void NotifyDraw(string symbol) => Drawn?.Invoke(new DrawNotice{remaining=Board.stock.Count,generation=Board.generation,symbol=symbol,stock=Board.stock.Select(x=>new StockCard{source=x.source,symbol=x.symbol}).ToList()}); public Cell Draw(string exclude=null,string preferred=null) { if(Board.stock.Count==0)Refill();if(Board.stock.Count==0)throw new InvalidOperationException("Cannot draw from an empty deck composition."); int index=preferred!=null?Board.stock.FindIndex(x=>x.symbol==preferred):exclude!=null?Board.stock.FindLastIndex(x=>x.symbol!=exclude):Board.stock.Count-1; if(index<0&&preferred!=null)throw new InvalidOperationException("Requested card is not in stock: "+preferred);if(index<0)index=Board.stock.Count-1; var drawn=Board.stock[index];Board.stock.RemoveAt(index);Board.drawn++;NotifyDraw(drawn.symbol); var result=new Cell{id=Board.nextId++,source=drawn.source,symbol=drawn.symbol};if(Board.stock.Count==0)Refill();return result; } public void Deal() { EndOperation();Board.cells.Clear();for(int i=0;ix.kind=="ticket").ToList()).Copy()); if(Boss=="cowboy_alcoolique"){var roots=State.cards.Where(c=>Basics.Contains(c.symbol)).Select(c=>c.symbol).Distinct().ToList();if(roots.Count>1)roots.Remove(State.debuff);State.debuff=Pick(roots);} if(Boss=="mineur")foreach(int i in Sample(Enumerable.Range(0,Board.cells.Count).Where(i=>Board.cells[i].symbol!="pierre"),(int)Round(Board.cells.Count*.15)))Board.cells[i].symbol="pierre"; DealtCells=Board.cells.Select(c=>c.Copy()).ToList();DealtWidth=Board.width;DealtHeight=Board.height; ResolveScatters(); } public ExpansionNotice ExpandOnce() { var scatter=Board.cells.Select((c,i)=>new{c,i}).Where(x=>x.c.symbol=="clown").Select(x=>x.i).ToList();if(scatter.Count<3)return null; var e=new ExpansionNotice{fromWidth=Board.width,fromHeight=Board.height,before=Board.cells.Select(c=>c.Copy()).ToList()}; foreach(int i in scatter){Board.cells[i]=Draw("clown");e.entered.Add(Board.cells[i].id);} int w=Board.width,h=Board.height;if(w<6){if(w<5)w++;else if(h==3)h=4;else w=6;} var old=Board.cells;Board.cells=new List(); for(int y=0;yc.Copy()).ToList();foreach(var m in State.magnets)if(m.condition=="scatter")m.charge=1;return e; } public void ResolveScatters() {Expansions.Clear();for(int i=0;i<64;i++){var e=ExpandOnce();if(e==null)return;Expansions.Add(e);}throw new InvalidOperationException("Scatter resolution exceeded its safety limit.");} public static bool Adjacent(int a,int b,int width) => a!=b&&Math.Pow(a%width-b%width,2)+Math.Pow(a/width-b/width,2)<=2; public bool BeginTrick(string id) { if(State.stage!=Stage.Battle||!State.tricks.Contains(id))return false; if(Board.operation==id){EndOperation();return true;}if(Board.operation=="discard"||Board.energy<=0)return false; EndOperation();Board.operation=id;if(id=="discard")Board.eligible=Board.cells.Select(c=>c.id).ToList(); return true; } public void EndOperation() {Board.operation="";Board.selected=-1;Board.discardUsed=0;Board.eligible.Clear();} public bool CanDiscard(int index) => Board.operation=="discard"&&Board.discardUsed<2&&index>=0&&index=Board.cells.Count||Board.cells[index].symbol!="clown"||(Board.operation=="discard"&&!CanDiscard(index)))return false; Board.cells[index]=Draw();Board.selected=-1;ResolveScatters();return true; } public bool SelectCell(int index) { if(State.stage!=Stage.Battle||index<0||index>=Board.cells.Count)return false; if(Board.operation=="discard")return Discard(index);if(Board.energy<=0)return false; if(Board.operation!="swap")return false; if(Board.selected==index){Board.selected=-1;return true;}if(Board.selected<0){Board.selected=index;return true;} int first=Board.selected;if(Board.operation=="swap"&&!Adjacent(first,index,Board.width))return false; var cell=Board.cells[first];Board.cells[first]=Board.cells[index];Board.cells[index]=cell; Board.energy--;EndOperation();ResolveScatters();return true; } public static List Analyze(IList board,int width,int height) { var matches=new List();int[,] directions={{1,0},{0,1},{1,1},{-1,1}}; for(int d=0;d<4;d++){int family=Math.Min(d,2),dx=directions[d,0],dy=directions[d,1]; for(int length=3;length<=(family==0?width:height);length++)for(int y=0;y=width||endY>=height)continue; var cells=Enumerable.Range(0,length).Select(n=>(y+dy*n)*width+x+dx*n).ToList();var symbols=cells.Select(i=>board[i]).ToList(); if(symbols.Any(c=>string.IsNullOrEmpty(c)||c=="clown"||c=="pierre")||symbols.Where(c=>c!="mime").Distinct().Count()!=1)continue; matches.RemoveAll(m=>m.family==family&&m.cells.All(cells.Contains));matches.Add(new Match{family=family,cells=cells,multiplier=Families[family],points=symbols.Sum(ValueOf)}); }}return matches.OrderBy(m=>m.cells.Min()).ToList(); } public string MatchKey(Match m) => m.family+":"+string.Join(";",m.cells.Select(i=>(i%Board.width)+","+(i/Board.width)+","+Board.cells[i].symbol))+":"+m.points.ToString("R",CultureInfo.InvariantCulture)+":"+m.multiplier.ToString("R",CultureInfo.InvariantCulture); public ScoreResult Preview() { var result=new ScoreResult{matches=Analyze(Board.cells.Select(c=>c.symbol).ToList(),Board.width,Board.height)}; foreach(var m in result.matches){m.points=m.cells.Sum(i=>CardValue(Board.cells[i])*(Sticker(Board.cells[i])=="compte_double"?2:1));m.multiplier=FamilyMultiplier(m.family)*Math.Pow(2,m.cells.Count(i=>Sticker(Board.cells[i])=="super_carte"));m.key=MatchKey(m);} result.points=result.basePoints=result.matches.Sum(m=>m.points);result.multiplier=result.baseMultiplier=result.matches.Sum(m=>m.multiplier); result.perfect=result.matches.SelectMany(m=>m.cells).Distinct().Count()==Board.cells.Count;result.preview=Round(result.points*result.multiplier);result.total=Round(result.points*result.multiplier*(result.perfect?1.5:1));return result; } public bool MagnetReady(Item m,ScoreResult score) => m.charge>=1||m.condition=="symbol"&&score.matches.Any(match=>match.cells.Any(i=>Board.cells[i].symbol==m.symbol)&&match.cells.All(i=>Board.cells[i].symbol=="mime"||Board.cells[i].symbol==m.symbol)); public ScoreResult PlanSettlement() { var r=Preview();r.multiplier*=r.perfect?1.5:1; for(int i=0;ic.symbol).Distinct().Count()*.1;break; case "poisson_mort":r.multiplier*=1.3;break; case "scarabee":r.multiplier+=State.magnets.Count*.2;break; case "ticket_or":r.magnetCoins+=State.tickets.Count;break; case "pendule":r.multiplier*=Math.Pow(1.2,r.matches.Count(x=>x.cells.Count==4));break; case "oeil_de_verre":r.multiplier+=Math.Pow(.5,r.matches.Count);break; case "chevaliere":foreach(int cell in r.matches.SelectMany(x=>x.cells).Distinct())r.growth.Add(new GrowthChange{source=Board.cells[cell].source,amount=5});break; default:continue; }r.magnets.Add(new MagnetStep{index=i,id=m.id,points=r.points,multiplier=r.multiplier}); } r.total=Round(Math.Max(0,r.points)*Math.Max(0,r.multiplier));if(Boss=="sosie_elvis")r.total=Math.Min(r.total,Snap(State.target*1.2/State.spins));return r; } int CollectBonusCoins(ScoreResult result) { int goldCoins = result.matches.Sum(match => match.cells.Count(index => Sticker(Board.cells[index]) == "carte_doree")); return result.magnetCoins + goldCoins; } // The winning board and its settlement are saved together until the player continues. internal int CoinsBeforeJackpot => Math.Max(0, State.coins - State.reward.Total - CollectBonusCoins(State.settlement)); public ScoreResult Collect() { if(State.stage!=Stage.Battle)return null;EndOperation();var result=PlanSettlement();result.scoreBefore=Board.score;result.hasScoreSnapshot=true;State.settlement=result; foreach(var step in result.magnets){var m=State.magnets[step.index];m.charge=0;if(m.id=="encens")m.bonus-=25;} State.coins+=CollectBonusCoins(result);foreach(var change in result.growth){var card=State.cards.FirstOrDefault(c=>c.id==change.source);if(card!=null)card.growth+=change.amount;} long added=result.total;if(Boss=="flambeuse"&&!State.reprieved&&AddScore(Board.score,added)>=State.target){State.reprieved=true;added=(long)Math.Ceiling(State.target/2d)-Board.score;} Board.score=added<0 ? Board.score+added : AddScore(Board.score,added); if(Boss=="gambler"&&result.matches.Count>=3)State.battleSpins++; State.outcome=Board.score>=State.target?1:Board.round>=State.battleSpins?-1:0; if(State.outcome==1){double ratio=Board.score/(double)State.target;State.reward=new Rewards{level=new[]{7,7,10,7,7,12}[(State.level-1)%6],remaining=Math.Max(0,State.battleSpins-Board.round),excess=new[]{1.5,2,3,5,10}.Select((t,i)=>ratio>=t?i+1:0).Sum()};State.coins+=State.reward.Total;State.history.Add(new HistoryEntry{level=State.level,score=Board.score,boss=Boss});} result.scoreAfter=Board.score;State.stage=Stage.Settlement;return result; } public int FinishSettlement() { if(State.stage!=Stage.Settlement)return -1; int usedTicket=-1; if(State.outcome<0) { usedTicket=State.tickets.FindIndex(t=>t.id=="free_spin"); if(usedTicket>=0){ConsumeTicket(usedTicket);State.outcome=0;} } if(State.outcome==1)State.stage=Stage.Victory;else if(State.outcome==-1)State.stage=State.endless && !State.reviveUsed ? Stage.ReviveChoice : Stage.Failed; else BeginNextRound(); return usedTicket; } void BeginNextRound() { State.stage = Stage.Battle; if (Boss == "croque_mort" && Board.width > 3) Board.width--; Board.round++; Board.energy = State.maxEnergy; Deal(); } public bool GrantExtraCollect(string runId, string requestId) { if (State.id != runId || State.stage != Stage.ReviveChoice || !State.endless || State.reviveUsed || string.IsNullOrEmpty(requestId) || State.adReceipts.Contains(requestId)) return false; State.adReceipts.Add(requestId); State.reviveUsed = true; State.battleSpins++; State.outcome = 0; BeginNextRound(); return true; } public void DeclineContinue() { if (State.stage == Stage.EndlessChoice) State.stage = Stage.Complete; else if (State.stage == Stage.ReviveChoice) State.stage = Stage.Failed; } } }