-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpg_game.py
1663 lines (1365 loc) · 70 KB
/
rpg_game.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
import sys
import json
import os
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QLabel, QGridLayout,
QMessageBox, QTabWidget, QScrollArea, QStackedWidget,
QGraphicsOpacityEffect, QStackedLayout)
from PyQt6.QtCore import Qt, QTimer, QPropertyAnimation, QEasingCurve, QDateTime, QThread, pyqtSignal, QObject, QUrl, QRect
from PyQt6.QtGui import QFont, QColor, QPainter, QPixmap
import threading
import queue
import winsound # Windows-only sound module
import random
# Use a flag to prevent too many sounds playing at once
MAX_CONCURRENT_SOUNDS = 4
active_sounds = 0
def play_sound_thread(sound_file):
"""Play sound in a separate thread to allow multiple sounds"""
global active_sounds
active_sounds += 1
if active_sounds <= MAX_CONCURRENT_SOUNDS:
try:
# Use SND_ASYNC flag to allow sound to play in background
# Don't use SND_NOSTOP flag to allow multiple instances
winsound.PlaySound(sound_file, winsound.SND_FILENAME | winsound.SND_ASYNC)
except Exception as e:
print(f"Error playing sound: {e}")
active_sounds -= 1
def play_sound(sound_file):
"""Windows sound playing function that doesn't cut off previous sounds"""
# Start a new thread for each sound to allow overlapping
sound_thread = threading.Thread(target=play_sound_thread, args=(sound_file,))
sound_thread.daemon = True # Make thread terminate when main program exits
sound_thread.start()
class Upgrade:
def __init__(self, name, base_cost, base_production, icon, description, required_upgrade=None):
self.name = name
self.count = 0
self.base_cost = base_cost
self.cost = base_cost
self.base_production = base_production
self.production = base_production
self.icon = icon
self.description = description
self.achievement_name = f"First {name}"
self.achievement_description = f"Recruit your first {name.lower()}"
self.required_upgrade = required_upgrade # Name of the required upgrade
# Add stats tracking
self.total_bought = 0
self.total_spent = 0
class SaveWorker(QThread):
finished = pyqtSignal()
error = pyqtSignal(str)
def __init__(self, save_data):
super().__init__()
self.save_data = save_data
def run(self):
try:
with open("rpg_save_game.json", "w") as f:
json.dump(self.save_data, f)
self.finished.emit()
except Exception as e:
self.error.emit(str(e))
class LoadWorker(QThread):
finished = pyqtSignal(dict)
error = pyqtSignal(str)
def __init__(self):
super().__init__()
def run(self):
try:
with open("rpg_save_game.json", "r") as f:
save_data = json.load(f)
self.finished.emit(save_data)
except Exception as e:
error_msg = str(e)
print(f"Failed to load game: {error_msg}")
self.error.emit(error_msg)
class RotationHelper(QObject):
rotationChanged = pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent)
self._rotation = 0
def getRotation(self):
return self._rotation
def setRotation(self, value):
if self._rotation != value:
self._rotation = value
self.rotationChanged.emit(value)
rotation = property(getRotation, setRotation)
class MainMenu(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setup_ui()
def setup_ui(self):
layout = QVBoxLayout(self)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
# Title
title = QLabel("Monster Slayer RPG")
title.setFont(QFont("Arial", 48, QFont.Weight.Bold))
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(title)
# Spacing
layout.addSpacing(50)
# Buttons
self.new_game_btn = QPushButton("Start New Adventure")
self.new_game_btn.setFont(QFont("Arial", 16))
self.new_game_btn.setMinimumSize(200, 50)
layout.addWidget(self.new_game_btn, alignment=Qt.AlignmentFlag.AlignCenter)
self.load_game_btn = QPushButton("Continue Adventure")
self.load_game_btn.setFont(QFont("Arial", 16))
self.load_game_btn.setMinimumSize(200, 50)
self.load_game_btn.setVisible(os.path.exists("rpg_save_game.json"))
layout.addWidget(self.load_game_btn, alignment=Qt.AlignmentFlag.AlignCenter)
self.settings_btn = QPushButton("Settings")
self.settings_btn.setFont(QFont("Arial", 16))
self.settings_btn.setMinimumSize(200, 50)
layout.addWidget(self.settings_btn, alignment=Qt.AlignmentFlag.AlignCenter)
self.exit_btn = QPushButton("Exit Game")
self.exit_btn.setFont(QFont("Arial", 16))
self.exit_btn.setMinimumSize(200, 50)
layout.addWidget(self.exit_btn, alignment=Qt.AlignmentFlag.AlignCenter)
# Add spacing between buttons
layout.setSpacing(20)
class EnemyButton(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFixedSize(130, 150) # Increased height for HP bar
# Find all enemy images
self.enemy_images = {}
self.enemy_directory = "images/enemies"
self.load_enemy_images()
# Enemy state
self.current_enemy = None
self.enemy_name = ""
self.enemy_hp = 100
self.max_hp = 100
self.is_new_enemy = True # Flag to track if enemy is new and not yet defeated
# Select initial enemy
self.select_random_enemy()
# Click animation properties
self.is_clicked = False
self.click_scale = 0.9 # Scale down to 90% when clicked
def load_enemy_images(self):
"""Load all enemy images from the enemies directory"""
import glob
import os
# Use forward slashes for consistency
path_pattern = self.enemy_directory.replace("\\", "/") + "/*.png"
image_files = glob.glob(path_pattern)
for image_file in image_files:
name = os.path.basename(image_file).split(".")[0] # Get filename without extension
self.enemy_images[name] = QPixmap(image_file)
if not self.enemy_images:
print(f"Warning: No enemy images found in {self.enemy_directory}")
# Create a fallback red square as a placeholder
placeholder = QPixmap(512, 512)
placeholder.fill(QColor(255, 0, 0))
self.enemy_images["placeholder"] = placeholder
def select_random_enemy(self):
"""Select a random enemy from the available images"""
if not self.enemy_images:
return
import random
self.enemy_name = random.choice(list(self.enemy_images.keys()))
self.current_enemy = self.enemy_images[self.enemy_name]
self.enemy_hp = self.max_hp
self.is_new_enemy = True # Mark this as a new enemy that hasn't been defeated
self.update()
def damage_enemy(self, damage):
"""Apply damage to the current enemy"""
self.enemy_hp -= damage
if self.enemy_hp <= 0:
# Get the defeated enemy's name and ID before selecting a new one
defeated_enemy_name = self.enemy_name
defeated_enemy_id = self.enemy_name
defeated_enemy_formatted_name = self.get_enemy_name()
# Enemy defeated, select a new one
self.select_random_enemy()
# Return both the defeated status and the defeated enemy info
return True, defeated_enemy_id, defeated_enemy_formatted_name
self.update()
# Return False for not defeated and None for enemy info
return False, None, None
def paintEvent(self, event):
painter = QPainter(self)
# Draw enemy image
if self.current_enemy:
# Calculate target rect for the image (120x120 at the top)
target_rect = QRect(5, 5, 100, 100)
# If clicked, scale down the drawing
if self.is_clicked:
# Calculate scaled rect
scale_factor = self.click_scale
width_diff = target_rect.width() * (1 - scale_factor)
height_diff = target_rect.height() * (1 - scale_factor)
scaled_rect = QRect(
int(target_rect.x() + width_diff / 2),
int(target_rect.y() + height_diff / 2),
int(target_rect.width() * scale_factor),
int(target_rect.height() * scale_factor)
)
painter.drawPixmap(scaled_rect, self.current_enemy)
else:
painter.drawPixmap(target_rect, self.current_enemy)
# Draw HP bar background
bar_rect = QRect(5, 130, 120, 15)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(60, 60, 60))
painter.drawRect(bar_rect)
# Draw HP bar fill based on current HP
if self.max_hp > 0:
hp_width = int((self.enemy_hp / self.max_hp) * bar_rect.width())
hp_rect = QRect(bar_rect.x(), bar_rect.y(), hp_width, bar_rect.height())
# Color changes based on HP percentage
hp_percent = self.enemy_hp / self.max_hp
if hp_percent > 0.6:
# Green for high health
hp_color = QColor(0, 200, 0)
elif hp_percent > 0.3:
# Yellow for medium health
hp_color = QColor(200, 200, 0)
else:
# Red for low health
hp_color = QColor(200, 0, 0)
painter.setBrush(hp_color)
painter.drawRect(hp_rect)
# Draw border around HP bar
painter.setPen(QColor(200, 200, 200))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(bar_rect)
painter.end()
def show_click_animation(self):
# Set clicked state
self.is_clicked = True
self.update()
# Reset after short delay
QTimer.singleShot(100, self.reset_click_animation)
def reset_click_animation(self):
self.is_clicked = False
self.update()
def get_enemy_name(self):
"""Return formatted enemy name for display"""
# Convert string like "some-enemy-name" to "Some Enemy Name"
if not self.enemy_name:
return "Unknown Enemy"
return " ".join(word.capitalize() for word in self.enemy_name.split("-"))
class XPIconLabel(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
# Set fixed size for the XP icon
self.setFixedSize(24, 24)
# Load sprite sheet - use the coin spritesheet for now
# In a real game, you'd replace this with an XP icon
self.spritesheet = QPixmap("images/coin_spritesheet.png")
# Frame data - each frame is 22x22 pixels
self.frame_width = 22
self.frame_height = 22
def paintEvent(self, event):
painter = QPainter(self)
# Calculate source rect based on first frame only
source_rect = QRect(0, 0, self.frame_width, self.frame_height)
# Draw the first frame scaled to label size
target_rect = QRect(0, 0, self.width(), self.height())
painter.drawPixmap(target_rect, self.spritesheet, source_rect)
painter.end()
class NotificationOverlay(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# Set up overlay properties
self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
# Set up layout
self.layout = QVBoxLayout(self)
self.layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
# Create container for notification with semi-transparent background
self.notification_container = QWidget()
self.notification_container.setObjectName("notificationContainer")
self.notification_container.setStyleSheet("""
#notificationContainer {
background-color: rgba(20, 20, 40, 0.9);
border-radius: 10px;
border: 2px solid purple;
}
QPushButton#closeButton {
background-color: rgba(120, 0, 120, 0.7);
color: white;
font-weight: bold;
border-radius: 10px;
border: 1px solid white;
padding: 5px;
}
QPushButton#closeButton:hover {
background-color: rgba(170, 0, 170, 0.9);
}
QPushButton#okButton {
background-color: rgba(60, 0, 120, 0.7);
color: white;
font-weight: bold;
border-radius: 10px;
border: 1px solid white;
padding: 5px;
min-height: 30px;
font-size: 14px;
}
QPushButton#okButton:hover {
background-color: rgba(90, 0, 180, 0.9);
}
""")
self.notification_layout = QVBoxLayout(self.notification_container)
self.notification_layout.setContentsMargins(20, 20, 20, 20)
# Add close button to top-right corner
close_button_container = QWidget()
close_layout = QHBoxLayout(close_button_container)
close_layout.setContentsMargins(0, 0, 0, 0)
# Title in a container with close button
title_container = QWidget()
title_layout = QHBoxLayout(title_container)
title_layout.setContentsMargins(0, 0, 0, 0)
# Title label
self.title_label = QLabel()
self.title_label.setFont(QFont("Arial", 18, QFont.Weight.Bold))
self.title_label.setStyleSheet("color: white;")
self.title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
title_layout.addWidget(self.title_label)
# Close button
self.close_button = QPushButton("X")
self.close_button.setObjectName("closeButton")
self.close_button.setFixedSize(24, 24)
self.close_button.clicked.connect(self.close_notification)
title_layout.addWidget(self.close_button, alignment=Qt.AlignmentFlag.AlignRight)
# Add the title container to the main layout
self.notification_layout.addWidget(title_container)
# Icon label
self.icon_label = QLabel()
self.icon_label.setFont(QFont("Arial", 48))
self.icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.notification_layout.addWidget(self.icon_label)
# Message label
self.message_label = QLabel()
self.message_label.setFont(QFont("Arial", 14))
self.message_label.setStyleSheet("color: white;")
self.message_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.notification_layout.addWidget(self.message_label)
# Add OK button at the bottom
self.ok_button = QPushButton("OK")
self.ok_button.setObjectName("okButton")
self.ok_button.setFixedWidth(100)
self.ok_button.clicked.connect(self.close_notification)
ok_button_container = QWidget()
ok_button_layout = QHBoxLayout(ok_button_container)
ok_button_layout.addWidget(self.ok_button, alignment=Qt.AlignmentFlag.AlignCenter)
ok_button_layout.setContentsMargins(0, 10, 0, 0) # Add some top margin
self.notification_layout.addWidget(ok_button_container)
# Add the container to the main layout
self.layout.addWidget(self.notification_container)
# Set fixed size for notification
self.notification_container.setFixedSize(400, 300) # Increased height to accommodate OK button
# Initially hide the overlay
self.hide()
# Auto-hide timer
self.hide_timer = QTimer(self)
self.hide_timer.timeout.connect(self.hide_animation)
# Animation for fading in/out
self.opacity_effect = QGraphicsOpacityEffect(self)
self.notification_container.setGraphicsEffect(self.opacity_effect)
self.opacity_effect.setOpacity(0)
self.fade_animation = QPropertyAnimation(self.opacity_effect, b"opacity")
self.fade_animation.setDuration(500) # 500ms for fade
self.fade_animation.finished.connect(self.on_animation_finished)
def show_notification(self, title, icon, message, duration=3000):
"""Show a notification with title, icon, and message for the specified duration"""
self.title_label.setText(title)
self.icon_label.setText(icon)
self.message_label.setText(message)
# Position overlay centered in parent
if self.parent():
parent_rect = self.parent().rect()
self.setGeometry(parent_rect)
# Show overlay
self.show()
# Start fade-in animation
self.fade_animation.setStartValue(0.0)
self.fade_animation.setEndValue(1.0)
self.fade_animation.start()
# Set auto-hide timer
self.hide_timer.start(duration)
def close_notification(self):
"""Immediately close the notification when the close button is clicked"""
self.hide_timer.stop()
self.hide_animation()
def hide_animation(self):
"""Start fade-out animation"""
self.hide_timer.stop()
self.fade_animation.setStartValue(1.0)
self.fade_animation.setEndValue(0.0)
self.fade_animation.start()
def on_animation_finished(self):
"""Handle animation completion"""
if self.opacity_effect.opacity() == 0:
self.hide()
class RPGGame(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Monster Slayer RPG")
self.setFixedSize(800, 700) # Set fixed size to 800x700
# Create status bar
self.statusBar().showMessage("Ready")
# Set up audio players
self.setup_audio()
# Initialize game state
self.xp = 0
self.xp_per_click = 1
self.total_xp = 0
self.total_clicks = 0
self.player_level = 1
self.xp_to_next_level = 100 # Base XP needed for level 2
self.enemies_defeated = 0
self.enemy_stats = {} # Dictionary to track statistics for each unique enemy
self.start_time = QDateTime.currentDateTime()
self.last_save_time = self.start_time
# Define upgrades with dependencies - now themed for RPG
self.upgrades = [
Upgrade("Squire", 10, 0.1, "🧑", "A novice fighter who helps you attack monsters"), # First upgrade, no dependency
Upgrade("Knight", 50, 0.5, "🛡️", "A trained warrior with better fighting skills", "Squire"), # Requires Squire
Upgrade("Archer", 200, 2.0, "🏹", "Attacks monsters from a distance", "Knight"), # Requires Knight
Upgrade("Mage", 1000, 10.0, "🧙", "Uses magic to damage multiple monsters at once", "Archer"), # Requires Archer
Upgrade("Healer", 5000, 50.0, "💊", "Keeps your party healthy for longer fights", "Mage"), # Requires Mage
Upgrade("Paladin", 10000, 200.0, "✝️", "Holy warrior with powerful light attacks", "Healer"),
Upgrade("Assassin", 50000, 500.0, "🗡️", "Deals critical damage to monsters", "Paladin"),
Upgrade("Warlock", 100000, 1000.0, "🔮", "Summons demons to fight for you", "Assassin"),
Upgrade("Ranger", 500000, 5000.0, "🐺", "Hunts with animal companions", "Warlock"),
Upgrade("Necromancer", 1000000, 10000.0, "💀", "Raises undead army to fight monsters", "Ranger"),
Upgrade("Dragon Rider", 5000000, 50000.0, "🐉", "Commands a dragon to burn enemies", "Necromancer"),
Upgrade("Time Mage", 10000000, 100000.0, "⏳", "Manipulates time to multiply attacks", "Dragon Rider"),
Upgrade("Deity", 50000000, 500000.0, "👑", "A god who fights alongside you", "Time Mage"),
Upgrade("Hero King", 100000000, 1000000.0, "⚔️", "Legendary hero with ultimate power", "Deity"),
Upgrade("World Savior", 500000000, 5000000.0, "🌍", "The chosen one who can defeat any monster", "Hero King")
]
# Achievements
self.achievements = {
"First Kill": {"name": "First Kill", "description": "Defeat your first monster", "unlocked": False},
"Monster Hunter": {"name": "Monster Hunter", "description": "Reach Level 5", "unlocked": False},
"Legendary Slayer": {"name": "Legendary Slayer", "description": "Reach Level 20", "unlocked": False}
}
# Add achievements for each upgrade
for upgrade in self.upgrades:
self.achievements[upgrade.achievement_name] = {
"name": upgrade.achievement_name,
"description": upgrade.achievement_description,
"unlocked": False
}
# Create central widget with stacked layout
self.central_widget = QStackedWidget()
self.setCentralWidget(self.central_widget)
# Create and add main menu
self.main_menu = MainMenu()
self.central_widget.addWidget(self.main_menu)
# Create and add game widget
self.game_widget = QWidget()
self.setup_game_ui()
self.central_widget.addWidget(self.game_widget)
# Create notification overlay
self.notification_overlay = NotificationOverlay(self)
# Connect menu buttons
self.main_menu.new_game_btn.clicked.connect(self.start_new_game)
self.main_menu.load_game_btn.clicked.connect(self.load_game)
self.main_menu.settings_btn.clicked.connect(self.show_settings)
self.main_menu.exit_btn.clicked.connect(self.close)
# Center the window
self.center_window()
def center_window(self):
screen = QApplication.primaryScreen().geometry()
size = self.geometry()
x = (screen.width() - size.width()) // 2
y = (screen.height() - size.height()) // 2
self.move(x, y)
def start_new_game(self):
# Reset game state
self.xp = 0
self.xp_per_click = 1
self.total_xp = 0
self.total_clicks = 0
self.player_level = 1
self.xp_to_next_level = 100 # Base XP needed for level 2
self.enemies_defeated = 0
self.enemy_stats = {} # Clear enemy statistics
self.start_time = QDateTime.currentDateTime()
self.last_save_time = self.start_time
# Reset upgrades
for upgrade in self.upgrades:
upgrade.count = 0
upgrade.cost = upgrade.base_cost
upgrade.production = upgrade.base_production
upgrade.total_bought = 0
upgrade.total_spent = 0
# Reset achievements
for achievement in self.achievements.values():
achievement["unlocked"] = False
# Reset enemy
self.enemy_button.select_random_enemy()
self.enemy_name_label.setText(f"Enemy: {self.enemy_button.get_enemy_name()}")
self.enemies_defeated_label.setText(f"Enemies Defeated: {self.enemies_defeated}")
# Clear enemy statistics display
self.clear_enemy_stats_display()
# Switch to game view
self.central_widget.setCurrentWidget(self.game_widget)
# Update visible upgrades to reset the shop view
self.update_visible_upgrades()
self.update_display()
self.update_stats()
self.show_status_message("New adventure started")
def show_settings(self):
QMessageBox.information(self, "Settings", "Settings feature coming soon!")
def setup_game_ui(self):
# Create game layout
game_layout = QVBoxLayout(self.game_widget)
# Create tab widget
self.tab_widget = QTabWidget()
game_layout.addWidget(self.tab_widget)
# Create game tab
game_tab = QWidget()
game_tab_layout = QVBoxLayout(game_tab)
# Create XP and level display
self.level_label = QLabel(f"Level: {self.player_level}")
self.level_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.level_label.setFont(QFont("Arial", 24, QFont.Weight.Bold))
game_tab_layout.addWidget(self.level_label)
self.xp_label = QLabel(f"XP: {self.xp}/{self.xp_to_next_level}")
self.xp_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.xp_label.setFont(QFont("Arial", 18))
game_tab_layout.addWidget(self.xp_label)
# Create party members discovered display
self.party_label = QLabel("1 of 15 party members recruited")
self.party_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.party_label.setFont(QFont("Arial", 14))
game_tab_layout.addWidget(self.party_label)
# Create enemy name label
self.enemy_name_label = QLabel("Enemy: Unknown")
self.enemy_name_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.enemy_name_label.setFont(QFont("Arial", 16, QFont.Weight.Bold))
game_tab_layout.addWidget(self.enemy_name_label)
# Create animated enemy button (replacing monster button)
self.enemy_button = EnemyButton()
# Create click area for the enemy (using transparent button overlay)
self.enemy_container = QWidget()
self.enemy_container.setFixedSize(130, 150)
enemy_container_layout = QVBoxLayout(self.enemy_container)
enemy_container_layout.setContentsMargins(0, 0, 0, 0)
# Add the enemy button to the container
self.enemy_button.setParent(self.enemy_container)
# Create a clickable overlay
self.enemy_click_area = QPushButton(self.enemy_container)
self.enemy_click_area.setFixedSize(130, 150)
self.enemy_click_area.setStyleSheet("background-color: transparent; border: none;")
self.enemy_click_area.setCursor(Qt.CursorShape.PointingHandCursor)
self.enemy_click_area.clicked.connect(self.click_enemy)
# Make sure the overlay is on top
self.enemy_click_area.raise_()
# Center the enemy container
enemy_layout = QHBoxLayout()
enemy_layout.addStretch()
enemy_layout.addWidget(self.enemy_container)
enemy_layout.addStretch()
game_tab_layout.addLayout(enemy_layout)
# Add enemy defeated counter
self.enemies_defeated_label = QLabel("Enemies Defeated: 0")
self.enemies_defeated_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.enemies_defeated_label.setFont(QFont("Arial", 14))
game_tab_layout.addWidget(self.enemies_defeated_label)
# Create shop section with scrollable area
shop_scroll = QScrollArea()
shop_scroll.setWidgetResizable(True)
shop_content = QWidget()
shop_layout = QGridLayout(shop_content)
shop_layout.setContentsMargins(5, 5, 5, 5)
# Create shop items for each upgrade, but add them to layout later dynamically
self.upgrade_widgets = {}
for i, upgrade in enumerate(self.upgrades):
# Create labels and button for each upgrade
count_label = QLabel(f"{upgrade.icon} {upgrade.name}s: {upgrade.count}")
count_label.setFont(QFont("Arial", 16))
cost_label = QLabel(f"Cost: {upgrade.cost} XP")
cost_label.setFont(QFont("Arial", 16))
buy_button = QPushButton(f"Recruit {upgrade.name}")
buy_button.clicked.connect(lambda checked, u=upgrade: self.buy_upgrade(u))
# Store widgets for updating
self.upgrade_widgets[upgrade.name] = {
"count_label": count_label,
"cost_label": cost_label,
"buy_button": buy_button,
"row": i, # Store row index for later placement
"visible": False # Track if currently visible in shop
}
# Add the shop content to the scroll area
shop_scroll.setWidget(shop_content)
shop_scroll.setMinimumHeight(250) # Set a reasonable height for the shop
game_tab_layout.addWidget(shop_scroll)
# Store references for later use
self.shop_layout = shop_layout
self.shop_content = shop_content
# Initialize visible upgrades
self.update_visible_upgrades()
# Create bottom button layout
bottom_buttons_layout = QHBoxLayout()
# Create save game button
save_button = QPushButton("Save Adventure")
save_button.setFont(QFont("Arial", 14))
save_button.clicked.connect(lambda: self.save_game(silent=False))
bottom_buttons_layout.addWidget(save_button)
# Create return to menu button with new name
menu_button = QPushButton("Return to Main Menu")
menu_button.setFont(QFont("Arial", 14))
menu_button.clicked.connect(self.return_to_menu)
bottom_buttons_layout.addWidget(menu_button)
game_tab_layout.addLayout(bottom_buttons_layout)
# Create achievements tab
achievements_tab = QWidget()
achievements_layout = QVBoxLayout(achievements_tab)
# Create scroll area for achievements
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll_content = QWidget()
scroll_layout = QVBoxLayout(scroll_content)
scroll_layout.setSpacing(5) # Reduce spacing between achievements
scroll_layout.setContentsMargins(5, 5, 5, 5) # Reduce margins
# Create achievement labels
self.achievement_labels = {}
for achievement_name, achievement in self.achievements.items():
achievement_widget = QWidget()
achievement_widget.setMaximumHeight(100) # Set maximum height
achievement_layout = QHBoxLayout(achievement_widget)
achievement_layout.setContentsMargins(5, 5, 5, 5) # Reduce internal margins
achievement_layout.setSpacing(10) # Set spacing between icon and text
# Create status icon
status_label = QLabel("🏆")
status_label.setFont(QFont("Arial", 16))
status_label.setFixedWidth(30) # Fixed width for icon
achievement_layout.addWidget(status_label)
# Create achievement info
info_widget = QWidget()
info_layout = QVBoxLayout(info_widget)
info_layout.setContentsMargins(0, 0, 0, 0) # Remove internal margins
info_layout.setSpacing(2) # Minimal spacing between name and description
name_label = QLabel(achievement["name"])
name_label.setFont(QFont("Arial", 16, QFont.Weight.Bold))
info_layout.addWidget(name_label)
desc_label = QLabel(achievement["description"])
desc_label.setFont(QFont("Arial", 12))
info_layout.addWidget(desc_label)
achievement_layout.addWidget(info_widget)
# Only add to layout if unlocked
if achievement["unlocked"]:
scroll_layout.addWidget(achievement_widget)
# Store label for updating
self.achievement_labels[achievement_name] = {
"widget": achievement_widget,
"status_label": status_label
}
# Add spacer at the end to push content up
scroll_layout.addStretch(1)
scroll.setWidget(scroll_content)
achievements_layout.addWidget(scroll)
# Create stats tab
stats_tab = QWidget()
stats_layout = QVBoxLayout(stats_tab)
# Create stats display
self.stats_labels = {}
# Time played
time_widget = QWidget()
time_layout = QHBoxLayout(time_widget)
time_label = QLabel("⏱️ Time Played:")
time_label.setFont(QFont("Arial", 16))
self.stats_labels["time"] = QLabel("0:00:00")
self.stats_labels["time"].setFont(QFont("Arial", 16))
time_layout.addWidget(time_label)
time_layout.addWidget(self.stats_labels["time"])
stats_layout.addWidget(time_widget)
# Player level
level_widget = QWidget()
level_layout = QHBoxLayout(level_widget)
level_label = QLabel("👑 Player Level:")
level_label.setFont(QFont("Arial", 16))
self.stats_labels["level"] = QLabel(f"{self.player_level}")
self.stats_labels["level"].setFont(QFont("Arial", 16))
level_layout.addWidget(level_label)
level_layout.addWidget(self.stats_labels["level"])
stats_layout.addWidget(level_widget)
# Total clicks (monster kills)
clicks_widget = QWidget()
clicks_layout = QHBoxLayout(clicks_widget)
clicks_label = QLabel("⚔️ Monsters Slain:")
clicks_label.setFont(QFont("Arial", 16))
self.stats_labels["clicks"] = QLabel("0")
self.stats_labels["clicks"].setFont(QFont("Arial", 16))
clicks_layout.addWidget(clicks_label)
clicks_layout.addWidget(self.stats_labels["clicks"])
stats_layout.addWidget(clicks_widget)
# Enemies defeated counter
enemies_defeated_widget = QWidget()
enemies_defeated_layout = QHBoxLayout(enemies_defeated_widget)
enemies_defeated_label = QLabel("🏆 Enemies Defeated:")
enemies_defeated_label.setFont(QFont("Arial", 16))
self.stats_labels["enemies_defeated"] = QLabel("0")
self.stats_labels["enemies_defeated"].setFont(QFont("Arial", 16))
enemies_defeated_layout.addWidget(enemies_defeated_label)
enemies_defeated_layout.addWidget(self.stats_labels["enemies_defeated"])
stats_layout.addWidget(enemies_defeated_widget)
# Total XP
xp_widget = QWidget()
xp_layout = QHBoxLayout(xp_widget)
# Create custom XP icon
xp_icon = XPIconLabel()
xp_layout.addWidget(xp_icon)
xp_label = QLabel("Total XP Earned:")
xp_label.setFont(QFont("Arial", 16))
self.stats_labels["total_xp"] = QLabel("0")
self.stats_labels["total_xp"].setFont(QFont("Arial", 16))
xp_layout.addWidget(xp_label)
xp_layout.addWidget(self.stats_labels["total_xp"])
stats_layout.addWidget(xp_widget)
# XP per second
xps_widget = QWidget()
xps_layout = QHBoxLayout(xps_widget)
xps_label = QLabel("⚡ XP per Second:")
xps_label.setFont(QFont("Arial", 16))
self.stats_labels["xps"] = QLabel("0")
self.stats_labels["xps"].setFont(QFont("Arial", 16))
xps_layout.addWidget(xps_label)
xps_layout.addWidget(self.stats_labels["xps"])
stats_layout.addWidget(xps_widget)
# Add party member stats section
party_stats_label = QLabel("Party Statistics")
party_stats_label.setFont(QFont("Arial", 20, QFont.Weight.Bold))
stats_layout.addWidget(party_stats_label)
# Create a scroll area for party stats to ensure they're all visible
party_scroll = QScrollArea()
party_scroll.setWidgetResizable(True)
party_content = QWidget()
party_content_layout = QVBoxLayout(party_content)
party_content_layout.setSpacing(10) # Add spacing between party members
# Create container widgets for party stats but don't add them to layout yet
self.upgrade_stat_widgets = {}
for upgrade in self.upgrades:
upgrade_widget = QWidget()
upgrade_widget.setMinimumHeight(90) # Set minimum height for each party stat
upgrade_layout = QVBoxLayout(upgrade_widget) # Changed to QVBoxLayout for better text display
upgrade_layout.setContentsMargins(5, 5, 5, 5) # Add some padding
# Create party stats
stats_text = f"{upgrade.icon} {upgrade.name}:"
stats_text += f"\nTotal Recruited: {upgrade.total_bought}"
stats_text += f"\nTotal XP Spent: {upgrade.total_spent:,}"
stats_text += f"\nCurrent XP/s: {upgrade.count * upgrade.production:.1f}/s"
upgrade_label = QLabel(stats_text)
upgrade_label.setFont(QFont("Arial", 11))
upgrade_label.setWordWrap(True) # Enable word wrap
upgrade_layout.addWidget(upgrade_label)
# Store the widget and label for later use
self.upgrade_stat_widgets[upgrade.name] = {
"widget": upgrade_widget,
"label": upgrade_label
}
# Only add to layout if already unlocked (for loading saved games)
if upgrade.count > 0:
party_content_layout.addWidget(upgrade_widget)
# Store the upgrade label in stats_labels
self.stats_labels[upgrade.name] = upgrade_label
# Add stretch at the end to push content to the top
party_content_layout.addStretch(1)
party_scroll.setWidget(party_content)
stats_layout.addWidget(party_scroll)
# Create enemies tab for tracking enemy statistics
enemies_tab = QWidget()
enemies_layout = QVBoxLayout(enemies_tab)
# Add header label
enemies_header_label = QLabel("Enemy Statistics")
enemies_header_label.setFont(QFont("Arial", 20, QFont.Weight.Bold))
enemies_header_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
enemies_layout.addWidget(enemies_header_label)
# Create a scrollable area for enemy statistics
enemies_scroll = QScrollArea()
enemies_scroll.setWidgetResizable(True)
enemies_content = QWidget()
self.enemies_content_layout = QVBoxLayout(enemies_content)
self.enemies_content_layout.setSpacing(5)
self.enemies_content_layout.setContentsMargins(10, 10, 10, 10)
# Create a message for when no enemies have been defeated
self.no_enemies_label = QLabel("No enemies defeated yet. Fight some monsters!")
self.no_enemies_label.setFont(QFont("Arial", 14))
self.no_enemies_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.enemies_content_layout.addWidget(self.no_enemies_label)
# Dictionary to store enemy statistic widgets
self.enemy_stat_widgets = {}
# Add stretch to push content to the top
self.enemies_content_layout.addStretch(1)
enemies_scroll.setWidget(enemies_content)
enemies_layout.addWidget(enemies_scroll)
# Add tabs to tab widget
self.tab_widget.addTab(game_tab, "Adventure")
self.tab_widget.addTab(achievements_tab, "Achievements")
self.tab_widget.addTab(stats_tab, "Stats")
self.tab_widget.addTab(enemies_tab, "Enemies")
# Setup auto-clicker timer with longer interval
self.timer = QTimer()
self.timer.timeout.connect(self.auto_click)
self.timer.start(250) # Update every 250ms instead of 100ms
# Setup stats update timer with longer interval
self.stats_timer = QTimer()
self.stats_timer.timeout.connect(self.update_stats)
self.stats_timer.start(2000) # Update every 2 seconds instead of 1 second
# Setup auto-save timer with longer interval
self.auto_save_timer = QTimer()
self.auto_save_timer.timeout.connect(self.auto_save)
self.auto_save_timer.start(60000) # Auto-save every 60 seconds instead of 30 seconds
def setup_audio(self):
# Define sound file paths
self.monster_sound_paths = []
for i in range(1, 6): # coin1.wav to coin5.wav - reuse coin sounds for now
path = os.path.abspath(f"audio/coin{i}.wav")