-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmain.py
More file actions
1019 lines (818 loc) · 43.4 KB
/
main.py
File metadata and controls
1019 lines (818 loc) · 43.4 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
# Dosidicus - a digital pet with a neural network | 2.1.2.0 March 2026
# main.py Entrypoint
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
import os
# BOOTSTRAP: Add the current directory and src directory to sys.path
# This ensures "from src.ui import Ui" works even if launched from elsewhere.
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
sys.path.insert(0, BASE_DIR)
import time
import sys
import json
import os
import shutil
import traceback
import multiprocessing
import logging
from PyQt5 import QtWidgets, QtCore
import random
import argparse
from src.ui import Ui
from src.tamagotchi_logic import TamagotchiLogic
from src.squid import Squid, Personality
from src.splash_screen import SplashScreen
from src.save_manager import SaveManager
from src.brain_tool import SquidBrainWindow
from src.display_scaling import DisplayScaling
from src.learning import LearningConfig
from src.plugin_manager import PluginManager
from src.brain_worker import BrainWorker
from src.config_manager import ConfigManager
from src.localisation import Localisation
def launch_brain_designer_process():
"""Entry point for Brain Designer in a separate process"""
from src.brain_designer_launcher import launch_brain_designer_process as _launch
_launch()
def setup_logging_configuration():
"""Initialize logging configuration"""
os.environ['QT_LOGGING_RULES'] = '*.debug=false;qt.qpa.*=false;qt.style.*=false'
os.makedirs('logs', exist_ok=True)
logging.basicConfig(
filename='logs/dosidicus_log.txt',
level=logging.ERROR,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def perform_cleanup_and_exit():
"""Recursively delete __pycache__ and logs directories."""
print("🧹 Cleaning environment...")
root_dir = os.path.dirname(os.path.abspath(__file__))
deleted_count = 0
for root, dirs, files in os.walk(root_dir, topdown=True):
# Filter and remove specific directories
# We iterate over a copy of dirs so we can modify the original list safely
for name in list(dirs):
if name in ['__pycache__', 'logs']:
path = os.path.join(root, name)
try:
shutil.rmtree(path)
print(f" Deleted: {path}")
dirs.remove(name) # Prevent os.walk from trying to enter this dir
deleted_count += 1
except Exception as e:
print(f" ❌ Failed to delete {path}: {e}")
print(f"✨ Cleanup complete. Removed {deleted_count} directories.")
def global_exception_handler(exctype, value, tb):
"""Global exception handler to log unhandled exceptions"""
error_message = ''.join(traceback.format_exception(exctype, value, tb))
logging.error("Unhandled exception:\n%s", error_message)
QtWidgets.QMessageBox.critical(None, "Error",
"An unexpected error occurred. Please check dosidicus_log.txt for details.")
class TeeStream:
"""Duplicate output to both console and file"""
def __init__(self, original_stream, file_stream):
self.original_stream = original_stream
self.file_stream = file_stream
def write(self, data):
self.original_stream.write(data)
self.file_stream.write(data)
self.file_stream.flush()
def flush(self):
self.original_stream.flush()
self.file_stream.flush()
class TimedMessageBox(QtWidgets.QDialog):
"""A message box that auto-closes after a timeout with a default choice"""
def __init__(self, parent, title, message, timeout_seconds=5):
super().__init__(parent)
self.setWindowTitle(title)
self.timeout_seconds = timeout_seconds
self.remaining_seconds = timeout_seconds
self.result_value = QtWidgets.QMessageBox.No # Default to No
self.loc = Localisation.instance()
# Setup UI
layout = QtWidgets.QVBoxLayout()
self.message_label = QtWidgets.QLabel(message)
self.message_label.setStyleSheet(f"font-size: {DisplayScaling.font_size(13)}pt;")
layout.addWidget(self.message_label)
# Auto-decline message
self.timer_label = QtWidgets.QLabel(self.loc.get("auto_decline", seconds=self.remaining_seconds))
self.timer_label.setStyleSheet(f"color: gray; font-size: {DisplayScaling.font_size(11)}pt;")
layout.addWidget(self.timer_label)
# Buttons
self.button_box = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Yes | QtWidgets.QDialogButtonBox.No
)
# Localise buttons manually since we use a custom dict system
self.button_box.button(QtWidgets.QDialogButtonBox.Yes).setText(self.loc.get("yes"))
self.button_box.button(QtWidgets.QDialogButtonBox.No).setText(self.loc.get("no"))
self.button_box.accepted.connect(self.accept_yes)
self.button_box.rejected.connect(self.reject_no)
layout.addWidget(self.button_box)
self.setLayout(layout)
# Setup timer
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.update_countdown)
self.timer.start(1000) # Update every second
def update_countdown(self):
"""Update the countdown and auto-close when time runs out"""
self.remaining_seconds -= 1
self.timer_label.setText(self.loc.get("auto_decline", seconds=self.remaining_seconds))
if self.remaining_seconds <= 0:
self.timer.stop()
self.reject_no() # Auto-close with No
def accept_yes(self):
"""User clicked Yes"""
self.timer.stop()
self.result_value = QtWidgets.QMessageBox.Yes
self.accept()
def reject_no(self):
"""User clicked No or timeout occurred"""
self.timer.stop()
self.result_value = QtWidgets.QMessageBox.No
self.reject()
def get_result(self):
"""Get the result after dialog closes"""
return self.result_value
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, specified_personality=None, debug_mode=False, neuro_cooldown=None):
super().__init__()
# Apply configured language from config.ini
config_manager = ConfigManager()
language = config_manager.get_language()
Localisation.instance().set_language(language)
print(f"📄 Applied language from config: {language}")
# Initialize configuration
self.config = LearningConfig()
if neuro_cooldown is not None:
self.config.neurogenesis['cooldown'] = neuro_cooldown
# Add initialization tracking flag
self._initialization_complete = False
# Set up debugging
self.debug_mode = debug_mode
if self.debug_mode:
self.setup_logging()
# Initialize UI first
logging.debug("Initializing UI")
self.user_interface = Ui(self, debug_mode=self.debug_mode)
# Initialize SquidBrainWindow with config
logging.debug("Initializing SquidBrainWindow")
self.brain_window = SquidBrainWindow(None, self.debug_mode, self.config)
# Store the original window reference to prevent garbage collection
self._brain_window_ref = self.brain_window
# Explicitly force creation of all tab contents
QtCore.QTimer.singleShot(100, self.preload_brain_window_tabs)
# Continue with normal initialization
self.brain_window.set_tamagotchi_logic(None) # Placeholder to ensure initialization
self.user_interface.squid_brain_window = self.brain_window
# Initialize plugin manager after UI and brain window
logging.debug("Initializing PluginManager")
self.plugin_manager = PluginManager()
print(f"> Plugin manager initialized: {self.plugin_manager}")
self.specified_personality = specified_personality
self.neuro_cooldown = neuro_cooldown
self.squid = None
# Check for existing save data
self.save_manager = SaveManager("saves")
# Track whether we want to show tutorial
self.show_tutorial = False
# ===== PERFORMANCE FIX: Single BrainWorker managed by brain_tool =====
# Don't create another worker here - SquidBrainWindow creates and shares it
# Access via self.brain_window.brain_worker if needed
self.brain_worker = None
print("ℹ️ BrainWorker managed by SquidBrainWindow")
# Initialize the game
logging.debug("Initializing game")
self.initialize_game()
# Now that tamagotchi_logic is created, set it in plugin_manager and brain_window
logging.debug("Setting tamagotchi_logic references")
self.plugin_manager.tamagotchi_logic = self.tamagotchi_logic
self.tamagotchi_logic.plugin_manager = self.plugin_manager
self.brain_window.set_tamagotchi_logic(self.tamagotchi_logic)
# New in 2.4.5.0 : Create a unique personality starter neuron
squid = self.tamagotchi_logic.squid
brain_widget = self.brain_window.brain_widget
if (squid and squid.personality and
brain_widget and hasattr(brain_widget, 'enhanced_neurogenesis')):
if not squid._has_personality_starter_neuron():
neuron = brain_widget.enhanced_neurogenesis.create_personality_starter_neuron(
squid.personality.value,
brain_widget.state
)
if neuron:
print(f"🧬 Personality starter neuron created: {neuron}")
# Load and initialize plugins after core components
logging.debug("Loading plugins")
plugin_results = self.plugin_manager.load_all_plugins()
# Setup plugins with tamagotchi_logic reference
for plugin_name, plugin_data in self.plugin_manager.plugins.items():
instance = plugin_data.get('instance')
if instance and hasattr(instance, 'setup') and not plugin_data.get('is_setup', False):
try:
instance.setup(self.plugin_manager, self.tamagotchi_logic)
plugin_data['is_setup'] = True
except Exception as e:
print(f"Error setting up plugin {plugin_name}: {e}")
# CRITICAL FIX: Re-load achievement data since plugin instances were replaced
# during load_all_plugins(), discarding any data loaded earlier
if self.save_manager.save_exists():
save_data = self.save_manager.load_game()
if save_data and 'achievements' in save_data:
self._restore_achievements_data(save_data['achievements'])
# Update status bar with plugin information
if hasattr(self.user_interface, 'status_bar'):
self.user_interface.status_bar.update_plugins_status(self.plugin_manager)
# Connect signals
self.user_interface.new_game_action.triggered.connect(self.start_new_game)
self.user_interface.load_action.triggered.connect(self.load_game)
self.user_interface.save_action.triggered.connect(self.save_game)
self.user_interface.decorations_action.triggered.connect(self.user_interface.toggle_decoration_window)
# Initialize plugin menu - do this AFTER loading plugins
self.user_interface.apply_plugin_menu_registrations(self.plugin_manager)
# Position window 300 pixels to the left of default position
desktop = QtWidgets.QApplication.desktop()
screen_rect = desktop.screenGeometry()
window_rect = self.geometry()
center_x = screen_rect.center().x()
window_x = center_x - (window_rect.width() // 2) # Default centered X position
# Move 300 pixels to the left
self.move(window_x - 300, self.y())
if self.debug_mode:
print(f"DEBUG MODE ENABLED: Console output is being logged to console.txt")
self.setup_facts_timer()
def preload_brain_window_tabs(self):
"""Force creation of all tab contents to prevent crashes during tutorial"""
print("Pre-loading brain window tabs...")
if not hasattr(self, 'brain_window') or not self.brain_window:
print("⚠️ Brain window not initialized, cannot preload")
return
try:
# Force the window to process events and initialize all tabs
if hasattr(self.brain_window, 'tabs'):
# Visit each tab to ensure it's loaded
tab_count = self.brain_window.tabs.count()
# Initialize tabs array to prevent garbage collection
if not hasattr(self, '_preloaded_tabs'):
self._preloaded_tabs = []
# Remember if window was visible before we started
was_visible = self.brain_window.isVisible()
#print(f"📋 Brain window was_visible before preload: {was_visible}")
# Temporarily show the window off-screen to force loading
original_pos = self.brain_window.pos()
self.brain_window.move(-10000, -10000) # Move off-screen
self.brain_window.show()
# Force each tab to be displayed at least once
for i in range(tab_count):
self.brain_window.tabs.setCurrentIndex(i)
QtWidgets.QApplication.processEvents()
# Get and store references to tab widgets
widget = self.brain_window.tabs.widget(i)
if widget:
self._preloaded_tabs.append(widget)
#print(f" ✓ Preloaded tab {i}: {self.brain_window.tabs.tabText(i)}")
# Return to first tab (Network/Brain tab)
self.brain_window.tabs.setCurrentIndex(0)
QtWidgets.QApplication.processEvents()
#print(f"📋 Reset to first tab: {self.brain_window.tabs.tabText(0)}")
# Restore original position
self.brain_window.move(original_pos)
# Only hide if it wasn't visible before (don't hide if user is viewing it)
if not was_visible:
self.brain_window.hide()
print("📋 Brain window hidden after preload (was not visible before)")
else:
print("📋 Brain window kept visible after preload (was visible before)")
print(f"✅ Successfully preloaded {len(self._preloaded_tabs)} tabs")
except Exception as e:
print(f"❌ Error preloading tabs: {e}")
import traceback
traceback.print_exc()
def setup_logging(self):
"""Set up console logging to file"""
if not hasattr(sys, '_original_stdout'):
sys._original_stdout = sys.stdout
sys._original_stderr = sys.stderr
console_log = open('console.txt', 'w', encoding='utf-8')
sys.stdout = TeeStream(sys._original_stdout, console_log)
sys.stderr = TeeStream(sys._original_stderr, console_log)
def setup_facts_timer(self):
"""Rare ocean-blue Humboldt squid facts every 5 minutes"""
config_manager = ConfigManager()
if not config_manager.get_facts_enabled():
return
self.fact_timer = QtCore.QTimer(self)
self.fact_timer.timeout.connect(self.show_random_squid_fact)
self.fact_timer.start(config_manager.get_fact_interval_ms())
def show_random_squid_fact(self):
"""Show one short Humboldt squid fact – big, bright blue, always visible"""
try:
from src.squid_facts import get_random_fact
fact = get_random_fact()
if not fact:
return
msg = f"🌊 Humboldt Fact: {fact}"
# Preferred: status bar (works everywhere, supports color)
if hasattr(self.user_interface, 'status_bar') and self.user_interface.status_bar:
colored_msg = f'<span style="color:#00BFFF; font-weight:bold; font-size:14px;">{msg}</span>'
self.user_interface.status_bar.showMessage(colored_msg, 8000) # 8 seconds
else:
# Fallback: plain message
self.user_interface.show_message(msg)
print(f"[Facts] DISPLAYED: {fact[:80]}...") # helpful console confirmation
except Exception as e:
print(f"[Facts] Error showing fact: {e}")
def initialize_game(self):
if hasattr(self.save_manager, 'cleanup_duplicate_saves'):
self.save_manager.cleanup_duplicate_saves()
if self.save_manager.save_exists() and self.specified_personality is None:
print("\x1b[32mExisting save data found and will be loaded\x1b[0m")
self.squid = Squid(self.user_interface, None, None)
self.tamagotchi_logic = TamagotchiLogic(self.user_interface, self.squid, self.brain_window)
self.squid.tamagotchi_logic = self.tamagotchi_logic
self.user_interface.tamagotchi_logic = self.tamagotchi_logic
self.brain_window.tamagotchi_logic = self.tamagotchi_logic
if hasattr(self.brain_window, 'set_tamagotchi_logic'):
self.brain_window.set_tamagotchi_logic(self.tamagotchi_logic)
self.load_game()
if hasattr(self.tamagotchi_logic, 'statistics_window'):
self.tamagotchi_logic.statistics_window.update_statistics()
brain_widget = self.brain_window.brain_widget
for name in brain_widget.original_neurons:
brain_widget.visible_neurons.add(name)
if hasattr(brain_widget, 'neurogenesis_data'):
for name in brain_widget.neurogenesis_data.get('new_neurons_details', {}):
brain_widget.visible_neurons.add(name)
core = brain_widget.original_neurons
for idx, name in enumerate(core):
QtCore.QTimer.singleShot(idx * 500, lambda n=name: brain_widget.reveal_neuron(n))
self.brain_window.show()
self.user_interface.brain_action.setChecked(True)
else:
print("\x1b[92m-------------- STARTING A NEW SIMULATION --------------\x1b[0m")
self.create_new_game(self.specified_personality)
self.tamagotchi_logic = TamagotchiLogic(self.user_interface, self.squid, self.brain_window)
self.squid.tamagotchi_logic = self.tamagotchi_logic
self.user_interface.tamagotchi_logic = self.tamagotchi_logic
self.brain_window.tamagotchi_logic = self.tamagotchi_logic
if hasattr(self.brain_window, 'set_tamagotchi_logic'):
self.brain_window.set_tamagotchi_logic(self.tamagotchi_logic)
if not self.save_manager.save_exists():
QtCore.QTimer.singleShot(500, self.delayed_tutorial_check)
self._initialization_complete = True
def delayed_tutorial_check(self):
"""Check if the user wants to see the tutorial after UI is responsive"""
# Process pending events to ensure UI is responsive
QtWidgets.QApplication.processEvents()
# Now check tutorial preference
self.check_tutorial_preference()
# If tutorial was chosen, schedule it for later
if self.show_tutorial:
# We'll show tutorial when the game starts
pass
else:
# Just open initial windows if no tutorial
QtCore.QTimer.singleShot(500, self.open_initial_windows)
def create_new_game(self, specified_personality=None):
"""Create a new game instance"""
# Delete any existing save to ensure clean start
if self.save_manager.save_exists():
self.save_manager.delete_save()
# Choose personality randomly if not specified
if specified_personality is None:
personality = random.choice(list(Personality))
else:
personality = specified_personality
# Create new squid with chosen personality
self.squid = Squid(
user_interface=self.user_interface,
tamagotchi_logic=None,
personality=personality,
neuro_cooldown=self.neuro_cooldown
)
print(f" ")
print(f">> Generated squid personality: {self.squid.personality.value}")
print(f" ")
if self.neuro_cooldown:
print(f"\x1b[43m Neurogenesis cooldown:\033[0m {self.neuro_cooldown}")
self.squid.memory_manager.clear_all_memories()
self.show_splash_screen()
def check_tutorial_preference(self):
"""Show a dialog asking if the user wants to see the tutorial with 5-second timeout"""
# Don't ask about tutorial if save data exists
if self.save_manager.save_exists():
self.show_tutorial = False
return
# Show timed dialog
dialog = TimedMessageBox(
self,
Localisation.instance().get("startup"),
Localisation.instance().get("show_tutorial_q"),
timeout_seconds=5
)
dialog.exec_()
# Set flag based on user's choice (defaults to No if timeout)
self.show_tutorial = (dialog.get_result() == QtWidgets.QMessageBox.Yes)
def position_and_show_decoration_window(self):
"""Position the decoration window in the bottom right and show it"""
if hasattr(self.user_interface, 'decoration_window') and self.user_interface.decoration_window:
# Get screen geometry
screen_geometry = QtWidgets.QApplication.desktop().availableGeometry()
# Position window in bottom right
decoration_window = self.user_interface.decoration_window
decoration_window.move(
screen_geometry.right() - decoration_window.width() - 20,
screen_geometry.bottom() - decoration_window.height() - 20
)
decoration_window.show()
self.user_interface.decorations_action.setChecked(True)
def start_new_game(self):
"""Start a new game, deleting any existing save"""
# First, ask for confirmation with a timed dialog
confirm_dialog = TimedMessageBox(
self,
"Confirm New Game",
"Are you sure you want to start a new game? This will delete all current progress and save data.",
timeout_seconds=10
)
confirm_dialog.exec_()
# If user declined or let it timeout, abort
if confirm_dialog.get_result() != QtWidgets.QMessageBox.Yes:
print("New game cancelled by user")
return
print("Starting new game...")
# Ask about tutorial
tutorial_dialog = TimedMessageBox(
self,
Localisation.instance().get("tutorial_title"),
Localisation.instance().get("tutorial_query"),
timeout_seconds=5
)
tutorial_dialog.exec_()
self.show_tutorial = (tutorial_dialog.get_result() == QtWidgets.QMessageBox.Yes)
# Stop current simulation if running
if hasattr(self, 'tamagotchi_logic'):
self.tamagotchi_logic.stop()
# Stop autosave timer if it exists
if hasattr(self.tamagotchi_logic, 'autosave_timer'):
self.tamagotchi_logic.autosave_timer.stop()
# Delete all save files (both autosave and manual save)
if self.save_manager.save_exists():
self.save_manager.delete_save(is_autosave=True) # Delete autosave
self.save_manager.delete_save(is_autosave=False) # Delete manual save
print("All save files deleted")
# Clear memory files
memory_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '_memory')
if os.path.exists(memory_dir):
import shutil
shutil.rmtree(memory_dir)
print("Memory directory cleared")
# Clear all neurons and state from brain window
if hasattr(self, 'brain_window') and hasattr(self.brain_window, 'brain_widget'):
brain_widget = self.brain_window.brain_widget
# Clear visible neurons
brain_widget.visible_neurons = set()
# Clear neurogenesis data
if hasattr(brain_widget, 'neurogenesis_data'):
brain_widget.neurogenesis_data = {
'new_neurons': [],
'new_neurons_details': {},
'new_synapses': []
}
# Clear enhanced neurogenesis tracking
if hasattr(brain_widget, 'enhanced_neurogenesis'):
brain_widget.enhanced_neurogenesis.reset_state()
# Reset brain widget state
if hasattr(brain_widget, 'state'):
brain_widget.state = brain_widget.create_initial_state()
# Clear hebbian learning state
if hasattr(brain_widget, 'hebbian'):
brain_widget.hebbian.reset()
print("Brain state cleared")
# Clear all decorations and items from the scene
if hasattr(self, 'user_interface') and hasattr(self.user_interface, 'scene'):
# Remove all items except the background (if it exists)
items_to_remove = []
background_item = getattr(self.user_interface, 'background', None)
for item in self.user_interface.scene.items():
# Keep the background (if it exists) and remove everything else
if background_item is None or item != background_item:
items_to_remove.append(item)
for item in items_to_remove:
self.user_interface.scene.removeItem(item)
# Clear decoration tracking
if hasattr(self.user_interface, 'awarded_decorations'):
self.user_interface.awarded_decorations = set()
print("Scene cleared")
# Create new game (creates squid but not tamagotchi_logic)
self.create_new_game(self.specified_personality)
# Create TamagotchiLogic
self.tamagotchi_logic = TamagotchiLogic(self.user_interface, self.squid, self.brain_window)
# Update references
self.squid.tamagotchi_logic = self.tamagotchi_logic
self.user_interface.tamagotchi_logic = self.tamagotchi_logic
self.brain_window.tamagotchi_logic = self.tamagotchi_logic
if hasattr(self.brain_window, 'set_tamagotchi_logic'):
self.brain_window.set_tamagotchi_logic(self.tamagotchi_logic)
self.plugin_manager.tamagotchi_logic = self.tamagotchi_logic
self.tamagotchi_logic.plugin_manager = self.plugin_manager
# Create personality starter neuron if needed
squid = self.tamagotchi_logic.squid
brain_widget = self.brain_window.brain_widget
if (squid and squid.personality and
brain_widget and hasattr(brain_widget, 'enhanced_neurogenesis')):
if not squid._has_personality_starter_neuron():
neuron = brain_widget.enhanced_neurogenesis.create_personality_starter_neuron(
squid.personality.value,
brain_widget.state
)
if neuron:
print(f"🧬 Personality starter neuron created: {neuron}")
# Reload plugins to ensure they get the new tamagotchi_logic
self.plugin_manager.reload_all_plugins()
print("New game created successfully!")
def load_game(self):
"""Delegate to tamagotchi_logic"""
self.tamagotchi_logic.load_game()
def save_game(self):
"""Delegate to tamagotchi_logic"""
if self.squid and self.tamagotchi_logic:
self.tamagotchi_logic.save_game()
def _restore_achievements_data(self, achievements_data):
"""Restore achievement data to the achievements plugin after plugin reload.
This is needed because plugin instances get replaced during initialization,
discarding any previously loaded save data.
"""
if not achievements_data:
return
try:
if 'achievements' in self.plugin_manager.plugins:
plugin_info = self.plugin_manager.plugins['achievements']
instance = plugin_info.get('instance')
if instance and hasattr(instance, 'load_save_data'):
instance.load_save_data(achievements_data)
unlocked_count = len(achievements_data.get('unlocked', {}))
print(f"✓ Restored {unlocked_count} achievements")
except Exception as e:
print(f"[Warning] Could not restore achievements: {e}")
def closeEvent(self, event):
"""Handle window close event"""
# Save game before closing
if hasattr(self, 'tamagotchi_logic') and self.tamagotchi_logic:
self.save_game()
# Stop the tamagotchi logic if it has a stop method
if hasattr(self, 'tamagotchi_logic') and self.tamagotchi_logic:
if hasattr(self.tamagotchi_logic, 'stop'):
self.tamagotchi_logic.stop()
# Stop the timer if it exists
elif hasattr(self.tamagotchi_logic, 'timer') and self.tamagotchi_logic.timer:
self.tamagotchi_logic.timer.stop()
# Clean up brain state bridge for designer sync
if hasattr(self, 'brain_window') and self.brain_window:
if hasattr(self.brain_window, 'brain_widget') and self.brain_window.brain_widget:
if hasattr(self.brain_window.brain_widget, 'cleanup_brain_bridge'):
self.brain_window.brain_widget.cleanup_brain_bridge()
# Close brain window
if hasattr(self, 'brain_window') and self.brain_window:
self.brain_window.close()
event.accept()
def show_splash_screen(self):
"""Display splash screen animation with synchronized neuron reveal"""
self.splash = SplashScreen(self)
self.splash.finished.connect(self.start_simulation)
self.splash.finished.connect(lambda: self.tamagotchi_logic.statistics_window.award(1000))
self.splash.second_frame.connect(self.show_hatching_notification)
# NEW: award 1000 points the instant the splash ends
self.splash.finished.connect(
lambda: self.tamagotchi_logic.statistics_window.award(1000)
)
# After splash ends, wait 3 s then show the normal feeding hint
self.splash.finished.connect(lambda: QtCore.QTimer.singleShot(3000, self.show_feeding_hint))
# Check if this is a brand new game (no save exists)
is_new_game = not self.save_manager.save_exists()
print(f"🎮 show_splash_screen: is_new_game={is_new_game}, save_exists={self.save_manager.save_exists()}")
if is_new_game:
# Ensure brain widget starts empty
if hasattr(self.brain_window, 'brain_widget') and hasattr(self.brain_window.brain_widget, 'visible_neurons'):
self.brain_window.brain_widget.visible_neurons = set()
# Show brain window first
self.brain_window.show()
self.user_interface.brain_action.setChecked(True)
# Force immediate processing to ensure brain window is painted
QtWidgets.QApplication.processEvents()
# Give the brain window time to fully render (longer delay)
QtCore.QTimer.singleShot(1500, lambda: self._start_splash_with_reveals())
else:
# For loaded games, show brain window with all neurons visible
if hasattr(self.brain_window, 'brain_widget') and hasattr(self.brain_window.brain_widget, 'visible_neurons'):
brain_widget = self.brain_window.brain_widget
# Add all core neurons to visible set
for neuron_name in brain_widget.original_neurons:
brain_widget.visible_neurons.add(neuron_name)
# Also add any neurogenesis neurons that exist
if hasattr(brain_widget, 'neurogenesis_data') and 'new_neurons_details' in brain_widget.neurogenesis_data:
for neuron_name in brain_widget.neurogenesis_data['new_neurons_details'].keys():
brain_widget.visible_neurons.add(neuron_name)
# Show brain window immediately for loaded games
self.brain_window.show()
self.user_interface.brain_action.setChecked(True)
# Force immediate processing to ensure brain window is painted
QtWidgets.QApplication.processEvents()
# Show splash normally (no animated reveals needed for loaded games)
self.splash.show()
QtCore.QTimer.singleShot(1000, self.splash.start_animation)
def show_feeding_hint(self):
"""Use the same strip as every other message."""
self.user_interface.show_message("Press D to open the Decorations window")
def _start_splash_with_reveals(self):
"""Start splash screen with neuron reveal synchronization (called after brain window is ready)"""
print(" 🥚 A squid is hatching...")
# Connect frame changes to neuron reveals
self.splash.frame_changed.connect(self._reveal_neuron_for_frame)
# Show and start the splash screen animation
self.splash.show()
QtCore.QTimer.singleShot(500, self.splash.start_animation) # Small delay for splash to show
def _reveal_neuron_for_frame(self, frame_index):
"""Reveal core neurons in sequence with animation frames"""
if not hasattr(self.brain_window, 'brain_widget'):
return
brain_widget = self.brain_window.brain_widget
core_neurons = brain_widget.original_neurons
# Distribution: 1-2 neurons per frame. Now revised for 8 core neurons (indices 0-7)
reveal_map = {
0: [0], # First frame
1: [1], # Second frame
2: [2], # Third frame
3: [3], # Fourth frame
4: [4, 5], # Fifth frame
5: [6, 7] # Sixth frame
}
# Reveal mapped neurons for this frame
for neuron_idx in reveal_map.get(frame_index, []):
if neuron_idx < len(core_neurons):
neuron_name = core_neurons[neuron_idx]
brain_widget.reveal_neuron(neuron_name)
#print(f"🧠 Revealed neuron: {neuron_name} (frame {frame_index})")
def show_hatching_notification(self):
"""Display hatching message"""
self.user_interface.show_message("Squid is hatching!")
def start_simulation(self):
"""Begin the simulation - brain window is already visible for new games"""
self.cleanup_duplicate_squids()
self.tamagotchi_logic.set_simulation_speed(1)
self.tamagotchi_logic.start_autosave()
# Get brain widget reference
brain_widget = self.brain_window.brain_widget
# Show tutorial if enabled
if self.show_tutorial:
QtCore.QTimer.singleShot(1000, self.user_interface.show_tutorial_overlay)
else:
# === FIX START: Manual cleanup if tutorial is skipped ===
if hasattr(brain_widget, 'is_tutorial_mode'):
# Set the flag to False, which allows connections to draw
brain_widget.is_tutorial_mode = False
# OPTIONAL: If setting the flag doesn't immediately refresh the links,
# you may need to force a repaint. If the links are set to show,
# a simple repaint will usually draw them once the block is gone.
brain_widget.update() # Force repaint
# === FIX END ===
# Only open decoration window automatically (brain window already visible for new games)
QtCore.QTimer.singleShot(500, self.position_and_show_decoration_window)
def show_tutorial_overlay(self):
"""Delegate to UI layer and ensure no duplicates remain"""
# First do one more duplicate cleanup
self.cleanup_duplicate_squids()
# Then show the tutorial via the UI
if hasattr(self, 'user_interface') and self.user_interface:
self.user_interface.show_tutorial_overlay()
def open_initial_windows(self):
"""Open brain window and decorations window"""
# Open brain window
if hasattr(self, 'brain_window'):
self.brain_window.show()
self.user_interface.brain_action.setChecked(True)
# Open decorations window
if hasattr(self.user_interface, 'decoration_window'):
self.position_and_show_decoration_window()
self.user_interface.decorations_action.setChecked(True)
def cleanup_duplicate_squids(self):
"""Remove any duplicate squid items from the scene"""
if not hasattr(self, 'user_interface') or not self.user_interface:
return
if not hasattr(self, 'squid') or not self.squid:
return
try:
# Get the reference to our genuine squid item
main_squid_item = self.squid.squid_item
# Get all items in the scene
all_items = self.user_interface.scene.items()
# Track how many items we find and remove
found_count = 0
# Look for graphics items that could be duplicate squids
for item in all_items:
# Skip our genuine squid item
if item == main_squid_item:
continue
# Only check QGraphicsPixmapItems
if isinstance(item, QtWidgets.QGraphicsPixmapItem):
# Check if it has the same pixmap dimensions as our squid
if (hasattr(item, 'pixmap') and item.pixmap() and main_squid_item.pixmap() and
item.pixmap().width() == main_squid_item.pixmap().width() and
item.pixmap().height() == main_squid_item.pixmap().height()):
print(f"Found potential duplicate squid item - removing")
self.user_interface.scene.removeItem(item)
found_count += 1
if found_count > 0:
print(f"Cleaned up {found_count} duplicate squid items")
# Force scene update
self.user_interface.scene.update()
except Exception as e:
print(f"Error during cleanup: {str(e)}")
def initialize_multiplayer_manually(self):
"""Manually initialize multiplayer plugin if needed"""
try:
# Import the plugin module directly
import sys
import os
plugin_path = os.path.join(os.path.dirname(__file__), 'plugins', 'multiplayer')
if plugin_path not in sys.path:
sys.path.insert(0, plugin_path)
import main as multiplayer_main
# Create plugin instance
multiplayer_plugin = multiplayer_main.MultiplayerPlugin()
# Find it in plugin_manager and add the instance
for plugin_name, plugin_data in self.plugin_manager.plugins.items():
if plugin_name.lower() == "multiplayer":
plugin_data['instance'] = multiplayer_plugin
print(f"Manually added multiplayer plugin instance to {plugin_name}")
# Initialize the plugin
if hasattr(multiplayer_plugin, 'setup'):
multiplayer_plugin.setup(self.plugin_manager)
# Register menu actions
if hasattr(multiplayer_plugin, 'register_menu_actions'):
multiplayer_plugin.register_menu_actions()
break
# Force the UI to refresh plugin menu
self.user_interface.setup_plugin_menu(self.plugin_manager)
#print("Manual multiplayer initialization complete")
return True
except Exception as e:
print(f"Error in manual multiplayer initialization: {e}")
import traceback
traceback.print_exc()
return False
def main():
"""Main entry point"""
# CRITICAL for PyInstaller + multiprocessing on Windows
multiprocessing.freeze_support()
sys.excepthook = global_exception_handler
parser = argparse.ArgumentParser(description="Dosidicus digital squid with a neural network")
parser.add_argument('-p', '--personality', type=str,
choices=[p.value for p in Personality],
help='Specify squid personality')
parser.add_argument('-d', '--debug', action='store_true',
help='Enable debug mode with console logging')
parser.add_argument('-nc', '--neurocooldown', type=int,
help='Set neurogenesis cooldown in seconds')
parser.add_argument('-c', '--clean', action='store_true',
help='Clean __pycache__ and logs folders before starting')
parser.add_argument('-designer', '--designer', action='store_true',
help='Launch Brain Designer standalone')
args = parser.parse_args()
# Perform cleanup if requested before logging setup
if args.clean:
perform_cleanup_and_exit()
# Launch designer if flag is set
if args.designer:
print("Launching Brain Designer standalone...")
try:
# Import and run designer's main function
try:
from src import brain_designer
except ImportError:
import brain_designer
# brain_designer.main() will parse sys.argv and handle -d and -c flags automatically
brain_designer.main()
except ImportError as e:
print(f"Error: Could not import brain_designer module: {e}")
sys.exit(1)
except Exception as e:
print(f"Error launching designer: {e}")
sys.exit(1)
return # Exit after designer closes
# Initialize logging (replaces previous global setup)
setup_logging_configuration()