-
Notifications
You must be signed in to change notification settings - Fork 0
/
games.py
818 lines (682 loc) · 27.3 KB
/
games.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
import datetime
import os
import random
from asyncio import TimeoutError, sleep
from sys import argv
from typing import Union
import discord
import modules.utilities as utils
from discord.ext import commands, tasks
from modules.extension import Extension
from modules.utilities import debugging
from modules.utilities import logger as l
from modules.utilities import prefix, secrets
from modules.utilities import utilities as u
from modules.utilities import ylcb_config
class games(Extension):
"""Games Extension - ylcb-devs"""
def __init__(self, bot: commands.Bot):
"""
games(bot)
Args:
bot (`commands.Bot`): `commands.Bot` instance
"""
super().__init__(bot, "games")
self.econ = bot.get_cog("economy")
self.items = bot.get_cog("items")
self.airdrop_spawner.start()
def cog_unload(self):
self.airdrop_spawner.cancel()
@tasks.loop(hours=1)
async def airdrop_spawner(self):
chance = random.randint(1,100)
if debugging: return
if chance < 60:
l.log("Airdrop Spawned")
money = random.randint(10,1000)
embed_dict = {
"title":"Airdrop!",
"description": f"Money: ${money}\n",
"type": "rich",
"timestamp": datetime.datetime.now().isoformat(),
"color": 0xff8800,
"author": {
"name": u.discordify(str(self.bot.user)),
"icon_url": str(self.bot.user.avatar_url)
}
}
rand_id = random.randint(1,10)
try: item = self.items.get_item_from_id(rand_id)
except: item = None
if item: embed_dict["description"] = embed_dict["description"] + f"Items: 1x {item['name']}"
embed = discord.Embed.from_dict(embed_dict)
channel = await self.bot.fetch_channel(ylcb_config.data["discord"]["event_channel_id"])
if debugging: msg: discord.Message = await channel.send(embed=embed)
else: msg: discord.Message = await channel.send("@here", embed=embed)
await msg.add_reaction("🛄")
await sleep(0.3)
def check(payload: discord.RawReactionActionEvent): return payload.user_id != self.bot.user and str(payload.emoji) == "🛄" and payload.message_id == msg.id
try:
payload = await self.bot.wait_for("raw_reaction_add", check=check, timeout=300)
except TimeoutError:
await msg.delete()
claimed = False
user = await self.bot.fetch_user(payload.user_id)
reason = ""
try:
self.econ.set_balance_from_d_id(payload.user_id, self.econ.get_balance_from_d_id(payload.user_id) + money)
self.econ.push_transaction_history_from_id(payload.user_id, "Airdrop", money)
if item: self.items.add_item_to_inventory_from_d_id(payload.user_id, item["id"])
except Exception as e:
reason = str(e)
else:
claimed = True
l.log(f"{str(user)} claimed an airdrop worth ${money}", channel=l.DISCORD)
if claimed:
embed_dict["title"] = "Claimed!"
embed_dict["timestamp"] = datetime.datetime.now().isoformat()
embed_dict["color"] = 0x00ff00
embed_dict["author"] = {
"name": u.discordify(str(user)),
"icon_url": str(user.avatar_url)
}
else:
embed_dict["title"] = "Error!"
embed_dict["timestamp"] = datetime.datetime.now().isoformat()
embed_dict["color"] = 0xff0000
embed_dict["description"] = f"Error: There was an error collecting airdrop rewards\nReason: {reason}"
embed = discord.Embed.from_dict(embed_dict)
await msg.edit(content=None, embed=embed)
@commands.command(name="hub", aliases=["games"], usage=f"{prefix}hub", brief="A hub to play all your games")
async def hub(self, ctx):
"""
A hub to play all your games
"""
hub = Hub(self.bot, ctx)
await hub.start()
del hub
@commands.command(name="chance", aliase=["roll"], usage=f"{prefix}chance <bet:float>", brief="Dice roll")
async def chance(self, ctx, bet: float):
"""
Dice roll
Args:
bet (`float`): How much the user is betting.
"""
game = Dice(self.bot, ctx, bet)
await game.start()
del game
@commands.command(name="21", aliases=["bj", "blackjack"], usage=f"{prefix}21 <bet:float> [decks:int]", brief="Simple game of blackjack")
async def blackjack(self, ctx, bet: float, decks: int = 4):
"""
Simple game of blackjack
Args:
bet (`float`): How much the user is betting.
decks (`int`, optional): Amount of decks to play with. Defaults to `4`.
"""
game = Blackjack(self.bot, ctx, bet, decks)
await game.start()
del game
async def can_user_play(self, ctx, _cfg: dict, bet: float, points: float, msg: discord.Message = None) -> bool:
"""
Checks if a user can play a game with given arguments
Args:
_cfg (`dict`): Game config
bet (`float`): How much the user is betting
points (`float`): Amount in user's bank
msg (`discord.Message`, optional): Message to edit instead of send a new one
Returns:
`bool`: if user can play game
"""
bet = round(bet, 2)
if not _cfg["enabled"]:
await ctx.send(f"{ctx.author.mention}, this game has been disabled by an admin.")
return False
if points < bet:
if not msg: await ctx.send(f"{ctx.author.mention}, you only have ${points} to bet!")
if msg: await msg.edit(f"{ctx.author.mention}, you only have ${points} to bet")
return False
if _cfg["min_bet"] < 1:
_cfg["min_bet"] = 1
self.config.updateFile()
l.log("min_bet was lower than 1, min_bet was set to 1", l.FLG)
if bet > _cfg["max_bet"] and _cfg["max_bet"] != 0:
await ctx.send(f"{ctx.author.mention}, the max bet is {_cfg['max_bet']}")
return False
return True
def setup(bot):
bot.add_cog(games(bot))
class StateManager:
def __init__(self, states: list, state: tuple):
self.states = states
self.state = state
# self.game = ["checks", "game", "check_failed", "error", "outcome"]
# self.hub = [State("menu"), "betting", "game", "error", "outcome"]
def set_state(self, new_state):
for old_state in self.states:
if old_state == new_state:
l.log(f"Set State:{new_state}->{self.state}")
self.state = new_state
def get_state(self):
return self.state
async def run_state(self):
await self.state[1]()
class Hub:
def __init__(self, bot, ctx):
"""
Hub to play all your games
Args:
bot (`commands.Bot`): `commands.Bot` instance
ctx (`commands.Context`): Command context
"""
self.bot = bot
self.alive = True
self.msg = None
self.embed_dict = {
"title":"Game Hub",
"type": "rich",
"timestamp": datetime.datetime.now().isoformat(),
"color": 0x0000ff,
"fields": [],
"author": {
"name": u.discordify(str(self.bot.user)),
"icon_url": str(self.bot.user.avatar_url)
}
}
self.bet: float = 0
self.prev_bet: float = 0
self.game_outcome: float = 0
self.session_outcome: float = 0
self.games_played = 0
self.ctx = ctx
self.player = ctx.author
self.emoji: str = ""
self.cog: games = self.bot.get_cog("games")
self.state_menu = "menu", self.menu
self.state_betting = "betting", self.betting
self.state_game = "game", self.m_game
self.state_error = "error", self.error
self.state_outcome = "outcome", self.m_outcome
self.state_exit = "exit", self.m_exit
self.gsm: StateManager = StateManager([self.state_menu, self.state_betting, self.state_game, self.state_error, self.state_outcome, self.state_exit], self.state_menu)
async def start(self):
while self.alive:
await self.gsm.run_state()
async def stop(self):
self.alive = False
async def m_exit(self):
self.embed_dict = {
"title":"Game/Session",
"color": 0x00ff00,
"fields": [
{"name": "Games Played", "value": f"{self.games_played}", "inline": True },
{"name": "Session Outcome", "value": f"${self.session_outcome}", "inline": True },
{"name": "Avg. $ per Game", "value": f"${(self.session_outcome/(self.games_played if self.games_played else 1))}", "inline": True },
{"name": "Current Balance", "value": f"${self.cog.econ.get_balance_from_d_id(self.player.id)}"},
],
"author": {
"name": u.discordify(str(self.player)),
"icon_url": str(self.player.avatar_url)
}
}
self.update_timestamp()
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
await self.msg.clear_reactions()
await self.stop()
def update_timestamp(self):
self.embed_dict["timestamp"] = datetime.datetime.now().isoformat()
async def betting_screen(self):
self.update_timestamp()
self.embed_dict = {
"title": f"Bet: ${str(self.bet)}",
"color": 0x0000ff,
"fields": [
{"name": "🔴", "value": "+$1", "inline": True},
{"name": "🟠", "value": "+$5", "inline": True},
{"name": "🟡", "value": "+$10", "inline": True},
{"name": "🟢", "value": "+$50", "inline": True},
{"name": "🔵", "value": "+$100", "inline": True},
{"name": "🟣", "value": "+$500", "inline": True},
{"name": "⚫", "value": "+$1000", "inline": True},
{"name": "✅", "value": "Start Game", "inline": True},
],
"author": {
"name": u.discordify(str(self.bot.user)),
"icon_url": str(self.bot.user.avatar_url)
}
}
if self.prev_bet: self.embed_dict["fields"].append({"name": "⬅️", "value": "Last Bet", "inline": True})
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
async def menu_screen(self):
description = "🃏 Blackjack\n🎲 Chance Roll\n❌ Exit Hub"
if self.emoji:
description = description + "\n⬅️ Previous Game"
self.embed_dict = {
"title":"Game Hub",
"description": description,
"color": 0x0000ff,
"author": {
"name": u.discordify(str(self.bot.user)),
"icon_url": str(self.bot.user.avatar_url)
}
}
self.update_timestamp()
if self.msg:
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
else:
self.msg = await self.ctx.send(embed=discord.Embed.from_dict(self.embed_dict))
await self.msg.clear_reactions()
await self.msg.add_reaction("🃏")
await self.msg.add_reaction("🎲")
await self.msg.add_reaction("❌")
if self.emoji: await self.msg.add_reaction("⬅️")
async def menu(self):
await self.menu_screen()
await sleep(0.3)
def check(payload: discord.RawReactionActionEvent): return payload.user_id != self.bot.user and str(payload.emoji) in ["🃏","🎲","❌","⬅️"] and payload.message_id == self.msg.id
response = await self.bot.wait_for("raw_reaction_add", check=check)
if str(response.emoji) in ["🃏","🎲"]:
self.emoji = str(response.emoji)
if str(response.emoji) == "❌":
self.gsm.set_state(self.state_exit)
else:
self.gsm.set_state(self.state_betting)
async def betting(self):
self.prev_bet = self.bet
self.bet = 0
await self.betting_screen()
await self.msg.clear_reactions()
await self.msg.add_reaction("🔴")
await self.msg.add_reaction("🟠")
await self.msg.add_reaction("🟡")
await self.msg.add_reaction("🟢")
await self.msg.add_reaction("🔵")
await self.msg.add_reaction("🟣")
await self.msg.add_reaction("⚫")
await self.msg.add_reaction("✅")
if self.prev_bet: await self.msg.add_reaction("⬅️")
await sleep(0.3)
betting = True
while betting:
def check(payload: discord.RawReactionActionEvent): return payload.user_id != self.bot.user and str(payload.emoji) in ["🔴","🟠","🟡","🟢","🔵","🟣","⚫","✅","❌","⬅️"] and payload.message_id == self.msg.id
response = await self.bot.wait_for("raw_reaction_add", check=check)
if str(response.emoji) == "🔴": self.bet += 1
if str(response.emoji) == "🟠": self.bet += 5
if str(response.emoji) == "🟡": self.bet += 10
if str(response.emoji) == "🟢": self.bet += 50
if str(response.emoji) == "🔵": self.bet += 100
if str(response.emoji) == "🟣": self.bet += 500
if str(response.emoji) == "⚫": self.bet += 1000
if str(response.emoji) == "✅": betting = False
if str(response.emoji) == "⬅️": self.bet = self.prev_bet
await self.betting_screen()
self.games_played += 1
self.gsm.set_state(self.state_game)
async def m_game(self):
await self.msg.clear_reactions()
self.update_timestamp()
self.embed_dict["description"] = "Loading game..."
game = None
if self.emoji == "🃏":
self.embed_dict["title"] = "Games/21"
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
game = Blackjack(self.bot,self.ctx,self.bet,4,self)
if self.emoji == "🎲":
self.embed_dict["title"] = "Games/Chance Roll"
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
game = Dice(self.bot,self.ctx,self.bet,self)
if game:
await game.start()
self.game_outcome = game.outcome
self.session_outcome += game.outcome
else:
self.gsm.set_state(self.state_error)
self.gsm.set_state(self.state_outcome)
async def m_outcome(self):
self.embed_dict = {
"title":"Game/Outcome",
"color": 0x00ff00,
"fields": [
{"name": "Game Outcome", "value": f"${self.game_outcome}", "inline": True },
{"name": "Session Outcome", "value": f"${self.session_outcome}", "inline": True },
{"name": "Current Balance", "value": f"${self.cog.econ.get_balance_from_d_id(self.player.id)}", "inline": True },
],
"author": {
"name": u.discordify(str(self.player)),
"icon_url": str(self.player.avatar_url)
},
"footer": {"text": "Directions: ✅: Home | ❌: Exit"}
}
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
await self.msg.add_reaction("✅")
await self.msg.add_reaction("❌")
await sleep(0.3)
def check(payload: discord.RawReactionActionEvent): return payload.user_id != self.bot.user and str(payload.emoji) in ["✅","❌"] and payload.message_id == self.msg.id
response = await self.bot.wait_for("raw_reaction_add", check=check)
if str(response.emoji) == "✅":
self.gsm.set_state(self.state_menu)
if str(response.emoji) == "❌":
self.gsm.set_state(self.state_exit)
async def error(self):
self.embed_dict = {
"title":"Game Hub/Error",
"type": "rich",
"timestamp": datetime.datetime.now().isoformat(),
"color": 0xff0000,
"fields": [
{"name": "Error", "value": "It appears your game has errored...", "inline": True}
],
"author": {
"name": u.discordify(str(self.bot.user)),
"icon_url": str(self.bot.user.avatar_url)
},
"footer": {"text": "Directions: ⬅️: Home | ❌: Exit"}
}
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
await self.msg.clear_reactions()
await self.msg.add_reaction("⬅️")
await self.msg.add_reaction("❌")
await sleep(0.3)
def check(payload: discord.RawReactionActionEvent): return payload.user_id != self.bot.user and str(payload.emoji) in ["🔴","🟠","🟡","🟢","🔵","🟣","⚫","✅","❌","⬅️"] and payload.message_id == self.msg.id
response = await self.bot.wait_for("raw_reaction_add", check=check)
if str(response.emoji) == "⬅️":
self.gsm.set_state(self.state_menu)
if str(response.emoji) == "❌":
self.gsm.set_state(self.state_exit)
class Game:
def __init__(self, bot, ctx, bet: float, hub: Hub = None):
"""
Game base class
Args:
bot (`commands.Bot`): `commands.Bot` instance
ctx (`commands.Context`): Command context
bet (`float`): Amount user bet
hub (`Hub`, optional): `Hub` instance. Defaults to `None`.
"""
self.outcome = 0
self.bet = bet
self.bot = bot
self.hub = hub
self.ctx = ctx
self.alive = True
self.playing = False
self.player = ctx.author
self.econ = bot.get_cog("economy")
if hub:
self.in_hub = True
self.msg = hub.msg
else:
self.in_hub = False
self.msg = None
self.boost = self.bot.get_cog("items").get_boost_from_d_id(self.player.id)
self.cog: game_cog = self.bot.get_cog("games")
class CardGame(Game):
def __init__(self, bot, ctx, bet: float, hub: Hub = None, decks: int = 4):
super().__init__(bot, ctx, bet, hub)
self.card_strs = ["alert a developer if you see this", "🇦", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟", "🇯", "🇶", "🇰"]
self.decks = decks
self.deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]*decks
class Blackjack(CardGame):
def __init__(self, bot, ctx, bet: float, decks: int = 4, hub: Hub = None):
"""
Blackjack game
Args:
bot (`commands.Bot`): `commands.Bot` instance
ctx (`commands.Context`): Command context
bet (`float`): Amount user bet
decks (`int`, optional): Amount of decks to play with. Defaults to `4`.
hub (`Hub`, optional): If game is ran from hub this will be set. Defaults to `None`.
"""
super().__init__(bot, ctx, bet, hub, decks)
self.dealer_hand = self.deal()
self.player_hand = self.deal()
self.alive = True
self.state_check = "check", self.check
self.state_game = "game", self.game
self.state_check_failed = "check_failed", self.check_failed
self.state_error = "error", self.error
self.state_outcome = "outcome", self.outcome_func
self.gsm: StateManager = StateManager([self.state_check, self.state_game, self.state_check_failed, self.state_error, self.state_outcome], self.state_check)
async def start(self):
while self.alive:
await self.gsm.run_state()
async def stop(self):
self.alive = False
async def check(self):
if not (self.bet or self.decks or self.hub):
self.ctx.send(f"{self.player.mention}, please specify a bet or decks")
self.gsm.set_state(self.state_check_failed)
return
if not await self.cog.can_user_play(self.ctx, self.cog.config.data["games"]["blackjack"], self.bet, self.cog.econ.get_balance_from_d_id(self.player.id), self.msg):
self.gsm.set_state(self.state_check_failed)
return
self.gsm.set_state(self.state_game)
async def check_failed(self):
if self.in_hub: await self.hub.state_check_failed[1]()
else: await self.stop()
async def error(self):
if self.in_hub: await self.hub.state_error[1]()
else: await self.stop()
async def game(self):
self.econ.set_balance_from_d_id(self.player.id, self.econ.get_balance_from_d_id(self.player.id) - self.bet)
l.log(f"Blackjack start: {str(self.player)} | Bet:${self.bet}", channel=l.DISCORD)
self.playing = True
self.embed_dict = {
"title":"Ongoing 21 Game",
"type": "rich",
"color": 0xffdd00,
"author": {
"name": u.discordify(str(self.player)),
"icon_url": str(self.player.avatar_url)
},
"footer": {"text": "Directions: 🔴: Stand | 🟢: Hit"}
}
if self.boost: self.embed_dict["footer"] = {"text": f"Directions: 🔴: Stand | 🟢: Hit | {self.boost}x Boost applied"}
await self.update_embed(self.dealer_hand, self.player_hand)
if (self.total(self.dealer_hand) == 21 and len(self.dealer_hand) == 2) or (self.total(self.player_hand) == 21 and len(self.player_hand) == 2):
self.playing = False
self.gsm.set_state(self.state_outcome)
return
if not self.in_hub: self.msg = await self.ctx.send(embed=discord.Embed.from_dict(self.embed_dict))
else: await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
await self.msg.add_reaction("🔴")
await self.msg.add_reaction("🟢")
while self.playing:
await sleep(0.3)
def check(payload: discord.RawReactionActionEvent): return payload.user_id == self.player.id and str(payload.emoji) in ["🔴","🟢"] and payload.message_id == self.msg.id
payload = await self.bot.wait_for("raw_reaction_add", check=check)
if str(payload.emoji) == "🟢":
self.hit(self.player_hand)
if self.total(self.player_hand) > 21:
self.playing = False
await self.update_embed(self.dealer_hand, self.player_hand)
elif str(payload.emoji) == "🔴":
self.playing = False
while self.total(self.dealer_hand) < 17 or self.s17_hit():
self.hit(self.dealer_hand)
await self.update_embed(self.dealer_hand, self.player_hand)
await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
await self.msg.clear_reactions()
self.gsm.set_state(self.state_outcome)
async def outcome_func(self):
self.multiplier = 1 + self.boost
_cfg = self.cog.config.data["games"]["blackjack"]
self.embed_dict["fields"] = [
{"name": "Dealer's hand:", "value": self.readable(self.dealer_hand), "inline": True},
{"name": "Dealer's value:", "value": self.total(self.dealer_hand), "inline": True},
{"name": "Bet:", "value": f"${self.bet}", "inline": True},
{"name": "My hand:", "value": self.readable(self.player_hand), "inline": True},
{"name": "My value:", "value": self.total(self.player_hand), "inline": True}
]
if self.boost: self.embed_dict["footer"] = {"text": f"{self.boost}x boost used"}
else: self.embed_dict["footer"] = None
if (self.total(self.player_hand) > self.total(self.dealer_hand) or self.total(self.dealer_hand) > 21) and self.total(self.player_hand) <= 21: ## if won
self.multiplier = _cfg["small_multiplier"] + self.boost
if self.total(self.player_hand) == 21 and len(self.player_hand) == 2: self.multiplier = _cfg["large_multiplier"] + self.boost
payout = self.bet * self.multiplier
self.outcome = payout - self.bet
self.cog.econ.set_balance_from_d_id(self.player.id, self.cog.econ.get_balance_from_d_id(self.player.id) + payout)
self.cog.econ.push_transaction_history_from_id(self.player.id, "Blackjack", self.outcome)
if not self.in_hub:
self.embed_dict["color"] = 0x00ff00
self.embed_dict["title"] = f"You won ${self.outcome}!"
elif self.total(self.dealer_hand) > self.total(self.player_hand) or self.total(self.player_hand) > 21: ## if lost
self.outcome = self.bet*-1
self.cog.econ.push_transaction_history_from_id(self.player.id, "Blackjack", self.outcome)
if not self.in_hub:
self.embed_dict["color"] = 0xff0000
self.embed_dict["title"] = f"You lost ${self.bet}!"
else: ## if push
self.outcome = 0
self.cog.econ.set_balance_from_d_id(self.player.id, self.cog.econ.get_balance_from_d_id(self.player.id) + self.bet)
if not self.in_hub:
self.embed_dict["title"] = "Push!"
self.embed_dict["color"] = 0xffdd00
self.cog.items.reset_boost_from_d_id(self.player.id)
l.log(f"Blackjack outcome: {str(self.player)}:{Blackjack.total(self.player_hand)} | Bet:${self.bet} | Multiplier:{self.multiplier}x ({self.boost}) | CPU:{Blackjack.total(self.dealer_hand)}", channel=l.DISCORD)
if not self.in_hub: await self.msg.edit(embed=discord.Embed.from_dict(self.embed_dict))
await self.stop()
def deal(self) -> list:
hand = []
for i in range(2):
random.shuffle(self.deck)
card = self.deck.pop()
hand.append(card)
return hand
def soft_17(self) -> bool:
return (1 in self.dealer_hand and self.total(self.dealer_hand) == 17)
def s17_hit(self) -> bool:
return (self.soft_17() and self.cog.config.data["games"]["blackjack"]["hit_on_soft_17"])
@staticmethod
def total(hand: list) -> int:
aces = Blackjack.check_for_ace(hand)
total = 0
for card in hand:
if card in [11,12,13]:
total += 10
elif card == 1:
if total >= 11: total += 1
else: total += 11
else: total += card
while aces > 1 and total > 21:
total -= 10
aces -= 1
return total
@staticmethod
def value(card: int) -> int:
if card in [11,12,13]:
return 10
elif card == 1:
return 11
else: return card
@staticmethod
def check_for_ace(hand) -> int:
"""Returns number of aces in hand"""
aces = 0
for i in hand:
if i == 1: aces += 1
return aces
def hit(self, hand: list) -> list:
"""Adds card to a hand"""
card = self.deck.pop()
hand.append(card)
return hand
def readable(self, hand: list) -> str:
"""Makes hand printable"""
handStr = ""
for card in hand:
handStr = handStr + self.readable_card(card) + " "
return handStr
def readable_card(self, card: int) -> str:
"""Makes card printable"""
return self.card_strs[card]
async def update_embed(self, dealer_hand, player_hand) -> dict:
self.embed_dict["fields"] = [
{"name": "Dealer showing:", "value": self.readable_card(self.dealer_hand[0]), "inline": True},
{"name": "Dealer's value:", "value": self.value(self.dealer_hand[0]), "inline": True},
{"name": "Bet:", "value": f"${self.bet}", "inline": True},
{"name": "My hand:", "value": self.readable(self.player_hand), "inline": True},
{"name": "My value:", "value": self.total(self.player_hand), "inline": True}
]
return self.embed_dict
class Dice(Game):
def __init__(self, bot, ctx, bet: float, hub: Hub = None):
"""
Dice game
Args:
bot (`commands.Bot`): `commands.Bot` instance
ctx (`commands.Context`): Command context
bet (`float`): Amount user bet
hub (`Hub`, optional): If game is ran from hub this will be set. Defaults to `None`.
"""
super().__init__(bot, ctx, bet, hub)
self.state_check = "check", self.check
self.state_game = "game", self.game
self.state_check_failed = "check_failed", self.check_failed
self.state_error = "error", self.error
self.state_outcome = "outcome", self.outcome_func
self.gsm: StateManager = StateManager([self.state_check, self.state_game, self.state_check_failed, self.state_error, self.state_outcome], self.state_check)
async def start(self):
while self.alive:
await self.gsm.run_state()
async def stop(self):
self.alive = False
async def check(self):
if not (self.bet or self.hub):
await self.ctx.send(f"{self.player.mention}, please specify a bet")
self.gsm.set_state(self.state_check_failed)
return
if not await self.cog.can_user_play(self.ctx, self.cog.config.data["games"]["blackjack"], self.bet, self.cog.econ.get_balance_from_d_id(self.player.id), self.msg):
self.gsm.set_state(self.state_check_failed)
return
self.gsm.set_state(self.state_game)
async def check_failed(self):
if self.in_hub: await self.hub.state_check_failed[1]()
else: await self.stop()
async def error(self):
if self.in_hub: await self.hub.state_error[1]()
else: await self.stop()
async def game(self):
self.econ.set_balance_from_d_id(self.player.id, self.econ.get_balance_from_d_id(self.player.id) - self.bet)
l.log(f"Chance start: {str(self.player)} | Bet:${self.bet}", channel=l.DISCORD)
self.playing = True
self.p_score = random.randint(2,12)
self.cpu_score = random.randint(2,12)
self.gsm.set_state(self.state_outcome)
async def outcome_func(self):
points = self.cog.econ.get_balance_from_d_id(self.player.id)
_cfg = self.cog.config.data["games"]["chance"]
embed_dict = {
"title":"It\'s a push!",
"type": "rich",
"timestamp": datetime.datetime.now().isoformat(),
"color": 0xffdd00,
"fields": [
{"name": "You scored:", "value": self.p_score, "inline": True},
{"name": "I scored:", "value": self.cpu_score, "inline": True}
]
}
self.boost = self.cog.items.get_boost_from_d_id(self.player.id)
multiplier = 1 + self.boost
if self.p_score > self.cpu_score:
multiplier = _cfg["small_multiplier"] + self.boost
if self.p_score == 2: multiplier = _cfg["large_multiplier"] + self.boost
payout = self.bet*multiplier
self.outcome = payout - self.bet
self.cog.econ.set_balance_from_d_id(self.player.id, points + payout)
self.cog.econ.push_transaction_history_from_id(self.player.id, "Chance Roll", self.outcome)
if not self.in_hub:
embed_dict["color"] = 0x00ff00
embed_dict["title"] = f"You won ${self.outcome}!"
elif self.cpu_score > self.p_score:
self.outcome = self.bet*-1
if not self.in_hub:
embed_dict["color"] = 0xff0000
embed_dict["title"] = f"You lost ${self.bet}!"
self.cog.econ.push_transaction_history_from_id(self.player.id, "Chance Roll", self.outcome)
elif self.cpu_score == self.p_score:
self.cog.econ.set_balance_from_d_id(self.player.id, points + self.bet)
l.log(f"Chance outcome: {str(self.player)}:{self.p_score} | Bet:${self.bet} | Multiplier:{multiplier}x ({self.boost}) | CPU:{self.cpu_score}", channel=l.DISCORD)
if not self.in_hub:
try: await self.msg.edit(embed=discord.Embed.from_dict(embed_dict))
except: self.msg = await self.ctx.send(embed=discord.Embed.from_dict(embed_dict))
await self.stop()