forked from JMoore11235/GU_Deck_Tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1344 lines (1066 loc) · 43.3 KB
/
main.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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf8 -*-
###########
# Imports #
###########
from time import sleep
import sys
import webbrowser
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QVBoxLayout, QPushButton, QLabel, QLineEdit, QSizePolicy, QComboBox
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QFont, QPalette, QColor, QIcon
from PyQt5.QtWebEngineWidgets import QWebEngineView
import getpass
import os
import urllib.request
import re
import subprocess
import json
import pydash as py_
from pprint import pprint
from utils.net import getDeckFromAPI, getPlayerIdFromLatestMatches
from utils.player import Player
from utils.globals import GU_DATA, ENCODING, GU_DECKS_PLAYER_PAGE_BASE
from utils.deck import ROW_LENGTH, findCard
from version import VERSION as localVersion
#########################
# Global variables #
#########################
player = None
opponent = None
playerId = None
opponentId = None
opponentGod = 'death'
gameId = None
firstPlayerId = None
needUpdateOpponentDeck = False
localLowPath = f'{os.getenv("APPDATA")}/../LocalLow/'
guLogPath = './Immutable/gods/'
netDataSyncFilePath = f'{localLowPath}{guLogPath}/netdatasync_client/netdatasync_client_info.txt'
assetDownloaderFilePath = f'{localLowPath}{guLogPath}/asset_downloader/asset_downloader_info.txt'
debugFilePath = f'{localLowPath}{guLogPath}/debug.log'
outputLogSimpleFilePath = f'{localLowPath}{guLogPath}/../../output_log_simple.txt'
combatFilePath = f'{localLowPath}{guLogPath}/combat.log'
HTML_TEMPLATE = '''
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home page</title>
<style type="text/css">
body {
background-color: #1d1d1d;
display: flex;
flex-direction: row;
justify-content: space-between;
color: #fff;
font-family: Consolas;
}
.hidden {
display: none;
}
.common, .common:hover{
color: #e6e6e6;
}
.common-background{
background-color: #e6e6e6;
}
.common-word-color, .common-word-color:hover{
color: #bdb988;
}
.rare, .rare:hover{
color: #42a5f5;
}
.rare-background{
background-color: #42a5f5;
}
.epic, .epic:hover{
color: #ba68c8;
}
.epic-background{
background-color: #ba68c8;
}
.legendary, .legendary:hover{
color: #ffca28;
}
.legendary-background{
background-color: #ffca28;
}
.mythic, .mythic:hover{
color: #ef5350
}
.mythic-background{
background-color: #ef5350
}
#deck-list-god-image-area{
display: inline-block;
margin-top: 10px;
width: 240px;
height: 50px;
background-position: 0% -80%;
background-size: cover;
border: 3px solid #505050;
border-radius: 6px;
}
#deck-list{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#deck-list:not(:last-child){
margin-bottom: 10px;
}
.deck-list-item-wrapper{
display: flex;
align-items: center;
}
.deck-list-item-wrapper:not(:last-child){
margin-bottom: 1px;
}
.deck-list-item{
display : flex;
justify-content: center;
align-items: center;
color:white;
font-size: 1.3em;
cursor: pointer;
width: fit-content;
}
.deck-list-item-unowned{
opacity: .5;
}
.deck-list-item:hover {
filter: brightness(1.2);
}
.deck-list-item-name-border{
display: flex;
font-size: .7em;
width: 250px;
border: 1px solid rgb(80, 80, 80);
position: relative;
padding: 5px;
}
.god-power-list-item-name-border{
width: 10.5em;
border: 2px solid rgb(185, 161, 94);
position: relative;
padding: 0 0 0 1.3em;
border-radius: 6px;
}
.deck-list-item-background{
position: absolute;
background-size: cover;
background-position-y: 20%;
opacity: .9;
top: 0;
left: 45%;
bottom: 0;
right: 5%;
z-index: 0;
}
.deck-list-item-background-unowned{
filter:saturate(.5);
}
.deck-list-item-background-fade{
position: absolute;
background-image: linear-gradient(to right, #1d1d1d, #1d1d1d00);
top: 0;
left: 45%;
bottom: 0;
right: 30%;
z-index: 0;
}
.deck-list-item-background-fade-right{
position: absolute;
background-image: linear-gradient(to right, #1d1d1d00, #1d1d1d);
top: 0;
left: 78%;
bottom: 0;
right: 4.5%;
z-index: 0;
}
.deck-list-item-name{
text-overflow: ellipsis;
/* required for ellipsis */
overflow: hidden;
white-space: nowrap;
text-align: left;
flex-grow: 1;
z-index: 1;
}
.deck-list-item-count{
margin-right: 15px;
z-index: 1;
}
.deck-list-item-rarity-strip{
position: absolute;
top: 0;
left: 98%;
bottom: 0;
right: 0;
z-index: 0;
}
.deck-list-item-percentage{
margin-left: 10px;
color:darkgrey;
}
div.tooltip img {
z-index: 10;
display: none;
background: gray;
height: 400px;
}
div.tooltip:hover img{
display:inline; position:absolute;
top: 0px;
background: transparent;
}
div.tooltip-left:hover img{
right: 0px;
}
div.tooltip-right:hover img{
left: 0px;
}
div.tooltip-top:hover img{
top: 300px;
}
div.tooltip-bottom:hover img{
bottom: 0px;
}
</style>
</head>
<body>
<div class="me">
[me_DECKS]
</div>
<div class="opponent">
[opponent_DECKS]
</div>
</body>
</html>
'''
#########################
# PyInstaller Functions #
#########################
# Taken from: https://www.titanwolf.org/Network/q/8250536f-04b3-423a-8833-b76bf07cdb89/y
# This is needed to wrap text files into the .exe while still allowing the tracker to be used in .py form
# Input: Relative path to a file that will be wrapped in the .exe file
# Output: Valid path to that file whether or not it's wrapped in the .exe file
def resource_path(rel_path):
# This is the path added when run in the .exe file
try:
base_path = sys._MEIPASS
# This throws an exception when not in the .exe, so just use the local directory
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, rel_path)
####################
# Config Functions #
####################
# Input: Config file, line of config to update, and the value to update it to.
# Output: Just returns the updatedValue input
# Additional functionality: Updates the config file
def updateConfig(configFile, lineToChange, updatedValue):
conFile = open(configFile, "r", encoding=ENCODING)
lines = conFile.readlines()
conFile.close()
found = False
for n in range(len(lines)):
if (lines[n].split("::==")[0] == lineToChange):
lines[n] = lineToChange + "::==" + str(updatedValue) + "\n"
found = True
break
# If the value to change doesn't exist, return -1
if (not found):
return -1
conFile = open(configFile, "w", encoding=ENCODING)
conFile.writelines(lines)
conFile.close()
return updatedValue
# config.txt Line Number -> Value:
# 0 -> Text Font (textFont)
# 1 -> Text Size (textSize)
# 2 -> Opacity (opacity)
# 3 -> Log File Path (logFolderPath)
# 4 -> Show Deck Tracker (deckTracker)
# Input: Config file and the line of config to return (see above for correct line)
# Output: The requested value
def getConfigVal(configFile, lineHeader):
conFile = open(configFile, "r", encoding=ENCODING)
lines = conFile.readlines()
conFile.close()
for line in lines:
splitLines = line.split("::==")
if (splitLines[0] == lineHeader):
return splitLines[1].strip()
# We didn't find the header
return -1
#####################
# Tracker Functions #
#####################
# Output: None
# Additional Functionality: Opens the opponent's gudecks page in a new tab of their default browser
def getOpponentWebpage(logFolderPath):
global opponentId
if (not opponentId):
return -1
webbrowser.open((f'{GU_DECKS_PLAYER_PAGE_BASE}{opponentId}'), new=2, autoraise=True)
return 1
def getOpponentDeck(god, needUpdate):
if (opponent.hasDeckList and not needUpdate):
return
opponentGod = god
# global outputLogSimpleFilePath
# with open(outputLogSimpleFilePath, "r", encoding=ENCODING) as f:
# file = f.read()
# opponentGod = re.findall("Set God Color: (\w+)", file)[-1].lower()
print('getOpponentDeck', opponentId, opponentGod)
(deck, archetype, stats) = getDeckFromAPI(
opponentId, opponentGod, useMock=False)
[god, *cardIds] = deck.split(',')
return (god, cardIds, archetype, stats)
# Output: A list of tuples representing the player's starting deck
# Error codes: -1 -> No valid file found; -2 -> No deck within file found
def getStartingCardIds():
# TODO: get actual player cards
return [100071]
global assetDownloaderFilePath
# Can't find the log file for some reason
if (not os.path.exists(assetDownloaderFilePath)):
return -1
with open(assetDownloaderFilePath, "r", encoding=ENCODING) as assetFile:
numCardsFound = 0
artIdList = []
for line in assetFile:
if ("LoadOrDownloadAssetBundle: " in line):
artId = line.split("LoadOrDownloadAssetBundle: ")[1].strip()
artIdList.append(artId.upper())
numCardsFound += 1
# player deck = first 30 cards
if (numCardsFound == 30):
break
cardIds = []
for artId in artIdList:
card = findCard(artId=artId)
cardIds.append(card["id"])
print('cardIds', cardIds)
return cardIds
def getDecksStr():
global playerId, opponentId, player, opponent
if not playerId or not opponentId:
return ''
playerDeckLines = str(player.deck).split('\n')
opponentDeckLines = str(opponent.deck).split('\n')
spacer = ' ' * ROW_LENGTH
rows = []
for index in range(max([len(playerDeckLines), len(opponentDeckLines)])):
rows.append(f'{py_.get(playerDeckLines, index, spacer): ^{ROW_LENGTH}}{py_.get(opponentDeckLines, index, spacer): >{ROW_LENGTH}}')
return "\n".join(rows)
def resetPlayersData():
print('resetPlayersData')
global playerId, opponentId, firstPlayerId, player, opponent
playerId = opponentId = firstPlayerId = player = opponent = None
def setPlayers():
global playerId, opponentId, player, opponent, opponentGod
if playerId and opponentId and player and opponent:
return
print('set players')
try:
global debugFilePath
with open(debugFilePath, "r", encoding=ENCODING) as f:
file = f.read()
ids = re.search(
"Initialising.*?p:PlayerInfo\(apolloId:\s(\d+).*?o:PlayerInfo\(apolloId:\s(\d+)", file).groups()
playerId = int(ids[0])
opponentId = int(ids[1])
opponentGod = re.search(f"playerID:'{opponentId}'.*targetGod:'(\w+)'", file).groups()[0].lower()
print(f'player ids: {playerId} vs {opponentId} ({opponentGod})')
player = Player(id=playerId, type="me")
opponent = Player(id=opponentId, type="opponent")
except:
print('cant set players')
def setFirstPlayerId():
global firstPlayerId
if firstPlayerId:
return
try:
global debugFilePath
with open(debugFilePath, "r", encoding=ENCODING) as f:
file = f.read()
firstPlayerId = int(
re.search("playerID:'(\d+)'.*targetName:'StartTurnCardDraw'", file).groups()[0])
print('firstPlayerId', firstPlayerId)
except:
print('not found firstPlayerId')
def getGameId():
try:
global debugFilePath
with open(debugFilePath, "r", encoding=ENCODING) as f:
file = f.read()
gameId = re.search("gameID:\s'([\w-]+)'", file).groups()[0]
print(f"gameId {gameId}")
return gameId
except:
print('cant get game id')
def processCombatRecorder():
global firstPlayerId
global combatFilePath
playerIds = [player.id, opponent.id]
if (player.id != firstPlayerId):
playerIds = playerIds[:: -1]
# todo: rewrite this
cards = {
playerIds[0]: {
'drawnCardIds': [],
'playedCardIds': []
},
playerIds[1]: {
'drawnCardIds': [],
'playedCardIds': []
}
}
try:
with open(combatFilePath, "r", encoding=ENCODING) as f:
# file = f.read().split('00:03:18.03')[0]
file = f.read()
# print(cards)
# todo: find 3 first drew card only (mulligan)
for name in re.findall('Drew Card: (.*)$', file, re.MULTILINE)[:3]:
card = findCard(name=name)
if card:
cards[player.id]['drawnCardIds'].append(card["id"])
turns = re.findall("Event:\sDraw.*?EndTurn", file,
re.MULTILINE | re.DOTALL)
lastTurn = file.split('StatEvent: Refresh')[-1]
# add current not finished turn
if 'EndTurn' not in lastTurn:
turns.append(lastTurn)
for (index, turn) in enumerate(turns):
currentPlayerId = playerIds[index % 2]
# print(f"\n{'_' * ROW_LENGTH}\nturn {currentPlayerId}")
# print(turn)
for name in re.findall('Drew Card: (.*)$', turn, re.MULTILINE):
# print(f'draw - {name}')
card = findCard(name=name)
if card:
cards[currentPlayerId]['drawnCardIds'].append(
card["id"])
for name in re.findall('Played \| Card: (.*)\|$', turn, re.MULTILINE):
# print(f'play - {name}')
card = findCard(name=name.strip())
if card["id"] == -1:
# don't add unknown cards to played list (cards with choice - Tracking Bolt)
# print('unknown', name)
continue
if card:
cards[currentPlayerId]['playedCardIds'].append(
card["id"])
# pprint(cards)
# sys.exit()
for playerId in playerIds:
currentPlayer = player if player.id == playerId else opponent
currentPlayer.deck.playedCardIds = cards[playerId]['playedCardIds']
currentPlayer.deck.drawnCardIds = cards[playerId]['drawnCardIds']
except Exception as ex:
print(ex)
print('error while processing combat log')
global gameId
currentGameId = getGameId()
if gameId != currentGameId:
gameId = currentGameId
print('new game started')
resetPlayersData()
#################
# GUI Functions #
#################
# Calls getOpponentsWebpage, but if it errors, provides an error warning to the user
def opponentsWebpage(logFolderPath):
res = getOpponentWebpage(logFolderPath)
if (res == -1):
alert = QMessageBox()
alert.setText(
'Opponent User ID Not Found. Please try again in a few seconds. [Debugging Code: 0201]')
alert.exec()
elif (res == -2):
alert = QMessageBox()
alert.setText(
'No valid log file found. Please check path. [Debugging Code: 0202]')
alert.exec()
def toggleConfigBoolean(configFile, key):
currVal = getConfigVal(configFile, key) == 'True'
print('toggleConfigBoolean', key, currVal, not currVal)
updateConfig(configFile, key, not currVal)
if key == 'deckTracker' and not currVal:
resetPlayersData()
pass
# Main Window which includes the deck tracker
class MainWindow(QWidget):
def __init__(self, windowTitle, windowIcon, configFile):
super().__init__()
#################
# Initial Setup #
#################
self.__press_pos = QPoint()
# Setting all the inputs to "self.X" values so I can use it in update
self.windowTitle = windowTitle
self.windowIcon = windowIcon
self.configFile = configFile
# Find and set initial preference values
global playerId, firstPlayerId
# playerId = getConfigVal(configFile, "playerId")
# firstPlayerId = playerId
self.textFont = getConfigVal(configFile, "textFont")
self.textSize = int(getConfigVal(configFile, "textSize"))
self.opacity = float(getConfigVal(configFile, "opacity"))
self.logFolderPath = getConfigVal(configFile, "logFolderPath")
positionX = int(getConfigVal(configFile, "positionX"))
positionY = int(getConfigVal(configFile, "positionY"))
# move window to last position
if positionX and positionY:
self.move(positionX, positionY)
# Always start with the deck tracker disabled, regardless of previous settings
updateConfig(configFile, "deckTracker", False)
self.showTracker = False
self.htmlHash = None
# This is so that we don't spam the user with tons of warnings if a log file can't be found
self.warnedAboutLogFile = False
# This keeps track of the last log path we warned about, so we know if we should update warnedAboutLogFile
self.warnedlogFolderPath = ""
###############################
# Creation of the Main Window #
###############################
# self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self.tempWindow = None
self.layout = QVBoxLayout()
self.setWindowTitle(windowTitle)
self.setWindowIcon(QIcon(windowIcon))
self.setSizePolicy(
QSizePolicy.Expanding, QSizePolicy.Expanding
)
buttonSize = (30, 30)
iconSize = 12
self.layoutButtons = QHBoxLayout()
self.opponentPageButton = QPushButton("🌐", self)
self.opponentPageButton.setFixedSize(*buttonSize)
# I wanted to call this, but you have to do the line beneath it instead for some reason:
# self.opponentPageButton.clicked.connect(opponentsWebpage(logFolderPath))
self.opponentPageButton.clicked.connect(
lambda i: opponentsWebpage(self.logFolderPath))
self.opponentPageButton.setFont(QFont(self.textFont, iconSize))
self.layoutButtons.addWidget(self.opponentPageButton)
self.settingsButton = QPushButton("⚙", self)
self.settingsButton.setFixedSize(*buttonSize)
self.settingsButton.clicked.connect(self.settings)
self.settingsButton.setFont(QFont(self.textFont, iconSize))
self.layoutButtons.addWidget(self.settingsButton)
self.toggleDeckTrackerButton = QPushButton("+", self)
self.toggleDeckTrackerButton.setFixedSize(*buttonSize)
self.toggleDeckTrackerButton.clicked.connect(
lambda i: toggleConfigBoolean(self.configFile, "deckTracker"))
self.toggleDeckTrackerButton.clicked.connect(self.update)
self.toggleDeckTrackerButton.setFont(QFont(self.textFont, iconSize))
self.layoutButtons.addWidget(self.toggleDeckTrackerButton)
self.pinButton = QPushButton("📌", self)
self.pinButton.setFixedSize(*buttonSize)
self.pinButton.setShortcut("Ctrl+d") # shortcut key
self.pinButton.clicked.connect(self.savePosition)
self.pinButton.setFont(QFont(self.textFont, iconSize))
self.layoutButtons.addWidget(self.pinButton)
self.closeButton = QPushButton("X", self)
self.closeButton.setFixedSize(*buttonSize)
self.closeButton.setShortcut("Ctrl+q") # shortcut key
self.closeButton.clicked.connect(self.close)
self.closeButton.setFont(QFont(self.textFont, iconSize))
self.layoutButtons.addWidget(self.closeButton)
self.layout.addLayout(self.layoutButtons)
self.layoutPlayersData = QHBoxLayout()
self.opponentId = QLineEdit("")
self.opponentId.setFont(QFont(self.textFont, self.textSize))
self.layoutPlayersData.addWidget(self.opponentId)
self.opponentGod = QComboBox()
self.opponentGod.addItems(
["death", "deception", "light", "magic", "nature", "war"])
self.opponentGod.setFont(QFont(self.textFont, self.textSize))
self.layoutPlayersData.addWidget(self.opponentGod)
self.confirmButton = QPushButton("V", self)
self.confirmButton.clicked.connect(self.confirm)
self.confirmButton.setFont(QFont(self.textFont, self.textSize))
self.layoutPlayersData.addWidget(self.confirmButton)
self.firstPlayerButton = QPushButton("<>", self)
self.firstPlayerButton.clicked.connect(self.changeFirstPlayer)
self.firstPlayerButton.setFont(QFont(self.textFont, self.textSize))
self.layoutPlayersData.addWidget(self.firstPlayerButton)
self.layout.addLayout(self.layoutPlayersData)
self.deckTrackerLabel = QLabel()
self.deckTrackerLabel.hide()
self.deckTrackerLabel.setFont(QFont(self.textFont, self.textSize))
if (self.showTracker):
self.layout.addWidget(self.deckTrackerLabel)
self.webEngineView = QWebEngineView()
self.webEngineView.setHtml('<div>hello</div>')
self.webEngineView.setSizePolicy(
QSizePolicy.Maximum, QSizePolicy.Maximum)
self.webEngineView.setMinimumSize(400, 900)
# self.webEngineView.setMinimumSize(400, 620)
self.webEngineView.setZoomFactor(0.9)
print(self.sizeHint())
print(self.webEngineView.sizeHint())
print(self.webEngineView.size())
self.webEngineView.resize(self.size())
# self.webEngineView.setWindowFlags(Qt.FramelessWindowHint)
# self.webEngineView.setAttribute(Qt.WA_TranslucentBackground, True)
self.layout.addWidget(self.webEngineView)
self.setLayout(self.layout)
self.show()
# Update once per interval
self.my_timer = QtCore.QTimer()
self.my_timer.timeout.connect(self.update)
# todo: start immediately
# self.my_timer.start(5000) # 5 sec
self.my_timer.start(1000) # 1 sec
# Constantly looping update to keep the deck tracker up to date
def update(self):
######################
# Update Preferences #
######################
# print('update tick')
# Find and set current preference values
self.textFont = getConfigVal(configFile, "textFont")
self.textSize = int(getConfigVal(configFile, "textSize"))
self.opacity = float(getConfigVal(configFile, "opacity"))
self.logFolderPath = getConfigVal(configFile, "logFolderPath")
self.showTracker = True
if (getConfigVal(configFile, "deckTracker") == "False"):
self.showTracker = False
# Update Tracker based on new settings
self.toggleDeckTrackerButton.setText("-" if self.showTracker else "+")
self.deckTrackerLabel.setFont(QFont(self.textFont, self.textSize))
self.setWindowOpacity(self.opacity)
# If we have a different path than the one we previously warned about, we have no longer warned about the
# current log file
if (self.warnedlogFolderPath != self.logFolderPath):
self.warnedAboutLogFile = False
########################
# Update the deck list #
########################
decksText = ''
decksHtml = '<div>decks</div>'
global player, playerId, opponent, opponentId, opponentGod, needUpdateOpponentDeck
if self.showTracker:
setPlayers()
if not playerId or not player or not opponentId:
return
if not player.hasDeckList:
print('not found my deck')
startingCardIds = getStartingCardIds()
player.deck.setDeckList('player', startingCardIds)
if needUpdateOpponentDeck or not opponent.hasDeckList:
print('not found opponent deck')
(god, startingCardIds, archetype, stats) = getOpponentDeck(
opponentGod, needUpdate=needUpdateOpponentDeck)
opponent.deck.setDeckList(god, startingCardIds, archetype, stats)
needUpdateOpponentDeck = False
setFirstPlayerId()
processCombatRecorder()
# decksText = getDecksStr()
if player and opponent and player.hasDeckList and opponent.hasDeckList:
meHtml = player.asHtml()
opponentHtml = opponent.asHtml()
decksHtml = HTML_TEMPLATE.replace(f'[me_DECKS]', meHtml).replace(f'[opponent_DECKS]', opponentHtml)
# open('my.html', 'w').write(decksHtml.encode('utf8').decode('ascii', 'ignore'))
self.deckTrackerLabel.setText(decksText)
newHash = hash(decksHtml)
if (self.htmlHash != newHash):
self.webEngineView.setHtml(decksHtml)
self.htmlHash = newHash
if (self.showTracker):
self.layout.addWidget(self.deckTrackerLabel)
else:
self.layout.removeWidget(self.deckTrackerLabel)
# self.setLayout(self.layout)
# self.adjustSize()
def settings(self):
self.tempWindow = SettingsWindow(self.windowTitle, self.configFile)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.__press_pos = event.pos()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.__press_pos = QPoint()
def mouseMoveEvent(self, event):
if not self.__press_pos.isNull():
self.move(self.pos() + (event.pos() - self.__press_pos))
def savePosition(self):
point = self.pos()
updateConfig(configFile, "positionX", point.x())
updateConfig(configFile, "positionY", point.y())
def confirm(self):
global opponentId, opponentGod, needUpdateOpponentDeck
opponentId = int(self.opponentId.text() or opponentId)
opponentGod = self.opponentGod.currentText()
needUpdateOpponentDeck = True
print(f'opponent id={opponentId} god={opponentGod}')
def changeFirstPlayer(self):
global playerId, opponentId, firstPlayerId
firstPlayerId = playerId if firstPlayerId != playerId else opponentId
class SettingsWindow(QWidget):
def __init__(self, windowTitle, configFile):
super().__init__()
# Setting all the inputs to "self.X" values so I can use it in confirm
self.configFile = configFile
# Find and set current preference values
self.textFont = getConfigVal(configFile, "textFont")
self.textSize = int(getConfigVal(configFile, "textSize"))
self.opacity = float(getConfigVal(configFile, "opacity"))
self.logFolderPath = getConfigVal(configFile, "logFolderPath")
# We don't need deckTracker
self.setWindowOpacity(self.opacity)
self.setWindowTitle(windowTitle)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self.layout = QVBoxLayout()
self.updateNotify = True
strToDisplay = "(Currently Enabled)"
if (getConfigVal(self.configFile, "updateNotify") == "False"):
self.updateNotify = False
strToDisplay = "(Currently Disabled)"
self.updateNotifyButton = QPushButton(
"Toggle Update Notifications " + strToDisplay, self)
self.updateNotifyButton.clicked.connect(
lambda i: toggleConfigBoolean(self.configFile, "updateNotify"))
self.updateNotifyButton.clicked.connect(self.updateText)
self.updateNotifyButton.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.updateNotifyButton)
strToDisplay = "(Currently Enabled)"
if (getConfigVal(self.configFile, "autoUpdate") == "False"):
self.updateNotify = False
strToDisplay = "(Currently Disabled)"
self.autoUpdateButton = QPushButton(
"Toggle Automatic Updates " + strToDisplay, self)
self.autoUpdateButton.clicked.connect(
lambda i: toggleConfigBoolean(self.configFile, "autoUpdate"))
self.autoUpdateButton.clicked.connect(self.updateText)
self.autoUpdateButton.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.autoUpdateButton)
self.textSizeLabel = QLabel(
"Enter desired text size (Currently " + str(self.textSize) + "):")
self.textSizeLabel.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.textSizeLabel)
self.textSizeEdit = QLineEdit("")
self.textSizeEdit.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.textSizeEdit)
self.textFontLabel = QLabel(
"Enter desired text font (Currently " + str(self.textFont) + "):")
self.textFontLabel.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.textFontLabel)
self.textFontEdit = QLineEdit("")
self.textFontEdit.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.textFontEdit)
self.opacityLabel = QLabel("Enter desired opacity (Currently " +
str(self.opacity) + "; Range 0.25-1):")
self.opacityLabel.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.opacityLabel)
self.opacityEdit = QLineEdit("")
self.opacityEdit.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.opacityEdit)
self.pathLabel = QLabel("Enter path to 'FuelGames' log folder:")
self.pathLabel.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.pathLabel)
self.pathEdit = QLineEdit("")
self.pathEdit.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.pathEdit)
self.confirmButton = QPushButton("Apply", self)
self.confirmButton.clicked.connect(self.confirm)
self.confirmButton.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.confirmButton)
self.cancelButton = QPushButton("Cancel", self)
self.cancelButton.clicked.connect(self.cancel)
self.cancelButton.setFont(QFont(self.textFont, self.textSize))
self.layout.addWidget(self.cancelButton)
self.setLayout(self.layout)
self.show()
def updateText(self):
self.updateNotify = True
strToDisplay = "(Currently Enabled)"
if (getConfigVal(self.configFile, "updateNotify") == "False"):
self.updateNotify = False
strToDisplay = "(Currently Disabled)"
self.updateNotifyButton.setText(
"Toggle Update Notifications " + strToDisplay)
strToDisplay = "(Currently Enabled)"
if (getConfigVal(self.configFile, "autoUpdate") == "False"):
self.updateNotify = False
strToDisplay = "(Currently Disabled)"
self.autoUpdateButton.setText(
"Toggle Automatic Updates " + strToDisplay)
def confirm(self):
# 0 (Text Font)
if (not str(self.textFontEdit.text()) == ""):
updateTextFont = self.textFontEdit.text()
updateConfig(self.configFile, "textFont", updateTextFont)
# 1 (Text Size)