-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSteamRoulette.py
More file actions
1572 lines (1266 loc) · 70.8 KB
/
SteamRoulette.py
File metadata and controls
1572 lines (1266 loc) · 70.8 KB
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
import os
import io
import random
import platform
import webbrowser
import requests
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageDraw, ImageFont, ImageTk
from io import BytesIO
import json
import vdf
import sys
from concurrent.futures import ThreadPoolExecutor
import time
import winreg
import threading
from functools import lru_cache
def create_cache_directory():
"""Ensure the cache directory exists."""
# Define the path to store cached images
cache_dir = os.path.join(os.path.dirname(sys.executable), "image_cache")
# Check if the directory exists, create it if it doesn't
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
print(f"Cache directory created at: {cache_dir}")
else:
print(f"Cache directory already exists at: {cache_dir}")
return cache_dir
def get_steam_install_path():
try:
# Open the registry key where Steam installation path is stored
registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam")
# Get the value of "SteamPath"
steam_path, _ = winreg.QueryValueEx(registry_key, "SteamPath")
return steam_path
except FileNotFoundError:
print("Steam installation not found in the registry.")
return None
def find_steam_path_fallback():
common_paths = [
r"C:\Program Files (x86)\Steam",
r"C:\Program Files\Steam",
os.path.expanduser("~\\AppData\\Local\\Steam"), # Potential user-specific path
]
for path in common_paths:
if os.path.exists(os.path.join(path, "steam.exe")):
return path
return None
def resource_path(relative_path):
"""Get the absolute path to the resource, works for both development and PyInstaller."""
try:
base_path = sys._MEIPASS # PyInstaller temp directory
except Exception:
base_path = os.path.dirname(os.path.abspath(__file__)) # Development mode
resolved_path = os.path.join(base_path, relative_path)
print(f"Resolved path for {relative_path}: {resolved_path}") # Debugging output
return resolved_path
# Constants
STEAM_PATH = get_steam_install_path() or find_steam_path_fallback()
ICON_PATH = resource_path("SteamRouletteIcon.ico")
IMAGE_PATH = os.path.dirname(os.path.abspath(__file__))
PLACEHOLDER_IMAGE_DIMENSIONS = (600, 300)
# Utility Functions
def parse_vdf(file_path):
"""Parse a VDF file and return its content."""
try:
with open(file_path, "r", encoding="utf-8") as file:
content = vdf.parse(file)
# Extract library folders from the parsed VDF
libraries = content.get("libraryfolders", {})
return {key: value.get("path") for key, value in libraries.items() if isinstance(value, dict) and "path" in value}
except Exception as e:
print(f"Error parsing VDF file: {e}")
return {}
@lru_cache(maxsize=None)
def fetch_game_data(acf_path, library_path):
"""Extract game data from an ACF file and include the library path."""
try:
with open(acf_path, "r", encoding="utf-8") as file:
content = vdf.parse(file).get("AppState", {})
game_data = {
"app_id": content.get("appid"),
"name": content.get("name"),
"path": library_path # Include the path to the game
}
return game_data
except Exception as e:
print(f"Error reading ACF file {acf_path}: {e}")
return {}
@lru_cache(maxsize=1000)
def fetch_header_image(app_id, cache_dir, timeout=10):
"""Fetch game header image from Steam or return a placeholder."""
cache_file_path = os.path.join(cache_dir, f"{app_id}.jpg")
if os.path.exists(cache_file_path):
print(f"Using cached image for app_id {app_id}")
return Image.open(cache_file_path) # Open the cached image
# If not cached, fetch from Steam
urls = [
f"https://cdn.cloudflare.steamstatic.com/steam/apps/{app_id}/header.jpg",
f"https://cdn.cloudflare.steamstatic.com/steam/apps/{app_id}/page_bg.jpg",
]
for url in urls:
try:
response = requests.get(url, timeout=timeout)
if response.status_code == 200:
img = Image.open(BytesIO(response.content))
img.save(cache_file_path, "JPEG") # Save it to the cache
return img
except Exception as e:
print(f"Error fetching image for app_id {app_id}: {e}")
print(f"No valid image found for app_id {app_id}. Using placeholder.")
return create_placeholder_image("Image Unavailable")
def create_placeholder_image(text):
"""Generate a placeholder image."""
img = Image.new("RGB", PLACEHOLDER_IMAGE_DIMENSIONS, color=(255, 255, 255))
draw = ImageDraw.Draw(img)
font = ImageFont.load_default()
# Use textbbox to calculate text size
bbox = draw.textbbox((0, 0), text, font=font)
text_size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
# Position the text in the center of the image
draw.text(
((img.width - text_size[0]) / 2, (img.height - text_size[1]) / 2),
text,
font=font,
fill="black",
)
return img
def get_installed_games(steam_path):
"""Scan for installed games in Steam library."""
library_folders = parse_vdf(os.path.join(steam_path, "steamapps", "libraryfolders.vdf"))
installed_games = []
for library_path in library_folders.values():
if library_path and isinstance(library_path, str):
steamapps_path = os.path.join(library_path, "steamapps")
if os.path.exists(steamapps_path):
for acf_file in filter(lambda f: f.endswith(".acf"), os.listdir(steamapps_path)):
game = fetch_game_data(os.path.join(steamapps_path, acf_file), library_path)
if game and game.get("app_id"): # Validate app_id here
installed_games.append(game)
else:
print(f"Excluded invalid game: {game}")
return installed_games
def fetch_steam_user_id(self, api_key):
"""Automatically fetch the Steam User ID using the API key."""
url = "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/"
params = {
"key": api_key,
"steamids": "76561197960287930" # This is a placeholder; we will replace it dynamically
}
try:
# Request the player summary
response = requests.get(url, params=params, timeout=10)
response.raise_for_status() # Check if the response is successful
data = response.json()
# Check if we received valid player data
if "response" in data and "players" in data["response"]:
player_info = data["response"]["players"][0]
steam_id = player_info.get("steamid")
print(f"Successfully fetched Steam User ID: {steam_id}")
return steam_id
else:
print("Could not fetch Steam User ID.")
return None
except Exception as e:
print(f"Error fetching Steam User ID: {e}")
return None
def get_all_games(api_key, steam_id):
"""Fetch all games owned by the user via the Steam API."""
url = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v1/"
params = {
"key": api_key,
"steamid": steam_id,
"include_appinfo": True, # Include app info (app_id, name, etc.)
"include_played_free_games": True # Include free-to-play games
}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
# Log the full response to check if app_id exists
print(f"Full Response from Steam API: {data}")
if "response" in data and "games" in data["response"]:
games = data["response"]["games"]
print(f"Fetched {len(games)} games from the Steam API.")
return games
else:
print("No games found in the response.")
return []
except Exception as e:
print(f"Error fetching games from Steam API: {e}")
return []
def get_steam_app_list():
"""Fetch the complete list of Steam app IDs."""
url = "https://api.steampowered.com/ISteamApps/GetAppList/v2/"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
if "applist" in data and "apps" in data["applist"]:
app_list = {str(app["appid"]): app["name"] for app in data["applist"]["apps"]}
return app_list
else:
print("Error: No apps found in the response.")
return {}
except Exception as e:
print(f"Error fetching app list from Steam API: {e}")
return {}
def get_uninstalled_games_from_api(api_key, steam_id, installed_games):
"""Fetch uninstalled games using the Steam API."""
all_games = get_all_games(api_key, steam_id)
if not all_games:
print("No games fetched from Steam API.")
return []
installed_ids = {str(game["app_id"]) for game in installed_games}
uninstalled_games = [
{"app_id": str(game["appid"]), "name": game["name"]}
for game in all_games
if str(game["appid"]) not in installed_ids
]
print(f"Uninstalled games detected via API: {len(uninstalled_games)}") # Debugging line
return uninstalled_games
def get_uninstalled_games(installed_games, all_games):
"""Identify uninstalled games based on the library paths."""
# Log the installed and all games data for debugging
print(f"Installed games: {len(installed_games)} games")
print(f"All games: {len(all_games)} games")
# Strip spaces and ensure app_id is consistently formatted
installed_ids = {str(game.get("app_id")).strip() for game in installed_games if game.get("app_id")}
print(f"Installed game IDs: {installed_ids}") # Log installed game IDs
uninstalled_games = []
for game in all_games:
# Safely check if 'app_id' exists in the game dictionary
app_id = str(game.get("app_id")).strip() # Convert to string and strip spaces
if app_id and app_id not in installed_ids:
uninstalled_games.append(game)
print(f"Uninstalled games identified: {len(uninstalled_games)}") # Log number of uninstalled games
return uninstalled_games
def get_drives():
"""Detect all available drives on the system."""
if platform.system() == "Windows":
return [f"{chr(i)}:\\" for i in range(65, 91) if os.path.exists(f"{chr(i)}:\\")]
elif platform.system() == "Linux":
return [line.split()[0] for line in os.popen("df -h --output=source").readlines()[1:]]
elif platform.system() == "Darwin": # macOS
return [line.split()[2] for line in os.popen("mount").readlines()]
return []
# GUI Class
class SteamRouletteGUI:
def __init__(self, root, installed_games, drives):
self.root = root
self.installed_games = installed_games
self.excluded_games = []
self.uninstalled_games = []
self.selected_game = None
self.drives = drives
self.api_key = self.load_api_key()
self.cache_dir = create_cache_directory()
# Define color schemes
self.light_mode_bg = "#ffffff"
self.dark_mode_bg = "#2e2e2e"
self.light_mode_fg = "#000000"
self.dark_mode_fg = "#ffffff"
# Preload the images
self.preloaded_images = {}
# Preload Header Images
self.preload_images()
# Load saved Game Exclusions
self.load_exclusions()
self.canvas_frame = tk.Frame(root, bg=self.light_mode_bg)
self.canvas_frame.pack(pady=5)
# Path to the folder containing the header images
if getattr(sys, 'frozen', False): # If running as an executable
base_path = sys._MEIPASS
else: # If running as a script
base_path = os.path.dirname(os.path.abspath(__file__))
# Initialize animation speed (starting value)
self.initial_animation_speed = 50 # Adjust this as needed
self.animation_speed = self.initial_animation_speed
# Create a frame to contain the game name label and other elements
frame = tk.Frame(self.root, bg=self.light_mode_bg)
frame.pack(side="top", pady=5)
# Apply light mode to the frame
self.update_theme(frame, self.light_mode_bg, self.light_mode_fg)
# Set initial animation speed
self.animation_speed = 200 # Controls the distance moved per frame
self.frame_delay = 16 # Controls the speed of the animation (time between frames)
self.root.title("Steam Roulette")
width = 600
height = 750
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate x and y coordinates for the Tk root window
x = (ws/2) - (width/2)
y = (hs/2) - (height/2)
self.root.geometry('%dx%d+%d+%d' % (width, height, x, y))
self.root.resizable(False, False)
# Define the relative path to the 'header_images' folder
self.header_images_folder = os.path.join((sys.executable), "image_cache")
# Try to load images locally, if they don't exist, fallback to Steam API
if os.path.exists(self.header_images_folder) and os.listdir(self.header_images_folder):
self.header_images = self.load_header_images(self.header_images_folder)
# Canvas
self.canvas = tk.Canvas(self.root, width=600, height=300, bg="black")
self.canvas.pack(pady=1)
print(f"Canvas initialized: {self.canvas}")
# Display a random header image on startup
self.display_random_header_image()
# Label displaying "Games Found on Drives"
self.label_game_count = tk.Label(root, text=self.generate_games_found_text(), font=("Arial", 10))
# Get the width of the window and place the label in the top-right corner
window_width = root.winfo_width() # Get current width of the window
self.label_game_count.place(x=window_width - 5, y=5, anchor='ne') # 10px from the right and 10px from the top
# Label displaying copyright notice in the top-left corner
self.copyright_notice = tk.Label(root, text="© Streetbackguy 2024", font=("Arial", 8))
self.copyright_notice.place(relx=0.0, rely=0.0, anchor='nw', x=5, y=5)
# Welcome label
self.label_welcome = tk.Label(frame, text="Welcome to Steam Roulette!", font=("Arial", 16), bg=self.light_mode_bg)
self.label_welcome.grid(row=1, pady=5)
# Game name label
self.label_game_name = tk.Label(frame, text="", wraplength=600, font=("Arial", 20), bg=self.light_mode_bg)
self.label_game_name.grid(row=2, pady=5)
# Initial theme mode (light mode by default)
self.is_dark_mode = False
# Create a frame for the lower-left corner buttons
self.button_frame = tk.Frame(root, bg=self.light_mode_bg)
self.button_frame.pack(pady=5)
self.button_frame.place(relx=0.0, rely=1.0, anchor='sw', x=2, y=-2) # Padding for the frame
# Button to set the API Key
self.button_set_api_key = tk.Button(self.button_frame, text="Set API Key", command=self.set_api_key, state=tk.NORMAL, font=("Arial", 10))
self.button_set_api_key.grid(row=0, column=0, pady=2, padx=2)
# Create a button to set the Steam User ID manually
self.button_set_user_id = tk.Button(self.button_frame, text="Set Steam User ID", command=self.set_user_id_key, state=tk.NORMAL, font=("Arial", 10))
self.button_set_user_id.grid(row=0, column=1, pady=2, padx=2)
# Button to toggle dark mode
self.button_toggle_theme = tk.Button(self.button_frame, text="Toggle Dark Mode", command=self.toggle_theme, font=("Arial", 10))
self.button_toggle_theme.grid(row=0, column=2, pady=2, padx=2)
try:
# Set the window and taskbar icon
self.root.iconbitmap(ICON_PATH) # Set .ico for the window
self.root.iconphoto(True, tk.PhotoImage(file=ICON_PATH)) # Set taskbar icon
except Exception as e:
print(f"Error setting window icon: {e}")
# Create a frame to contain the game name label and other elements
utility_frame = tk.Frame(self.root, bg=self.light_mode_bg)
utility_frame.pack(pady=5)
# Apply light mode to the utility frame
self.update_theme(utility_frame, self.light_mode_bg, self.light_mode_fg)
# Button to spin the wheel
self.selected_num_games = None
self.button_spin = tk.Button(utility_frame, text="Spin the Wheel", command=self.spin_wheel, font=("Arial", 14))
self.button_spin.grid(row=0, column=0, pady=10, padx=10, sticky="n", columnspan=2)
# Button to launch the selected game
self.button_launch = tk.Button(utility_frame, text="Launch/Install Game", command=self.launch_game, state=tk.DISABLED, font=("Arial", 10))
self.button_launch.grid(row=1, column=0, pady=5, padx=4)
# Button to go to the Steam store for the selected game
self.button_store = tk.Button(utility_frame, text="Steam Storepage", command=self.open_store, state=tk.DISABLED, font=("Arial", 10))
self.button_store.grid(row=1, column=1, pady=5, padx=4)
# Create a container frame to hold the button and label
self.frame_controls = tk.Frame(self.root)
self.frame_controls.place(anchor='w', x=4, y=645)
# Configure columns for centering
for col in range(3): # Assuming a grid with 3 columns for flexibility
self.frame_controls.grid_columnconfigure(col, weight=1)
# Add a button that triggers the popup to input the number of games
self.button_set_number_of_games = tk.Button(self.frame_controls, text="Set Number of Games", command=self.set_number_of_games)
self.button_set_number_of_games.grid(row=0, column=1, pady=2) # Centered in row 0, column 1
# Label to show the number of games selected (initially empty)
self.label_number_of_games = tk.Label(self.frame_controls, text="Number of games to spin:\nAll Games", font=("Arial", 8))
self.label_number_of_games.grid(row=1, column=1, pady=2) # Centered in row 1, column 1
# Exclude Games Button
self.button_exclude = tk.Button(self.frame_controls, text="Exclude Games", command=self.exclude_games, font=("Arial", 10))
self.button_exclude.grid(row=2, column=1, pady=2) # Centered in row 2, column 1
# Excluded Games Count Label
self.excluded_label = tk.Label(self.frame_controls, text=f"Excluded Games:\n{len(self.excluded_games)}", font=("Arial", 8))
self.excluded_label.grid(row=3, column=1, pady=2) # Centered in row 3, column 1
# Create a frame to contain the game name label and other elements
self.yes_no_frame = tk.Frame(self.root, bg=self.light_mode_bg)
self.yes_no_frame.place(relx=1.0, rely=1.0, anchor='se', x=-2, y=-2) # Padding for the frame
# Label to advise waiting when loading
self.please_wait_label = tk.Label(self.yes_no_frame, text="", font="6")
self.please_wait_label.grid(row=0)
# Checkbox to include/exclude uninstalled games
self.include_uninstalled_var = tk.BooleanVar(value=False)
self.include_uninstalled_checkbox = tk.Checkbutton(self.yes_no_frame,text="Include Uninstalled Games",variable=self.include_uninstalled_var,command=self.toggle_uninstalled_games,bg=self.light_mode_bg,fg=self.light_mode_fg,selectcolor=self.light_mode_bg)
self.include_uninstalled_checkbox.grid(sticky="w", row=1)
# Add checkbox for filtering 100% achievement games
self.filter_achievements_var = tk.BooleanVar(value=False)
self.filter_achievements_checkbox = tk.Checkbutton(self.yes_no_frame,text="Exclude 100% Achieved Games",variable=self.filter_achievements_var,command=self.toggle_achievement_filter,bg=self.light_mode_bg,fg=self.light_mode_fg,selectcolor=self.light_mode_bg)
self.filter_achievements_checkbox.grid(sticky="w", row=2)
self.active_images = []
self.selected_game_image = None
self.selected_game_item = None
self.animation_id = None
try:
# Use resource_path to get the correct logo path
logo_path = resource_path("SteamRouletteLogo.png")
print(f"Trying to load logo from: {logo_path}")
if not os.path.exists(logo_path):
raise FileNotFoundError(f"Logo file not found at: {logo_path}")
# Load the logo image
logo_image = Image.open(logo_path)
logo_image_tk = ImageTk.PhotoImage(logo_image)
# Display logo
self.label_logoimage = tk.Label(frame, image=logo_image_tk, bg=self.light_mode_bg)
self.label_logoimage.image = logo_image_tk # Keep reference to avoid garbage collection
self.label_logoimage.grid(row=0, pady=5)
except FileNotFoundError as fnfe:
print(fnfe)
# In case logo or icon is missing, display a fallback message
self.label_logoimage = tk.Label(frame, text="Logo Missing", font=("Arial", 16), bg=self.light_mode_bg)
self.label_logoimage.grid(row=0, pady=5)
except Exception as e:
print(f"Error: {e}")
try:
# Get the path for the .ico file
icon_path = resource_path("SteamRouletteIcon.ico")
print(f"Trying to load icon from: {icon_path}")
# Ensure the icon file exists
if not os.path.exists(icon_path):
raise FileNotFoundError(f"Icon file not found at: {icon_path}")
# Set the window icon
self.root.iconbitmap(icon_path)
print("Window icon successfully set.")
except FileNotFoundError as fnfe:
print(fnfe)
except Exception as e:
print(f"Error setting window icon: {e}")
# Set Light Mode
self.set_light_mode()
# Display a random header image on startup
self.display_random_header_image()
def preload_images(self):
"""Preload images for both installed and uninstalled games using threading."""
def preload_image(game):
app_id = game.get("app_id")
if not app_id or app_id in self.preloaded_images:
return
img = fetch_header_image(app_id, self.cache_dir)
if img:
self.preloaded_images[app_id] = img
# Preload images in parallel
with ThreadPoolExecutor(max_workers=10) as executor:
executor.map(preload_image, self.installed_games + getattr(self, 'uninstalled_games', []))
def generate_games_found_text(self):
"""Generate a summary of games found on each drive."""
drives_text = ["Installed\nGames Found:"]
for drive in self.drives:
games_count = len([game for game in self.installed_games if game.get('path', '').startswith(drive)])
drives_text.append(f"{drive} {games_count} games")
return "\n".join(drives_text)
def load_api_key(self):
"""Load API key from the file in the same directory as the .exe."""
api_key_path = "apikey.txt"
if os.path.exists(api_key_path):
with open(api_key_path, "r") as file:
return file.read().strip()
return ""
def set_api_key(self):
"""Prompt user for an API key and save it to a file in the current directory."""
bg_color = self.dark_mode_bg if self.is_dark_mode else self.light_mode_bg
fg_color = self.dark_mode_fg if self.is_dark_mode else self.light_mode_fg
api_key_popup = tk.Toplevel(self.root)
api_key_popup.title("Enter API Key")
width = 350
height = 150
hs = api_key_popup.winfo_screenheight()
ws = api_key_popup.winfo_screenwidth()
x = (ws/6) - (width/10)
y = (hs/5) - (height/5)
api_key_popup.geometry('%dx%d+%d+%d' % (width, height, x, y))
self.update_theme(api_key_popup, bg_color, fg_color)
label = tk.Label(api_key_popup, text="Please enter your Steam API Key:", bg=bg_color, fg=fg_color)
label.pack(pady=10)
entry = tk.Entry(api_key_popup, bg=bg_color, fg=fg_color)
entry.pack(pady=5)
def submit():
api_key = entry.get()
if api_key:
with open("apikey.txt", "w") as file:
file.write(api_key)
self.api_key = api_key
messagebox.showinfo("API Key", "API Key saved successfully.")
api_key_popup.destroy()
else:
messagebox.showerror("Error", "API Key not entered.")
submit_button = tk.Button(api_key_popup, text="Submit", command=submit, bg=bg_color, fg=fg_color)
submit_button.pack(pady=10)
def fetch_steam_user_id(self, api_key, steam_id):
"""Fetch Steam User ID automatically using the Steam API."""
url = "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/"
params = {
"key": api_key,
"steamids": steam_id # Placeholder Steam ID for testing; it will be replaced dynamically
}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status() # Check if the response is successful
data = response.json()
if "response" in data and "players" in data["response"]:
player_info = data["response"]["players"][0]
steam_id = player_info.get("steamid")
print(f"Successfully fetched Steam User ID: {steam_id}")
return steam_id
else:
print("Could not fetch Steam User ID.")
return None
except Exception as e:
print(f"Error fetching Steam User ID: {e}")
return None
def load_user_id_key(self):
"""Load Steam User ID from the file if available, else prompt for it."""
user_id_path = "steamuserid.txt"
if os.path.exists(user_id_path):
with open(user_id_path, "r") as file:
return file.read().strip() # Return the Steam User ID if found
else:
return "" # Return an empty string if no Steam User ID is found
def set_user_id_key(self):
"""Prompt the user for a Steam User ID and save it to a file."""
bg_color = self.dark_mode_bg if self.is_dark_mode else self.light_mode_bg
fg_color = self.dark_mode_fg if self.is_dark_mode else self.light_mode_fg
user_id_popup = tk.Toplevel(self.root)
user_id_popup.title("Enter Steam User ID")
width = 350
height = 150
hs = user_id_popup.winfo_screenheight()
ws = user_id_popup.winfo_screenwidth()
x = (ws/6) - (width/10)
y = (hs/5) - (height/5)
user_id_popup.geometry('%dx%d+%d+%d' % (width, height, x, y))
self.update_theme(user_id_popup, bg_color, fg_color)
label = tk.Label(user_id_popup, text="Please enter your Steam User ID:", bg=bg_color, fg=fg_color)
label.pack(pady=10)
entry = tk.Entry(user_id_popup, bg=bg_color, fg=fg_color)
entry.pack(pady=5)
def submit():
steam_user_id = entry.get()
if steam_user_id:
with open("steamuserid.txt", "w") as file:
file.write(steam_user_id)
messagebox.showinfo("Success", "Steam User ID saved successfully.")
user_id_popup.destroy()
else:
messagebox.showerror("Error", "Steam User ID not entered.")
submit_button = tk.Button(user_id_popup, text="Submit", command=submit, bg=bg_color, fg=fg_color)
submit_button.pack(pady=10)
def load_header_images(self, folder_path):
"""Load all image files from the specified folder."""
image_files = []
for filename in os.listdir(folder_path):
# Check if the file is a valid image (add more file extensions if needed)
if filename.endswith(('.png', '.jpg', '.jpeg', '.gif')):
image_files.append(os.path.join(folder_path, filename))
return image_files
def load_uninstalled_games_images(self):
"""Load images for uninstalled games in a background thread."""
# Simulate loading process for uninstalled game images (use your actual preloading logic here)
self.preload_images()
# Once images are loaded, safely update the UI
self.root.after(0, self.update_ui_after_loading_images)
def update_ui_after_loading_images(self):
"""Update UI elements after loading uninstalled game images."""
# Now that images are preloaded, you can enable the button or update the canvas
self.button_spin.config(state=tk.NORMAL, text="Spin the Wheel")
print("Uninstalled games images have been loaded.")
def toggle_uninstalled_games(self):
"""Toggle inclusion of uninstalled games based on checkbox state."""
if self.include_uninstalled_var.get(): # Checkbox is checked
if not self.api_key:
messagebox.showerror("Error", "Please set your Steam API key first.")
self.include_uninstalled_var.set(False) # Uncheck the box
return
# Disable the Spin button while loading images
self.button_spin.config(state=tk.DISABLED, text="Loading...")
self.include_uninstalled_checkbox.config(state=tk.DISABLED)
self.filter_achievements_checkbox.config(state=tk.DISABLED)
self.please_wait_label.config(text=f"Please Wait...")
user_id = self.load_user_id_key()
if not user_id:
user_id = self.fetch_steam_user_id(self.api_key, "Your Placeholder SteamID")
if user_id:
self.save_user_id_key(user_id)
else:
messagebox.showerror("Error", "Could not fetch Steam User ID.")
self.include_uninstalled_var.set(False) # Uncheck the box
return
all_games = get_all_games(self.api_key, user_id)
if not all_games:
messagebox.showerror("Error", "No games were fetched from the Steam API.")
self.include_uninstalled_var.set(False) # Uncheck the box
return
# Map 'appid' to 'app_id' for uninstalled games
uninstalled_games = [{**game, "app_id": str(game["appid"])} for game in all_games if "appid" in game]
installed_ids = {game["app_id"] for game in self.installed_games}
new_uninstalled_games = [game for game in uninstalled_games if game["app_id"] not in installed_ids]
if new_uninstalled_games:
# Add uninstalled games to the list
self.uninstalled_games = new_uninstalled_games
self.installed_games.extend(new_uninstalled_games)
# Apply the 100% achievement filter
if self.filter_achievements_var.get(): # Check if the filter is enabled
self.exclude_achievement_games()
# Load images for uninstalled games asynchronously
threading.Thread(target=self.load_images_in_parallel, daemon=True).start()
messagebox.showinfo("Uninstalled Games Added", f"Included {len(new_uninstalled_games)} uninstalled games.")
else:
messagebox.showinfo("No Uninstalled Games", "No uninstalled games were found to include.")
else: # Checkbox is unchecked
if hasattr(self, 'uninstalled_games'):
uninstalled_ids = {game["app_id"] for game in self.uninstalled_games}
self.installed_games = [game for game in self.installed_games if game["app_id"] not in uninstalled_ids]
del self.uninstalled_games # Clear the uninstalled games list
messagebox.showinfo("Uninstalled Games Removed", "Uninstalled games have been removed from the cycle.")
def toggle_achievement_filter(self):
"""Filter or unfilter 100% achievement games based on the checkbox state."""
# Disable the checkbox temporarily to prevent multiple clicks
self.include_uninstalled_checkbox.config(state=tk.DISABLED)
self.filter_achievements_checkbox.config(state=tk.DISABLED)
self.button_spin.config(state=tk.DISABLED)
self.please_wait_label.config(text=f"Please Wait...")
if self.filter_achievements_var.get():
# Run the filtering logic in a background thread
threading.Thread(target=self.exclude_achievement_games_in_background, daemon=True).start()
else:
# Run the reinclusion logic in a background thread
threading.Thread(target=self.include_achievement_games_in_background, daemon=True).start()
# Update the UI to reflect exclusions
self.excluded_label.config(text=f"Excluded Games:\n{len(self.excluded_games)}")
self.save_exclusions()
def exclude_achievement_games(self):
"""Add games with 100% achievements to the excluded list."""
for game_list in [self.installed_games, getattr(self, 'uninstalled_games', [])]:
for game in game_list:
app_id = game["app_id"]
if not self.supports_achievements(app_id):
print(f"Game {game['name']} (app_id: {app_id}) does not support achievements.")
continue
achievement_progress = self.get_achievement_progress(app_id)
if achievement_progress["unlocked"] == achievement_progress["total"] > 0:
if app_id not in self.excluded_games:
self.excluded_games.append(app_id)
def exclude_achievement_games_in_background(self):
"""Exclude 100% achievement games in the background."""
self.exclude_achievement_games() # Call the existing method to filter achievements
# Re-enable the checkbox after the operation is completed
self.root.after(0, self.enable_checkbox)
def include_achievement_games_in_background(self):
"""Include all achievement games in the background."""
self.include_achievement_games() # Call the existing method to include all games
# Re-enable the checkbox after the operation is completed
self.root.after(0, self.enable_checkbox)
def include_uninstalled_games_in_background(self):
"""Include all achievement games in the background."""
self.toggle_uninstalled_games() # Call the existing method to include all games
# Re-enable the checkbox after the operation is completed
self.root.after(0, self.enable_checkbox)
def enable_checkbox(self):
"""Re-enable the checkbox after background operation."""
self.include_uninstalled_checkbox.config(state=tk.NORMAL)
self.filter_achievements_checkbox.config(state=tk.NORMAL)
self.button_spin.config(state=tk.NORMAL)
self.please_wait_label.config(text=f"")
def supports_achievements(self, app_id):
"""Check if the game supports achievements using the Steam API."""
url = f"https://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v2/"
params = {
"key": self.api_key,
"appid": app_id
}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
# If the game has achievements in its schema, return True
return "game" in data and "availableGameStats" in data["game"] and "achievements" in data["game"]["availableGameStats"]
except Exception as e:
print(f"Error checking schema for app_id {app_id}: {e}")
return False
def include_achievement_games(self):
"""Remove games with 100% achievements from the excluded list."""
to_include = []
for app_id in self.excluded_games:
if self.get_achievement_progress(app_id) == 100:
to_include.append(app_id)
# Remove the 100% achievement games from the excluded list
for app_id in to_include:
self.excluded_games.remove(app_id)
def get_achievement_progress(self, app_id):
"""Fetch the achievement progress for a game."""
# Skip games without achievements
if not self.supports_achievements(app_id):
print(f"Game {app_id} does not support achievements.")
return {"total": 0, "unlocked": 0}
url = f"https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v1/"
params = {
"key": self.api_key,
"steamid": self.load_user_id_key(),
"appid": app_id
}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
if "playerstats" in data and "achievements" in data["playerstats"]:
total = len(data["playerstats"]["achievements"])
unlocked = sum(ach["achieved"] for ach in data["playerstats"]["achievements"])
return {"total": total, "unlocked": unlocked}
else:
print(f"No achievements data available for app_id {app_id}.")
return {"total": 0, "unlocked": 0}
except requests.exceptions.HTTPError as http_err:
if "400" in str(http_err):
print(f"Skipping app_id {app_id}: Achievements data not available (400 Bad Request).")
else:
print(f"HTTP error for app_id {app_id}: {http_err}")
except Exception as e:
print(f"Error fetching achievements for app_id {app_id}: {e}")
# Return default progress if the request fails
return {"total": 0, "unlocked": 0}
def load_images_in_parallel(self, batch_size=10):
"""Preload images for uninstalled games in batches."""
games_to_load = self.uninstalled_games
for i in range(0, len(games_to_load), batch_size):
batch = games_to_load[i:i + batch_size]
with ThreadPoolExecutor(max_workers=5) as executor:
executor.map(lambda game: fetch_header_image(game["app_id"], self.cache_dir), batch)
self.root.after(0, self.on_images_preloaded)
def on_images_preloaded(self):
"""Called when all images are preloaded."""
self.is_images_preloaded = True
# Re-enable the Spin button after images are loaded
self.button_spin.config(state=tk.NORMAL, text="Spin the Wheel")
self.include_uninstalled_checkbox.config(state=tk.NORMAL)
self.filter_achievements_checkbox.config(state=tk.NORMAL)
self.please_wait_label.config(text=f"")
print("Images for uninstalled games have been loaded and cached.")
def load_image_for_game(self, game, cache_dir):
"""Load and cache the image for a specific game."""
app_id = game["app_id"]
cache_file_path = os.path.join(cache_dir, f"{app_id}.jpg")
# Check if the image already exists in the cache
if os.path.exists(cache_file_path):
print(f"Using cached image for app_id {app_id}")
return # Skip if the image is already cached
# Fetch the image and save it to the cache
print(f"Fetching image for app_id {app_id}...")
img = fetch_header_image(app_id) # Replace with actual image fetching logic
if img:
# Save the image to the cache
img.save(cache_file_path, "JPEG")
print(f"Image cached for app_id {app_id}")
else:
print(f"Failed to fetch image for app_id {app_id}")
def start_animation(self):
"""Start the spinning animation after loading images."""
# Ensure that images are properly preloaded
if not self.preloaded_images:
print("Error: No images were preloaded.")
return
# Now start the animation
self.cycle_images(self.installed_games + getattr(self, 'uninstalled_games', []))
def display_random_header_image(self):
"""Display a random header image on the canvas initially."""
random_game = random.choice(self.installed_games)
random_app_id = random_game["app_id"] # Get the app_id of the selected game
print(f"Fetching image for app_id {random_app_id}")
random_image = fetch_header_image(random_app_id, self.cache_dir)
if random_image:
print(f"Image fetched successfully for app_id {random_app_id}")
# Resize the image to match the canvas size
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
print(f"Canvas width: {canvas_width}, Canvas height: {canvas_height}")
random_image_resized = random_image.resize((canvas_width, canvas_height), Image.Resampling.LANCZOS)
random_image_tk = ImageTk.PhotoImage(random_image_resized)
# Make sure to keep a reference to the image
self.canvas.create_image(canvas_width // 2, canvas_height // 2, image=random_image_tk, anchor=tk.CENTER)
# Store the image reference to prevent it from being garbage collected
self.active_images = [(random_image_tk, random_image)]
print("Random header image displayed on canvas.")
# Force Tkinter to process the events and refresh the canvas
self.canvas.update_idletasks()
self.root.update()
def display_image_from_url(self, image_url):
"""Download and display the image from a URL on the canvas."""
try:
img_data = requests.get(image_url).content
img = Image.open(io.BytesIO(img_data))
img_resized = img.resize((600, 300), Image.Resampling.LANCZOS) # Resize image to fit the canvas
img_tk = ImageTk.PhotoImage(img_resized)
# Display the image on the canvas
self.canvas.create_image(0, 0, anchor='nw', image=img_tk)
# Keep a reference to the image to avoid garbage collection
self.canvas.image = img_tk # Keep a reference so the image stays in memory
except Exception as e:
print(f"Error loading image from URL {image_url}: {e}")
def set_light_mode(self):
"""Set the window to light mode."""
self.update_theme(self.root, self.light_mode_bg, self.light_mode_fg)
def set_dark_mode(self):
"""Set the window to dark mode."""
self.update_theme(self.root, self.dark_mode_bg, self.dark_mode_fg)
def update_theme(self, widget, bg_color, fg_color):
"""Recursively update the background and foreground color for all widgets."""
# Update background color for the widget
widget.config(bg=bg_color)
# Update foreground and selectcolor where applicable