-
Notifications
You must be signed in to change notification settings - Fork 22
/
deck_editor.py
674 lines (538 loc) · 21.5 KB
/
deck_editor.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
from collections import OrderedDict, Counter
import json
import random
import natsort
import base64
import binascii
import struct
from sqlalchemy import or_
from .card import Card
from . import globals
from . import models
from .constants import *
from .exceptions import BanlistNotFoundError
from .parsers.deck_editor_parser import DeckEditorParser
class DeckEditor:
def __init__(self, player):
self.deck_edit_pos = 0
self.deck_name = ''
self.last_search = ""
self.player = player
self.deck_key = 'cards'
def get_decks(self, selector = DECK.OWNED, name = '', banlist = ''):
filtered_decks = 0
o_banlist = None
other_decks = []
owned_decks = []
params = []
pl = self.player
public_decks = []
session = pl.connection.session
query = session.query(models.Deck)
if selector & DECK.PUBLIC == DECK.PUBLIC:
params.append(models.Deck.public == True)
if selector & DECK.ALL == DECK.ALL:
pass
elif selector & DECK.OWNED == DECK.OWNED:
params.append(models.Deck.account_id == pl.get_account().id)
elif selector & DECK.OTHER == DECK.OTHER:
params.append(models.Deck.account_id != pl.get_account().id)
query = query.filter(or_(*params))
all_decks = query.all()
decks = all_decks[:]
if name:
name = name.lower()
decks = [deck for deck in all_decks if name in deck.name.lower()]
filtered_decks += len(all_decks) - len(decks)
all_decks = decks[:]
if banlist:
o_banlist = globals.banlists.get(banlist, None)
if not o_banlist:
raise BanlistNotFoundError()
for deck in all_decks:
content = json.loads(deck.content)
if len(o_banlist.check(content.get('cards', []) + content.get('side', []))) > 0:
decks.remove(deck)
filtered_decks += 1
return (decks, filtered_decks, )
def list_decks(self, selector = DECK.OWNED, name = '', banlist = ''):
filtered_decks = 0
other_decks = []
owned_decks = []
pl = self.player
public_decks = []
try:
(decks, filtered_decks) = self.get_decks(selector=selector, name=name, banlist=banlist)
except BanlistNotFoundError:
pl.notify(pl._("no banlist with name {banlist} found.").format(banlist = banlist))
return
public_decks = [deck for deck in decks if deck.public]
decks = [deck for deck in decks if deck not in public_decks]
owned_decks = [deck for deck in decks if deck.account_id == pl.get_account().id]
decks = [deck for deck in decks if deck not in owned_decks]
other_decks = decks
public_decks = natsort.natsorted(public_decks, key = lambda d: str(d.id) + ": " + d.account.name + "/" + d.name)
owned_decks = natsort.natsorted(owned_decks, key = lambda d: str(d.id) + ": " + d.name)
other_decks = natsort.natsorted(other_decks, key = lambda d: str(d.id) + ": " + d.account.name + "/" + d.name)
if len(public_decks):
pl.notify(pl._("There are {amount} public decks available:").format(amount = len(public_decks)))
for deck in public_decks:
banlist_text = pl._("compatible with no banlist")
if banlist:
banlist_text = pl._("compatible with {0} banlist").format(banlist)
else:
for b in globals.banlists.values():
content = json.loads(deck.content)
if len(b.check(content.get('cards', []) + content.get('side', []))) == 0:
banlist_text = pl._("compatible with {0} banlist").format(b.name)
break
pl.notify(pl._("{deck_id}: {deckname} ({banlist})").format(deck_id=deck.id, deckname=deck.account.name + "/" + deck.name, banlist=banlist_text))
if len(owned_decks):
pl.notify(pl._("You own {amount} decks:").format(amount = len(owned_decks)))
for deck in owned_decks:
if deck.public:
privacy = pl._("public")
else:
privacy = pl._("private")
banlist_text = pl._("compatible with no banlist")
if banlist:
banlist_text = pl._("compatible with {0} banlist").format(banlist)
else:
for b in globals.banlists.values():
content = json.loads(deck.content)
if len(b.check(content.get('cards', []) + content.get('side', []))) == 0:
banlist_text = pl._("compatible with {0} banlist").format(b.name)
break
pl.notify(pl._("{deck_id}: {deckname} ({privacy}) ({banlist})").format(deck_id=deck.id, deckname=deck.name, privacy=privacy, banlist=banlist_text))
if len(other_decks):
pl.notify(pl._("There are {amount} other decks available:").format(amount = len(other_decks)))
for deck in other_decks:
if deck.public:
privacy = pl._("public")
else:
privacy = pl._("private")
banlist_text = pl._("compatible with no banlist")
if banlist:
banlist_text = pl._("compatible with {0} banlist").format(banlist)
else:
for b in globals.banlists.values():
content = json.loads(deck.content)
if len(b.check(content.get('cards', []) + content.get('side', []))) == 0:
banlist_text = pl._("compatible with {0} banlist").format(b.name)
break
pl.notify(pl._("{deckname} ({privacy}) ({banlist})").format(deckname=deck.account.name + "/" + deck.name, privacy=privacy, banlist=banlist_text))
pl.notify(pl._("{shown} decks shown, {filtered} decks filtered").format(shown = len(public_decks) + len(owned_decks) + len(other_decks), filtered = filtered_decks))
def clear(self, name):
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if not deck:
self.player.notify(self.player._("Deck not found."))
return
deck.content = json.dumps({'cards': [], 'side': []})
session.commit()
self.player.notify(self.player._("Deck cleared."))
def delete(self, name):
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if not deck:
self.player.notify(self.player._("Deck not found."))
return
session.delete(deck)
session.commit()
self.player.notify(self.player._("Deck deleted."))
def rename(self, args):
if '=' not in args:
self.player.notify(self.player._("Usage: deck rename <old>=<new>"))
return
args = args.strip().split('=', 1)
name = args[0].strip()
dest = args[1].strip()
if not name or not dest:
self.player.notify(self.player._("Usage: deck rename <old>=<new>"))
return
if '=' in dest:
self.player.notify(self.player._("Deck names may not contain =."))
return
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if not deck:
self.player.notify(self.player._("Deck not found."))
return
dest_deck = models.Deck.find(session, account, dest)
if dest_deck:
self.player.notify(self.player._("Destination deck already exists"))
return
deck.name = dest
session.commit()
self.player.notify(self.player._("Deck renamed."))
def copy(self, args):
if '=' not in args:
self.player.notify(self.player._("Usage: deck copy <old>=<new>"))
return
args = args.strip().split('=', 1)
name = args[0].strip()
dest = args[1].strip()
if not name or not dest:
self.player.notify(self.player._("Usage: deck copy <old>=<new>"))
return
if '=' in dest:
self.player.notify(self.player._("Deck names may not contain =."))
return
if '/' in dest:
self.player.notify(self.player._("The copy destination can only be one of your own decks."))
return
player_name = ''
deck_name = name
if '/' in deck_name:
player_name = deck_name.split('/')[0].title()
deck_name = deck_name[(len(player_name) + 1):]
if player_name != '':
if player_name.lower() == self.player.nickname.lower():
self.player.notify(self.player._("You don't need to mention yourself if you want to use your own deck."))
return
account = self.player.connection.session.query(models.Account).filter_by(name=player_name).first()
if not account:
self.player.notify(self.player._("Player {0} could not be found.").format(player_name))
return
else:
account = self.player.get_account()
session = self.player.connection.session
if player_name != '':
deck = models.Deck.find_public(session, account, deck_name)
else:
deck = models.Deck.find(session, account, name)
if not deck:
self.player.notify(self.player._("Deck doesn't exist or isn't publically available."))
return
dest_deck = models.Deck.find(session, self.player.get_account(), dest)
if dest_deck:
self.player.notify(self.player._("Destination deck already exists"))
return
new_deck = models.Deck(name=dest, content=deck.content)
player_account = self.player.get_account()
player_account.decks.append(new_deck)
session.commit()
self.player.notify(self.player._("Deck copied."))
def draw(self, args):
if '=' not in args:
self.player.notify(self.player._("Usage: deck draw <deck>=<number>"))
return
args = args.strip().split('=', 1)
player_name = ''
deck_name = args[0].strip()
try:
amount = int(args[1])
except ValueError:
self.player.notify(self.player._("I didn't understand the amount of cards you want to draw."))
return
if not deck_name or not amount:
self.player.notify(self.player._("Usage: deck draw <deck>=<number>"))
return
session = self.player.connection.session
if '/' in deck_name:
player_name = deck_name.split('/')[0].title()
deck_name = deck_name[(len(player_name) + 1):]
if player_name != '':
if player_name.lower() == self.player.nickname.lower():
self.player.notify(self.player._("You don't need to mention yourself if you want to use your own deck."))
return
account = session.query(models.Account).filter_by(name=player_name).first()
if not account:
self.player.notify(self.player._("Player {0} could not be found.").format(player_name))
return
else:
account = self.player.get_account()
if player_name != '':
deck = models.Deck.find_public(session, account, deck_name)
else:
deck = models.Deck.find(session, account, deck_name)
if not deck:
self.player.notify(self.player._("Deck doesn't exist or isn't publically available."))
return
if not deck:
self.player.notify(self.player._("Deck not found."))
return
cards = json.loads(deck.content)['cards']
cards = [c for c in cards if c in globals.server.all_cards and not Card(c).extra]
random.shuffle(cards)
for i in range(0, min(amount, len(cards))):
self.player.notify(self.player._("Drew: %s") % Card(cards[i]).get_name(self.player))
def edit(self, deck_name):
con = self.player.connection
account = con.player.get_account()
deck = models.Deck.find(con.session, account, deck_name)
if deck and deck.public:
con.notify(con._("You cannot edit public decks. Switch it back to private by using deck private {0} first.").format(deck_name))
return
con.player.paused_parser = con.parser
con.parser = DeckEditorParser
if deck:
con.notify(con._("Deck exists, loading."))
con.player.deck = json.loads(deck.content)
found = False
invalid_cards = con.player.get_invalid_cards_in_deck(con.player.deck.get('cards', []))
if len(invalid_cards):
con.player.deck['cards'] = [c for c in con.player.deck['cards'] if c not in invalid_cards]
found = True
invalid_cards = con.player.get_invalid_cards_in_deck(con.player.deck.get('side', []))
if len(invalid_cards):
con.player.deck['side'] = [c for c in con.player.deck['side'] if c not in invalid_cards]
found = True
if found:
con.notify(con._("Invalid cards were removed from this deck. This usually occurs after the server loading a new database which doesn't know those cards anymore."))
else:
con.notify(con._("Creating new deck %s.") % deck_name)
con.player.deck = {'cards': [], 'side': []}
self.deck_name = deck_name
con.parser.prompt(con)
@staticmethod
def group_cards(cardlist):
"""
Groups all cards in the supplied list.
This provides output like foo, bar(x3) etc.
"""
cnt = Counter(cardlist)
return OrderedDict(natsort.natsorted(dict(cnt).items()))
def group_sort_cards(self, cardlist):
"""
Use the above function to group all cards, then sort them into groups.
"""
extras = [c for c in cardlist if (Card(c).type & TYPE.EXTRA)]
for c in extras: cardlist.remove(c)
traps = [c for c in cardlist if (Card(c).type & TYPE.TRAP)]
for c in traps: cardlist.remove(c)
monsters = [c for c in cardlist if (Card(c).type & TYPE.MONSTER)]
for c in monsters: cardlist.remove(c)
spells = [c for c in cardlist if (Card(c).type & TYPE.SPELL)]
for c in spells: cardlist.remove(c)
other=cardlist
extras_group = self.group_cards(extras)
traps_group = self.group_cards(traps)
spells_group = self.group_cards(spells)
monsters_group = self.group_cards(monsters)
other_group = self.group_cards(other)
groups=(monsters_group, spells_group, traps_group, extras_group, other_group)
return groups
def group_cards_combined(self, cardlist):
"""
Groups and sorts cards, then combines them in the correct order for proper indexing.
"""
groups = self.group_sort_cards(cardlist)
monsters, spells, traps, extras, other = groups
full = OrderedDict()
for x,y in monsters.items(): full[x] = y
for x,y in spells.items(): full[x] = y
for x,y in traps.items(): full[x] = y
for x,y in extras.items(): full[x] = y
for x, y in other.items(): full[x] = y
return full
def find_next(self, text, start, limit=None, wrapped=False):
sql = 'SELECT id FROM texts WHERE UPPERCASE(name) LIKE ? and id in (%s) ORDER BY id ASC LIMIT 1'
if limit:
cards = globals.server.all_cards[start:start+limit]
else:
cards = globals.server.all_cards[start:]
row = self.player.cdb.execute(sql % (', '.join([str(c) for c in cards])), ('%'+text.upper()+'%', )).fetchone()
if row is not None:
return globals.server.all_cards.index(row[0])
if wrapped:
return
return self.find_next(text, 0, start, wrapped=True)
def find_prev(self, text, start, end=None, wrapped=False):
sql = 'SELECT id FROM texts WHERE UPPERCASE(name) LIKE ? AND id IN (%s) ORDER BY id DESC LIMIT 1'
pos = start
if end is None:
end = 0
cards = globals.server.all_cards[end:start]
row = self.player.cdb.execute(sql % (', '.join([str(c) for c in cards])), ('%'+text.upper()+'%', )).fetchone()
if row is not None:
return globals.server.all_cards.index(row[0])
if wrapped:
return
return self.find_prev(text, len(globals.server.all_cards) - 1, start, wrapped=True)
def save(self):
deck = json.dumps(self.player.deck)
session = self.player.connection.session
account = self.player.get_account()
existing_deck = models.Deck.find(session, account, self.deck_name)
if existing_deck:
new_deck = existing_deck
else:
new_deck = models.Deck(account_id=account.id, name=self.deck_name)
account.decks.append(new_deck)
new_deck.content = deck
session.commit()
def new(self, name):
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if deck:
self.player.notify(self.player._("That deck already exists."))
return
deck = models.Deck(account_id=account.id, name=name)
account.decks.append(deck)
deck.content = json.dumps({'cards': [], 'side': []})
session.commit()
self.player.notify(self.player._("Deck created."))
def check(self, deck, banlist = None):
con = self.player.connection
if not banlist:
self.player.notify(self.player._("The following banlists are available (from newest to oldest):"))
for k in globals.banlists.keys():
self.player.notify(k)
return
if banlist not in globals.banlists:
self.player.notify(self.player._("This banlist is unknown."))
return
errors = globals.banlists[banlist].check_and_resolve(deck)
for err in errors:
self.player.notify(self.player._("%s: limit %d, found %d.") % (err[0].get_name(self.player), err[1], err[2]))
self.player.notify(self.player._("Check completed with %d errors.") % len(errors))
def count_occurrence_in_deck(self, code):
card = Card(code)
if card.alias == 0:
possible_cards = globals.language_handler.primary_database.execute('SELECT id FROM datas WHERE id = ? OR alias = ?', (code, code, )).fetchall()
else:
possible_cards = globals.language_handler.primary_database.execute('SELECT id FROM datas WHERE id = ? OR alias = ? OR id = ?', (code, card.alias, card.alias, )).fetchall()
found = 0
for c in possible_cards:
found += self.player.deck.get('cards', []).count(c[0])
found += self.player.deck.get('side', []).count(c[0])
return found
def deck_import(self, args):
if '=' not in args:
self.player.notify(self.player._("Usage: deck import <name>=<string>"))
return
args = args.strip().split('=', 1)
name = args[0].strip()
s = args[1].strip()
if not name or not s:
self.player.notify(self.player._("Usage: deck import <name>=<string>"))
return
try:
deck_string = json.dumps(parse_ydke(s))
except URLParseError:
self.player.notify(self.player._("Invalid import string."))
return
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if deck:
self.player.notify(self.player._("Deck already exists."))
return
deck = models.Deck(account_id=account.id, name=name, content=deck_string)
account.decks.append(deck)
session.commit()
self.player.notify(self.player._("Deck %s imported.") % name)
def deck_export(self, args):
name = args
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if not deck:
self.player.notify(self.player._("Deck not found."))
return
s = deck_to_ydke(json.loads(deck.content))
self.player.notify("deck import %s=%s" % (deck.name, s))
def set_public(self, name, pub):
account = self.player.get_account()
session = self.player.connection.session
deck = models.Deck.find(session, account, name)
if not deck:
self.player.notify(self.player._("Deck not found."))
return
if deck.public == pub:
if pub:
self.player.notify(self.player._("This deck is already public."))
else:
self.player.notify(self.player._("This deck is already private."))
return
if pub:
# performing several checks
# making unfinished decks publically available doesn't make sense
content = json.loads(deck.content)
main, extra = self.player.count_deck_cards(content['cards'])
if main < 40 or main > 60:
self.player.notify(self.player._("Your main deck must contain between 40 and 60 cards (currently %d).") % main)
return
if extra > 15:
self.player.notify(self.player._("Your extra deck may not contain more than 15 cards (currently %d).")%extra)
return
deck.public = pub
session.commit()
if pub:
self.player.notify(self.player._("This deck is now public."))
else:
self.player.notify(self.player._("This deck is no longer public."))
def list(self, cards):
pl = self.player
db = globals.language_handler.primary_database
codes = set(cards)
# this will filter all unknown cards
res = [r[0] for r in db.execute('SELECT id FROM datas WHERE id IN ({0})'.format(', '.join([str(c) for c in codes]))).fetchall()]
cards = list(filter(lambda c: c in res, cards))
groups = self.group_sort_cards(cards)
monsters, spells, traps, extra, other = groups
i = 1
if len(monsters):
pl.notify(pl._("monsters (%d):")%(sum(monsters.values())))
for code, count in monsters.items():
card = Card(code)
if count > 1:
pl.notify("%d: %s (x %d)" % (i, card.get_name(pl), count))
else:
pl.notify("%d: %s" % (i, card.get_name(pl)))
i += 1
if len(spells):
pl.notify(pl._("spells (%d):")%(sum(spells.values())))
for code, count in spells.items():
card = Card(code)
if count > 1:
pl.notify("%d: %s (x %d)" % (i, card.get_name(pl), count))
else:
pl.notify("%d: %s" % (i, card.get_name(pl)))
i += 1
if len(traps):
pl.notify(pl._("traps (%d):")%(sum(traps.values())))
for code, count in traps.items():
card = Card(code)
if count > 1:
pl.notify("%d: %s (x %d)" % (i, card.get_name(pl), count))
else:
pl.notify("%d: %s" % (i, card.get_name(pl)))
i += 1
if len(extra):
pl.notify(pl._("extra (%d):")%(sum(extra.values())))
for code, count in extra.items():
card = Card(code)
if count > 1:
pl.notify("%d: %s (x %d)" % (i, card.get_name(pl), count))
else:
pl.notify("%d: %s" % (i, card.get_name(pl)))
i += 1
class URLParseError(Exception):
pass
def parse_ydke(url):
if url.startswith('ydke://'):
s = url[7:]
else:
raise URLParseError
components = s.split('!')
try:
components = [base64.decodebytes(c.encode('ascii')) for c in components]
except binascii.Error:
raise URLParseError
components = [struct.unpack('<%di' % (len(c) / 4), c) for c in components]
deck = {"cards": components[0] + components[1]}
if len(components) > 2:
deck['side'] = components[2]
return deck
def deck_to_ydke(deck):
cards = struct.pack('<%di' % len(deck['cards']), *deck['cards'])
cards = base64.standard_b64encode(cards).decode('ascii')
side = struct.pack('<%di' % len(deck.get('side', [])), *deck.get('side', []))
side = base64.standard_b64encode(side).decode('ascii')
return 'ydke://%s!!%s' % (cards, side)