-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGarden-of-Inheritance.py
More file actions
8901 lines (7630 loc) · 352 KB
/
Garden-of-Inheritance.py
File metadata and controls
8901 lines (7630 loc) · 352 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
"""
Garden of Inheritance - Pea Garden Genetics Simulator
Main application file for Mendel's Pea Garden simulation.
Provides a visual interface for exploring Mendelian genetics through
plant breeding experiments.
Overview:
---------
This application simulates a garden where users can plant, breed, and observe
pea plants to discover Mendelian genetics principles. The simulation includes:
Features:
---------
- Interactive garden grid with tile-based plant placement
- Real-time plant growth and development simulation
- Genetic trait inheritance (flower color, pod color, seed traits, height)
- Breeding mechanics (pollination, emasculation, self-pollination)
- Seed harvesting and inventory management
- Historical archive browser for pedigree analysis
- Mendelian law detection (Dominance, Segregation, Independent Assortment)
- Environmental simulation (weather, temperature, seasons)
- Day/night visual cycles
- Time controls (pause, fast-forward, auto-advance)
Architecture:
-------------
The application is organized around these main components:
1. **GardenApp**: Main application class managing UI and game loop
2. **GardenEnvironment**: Manages time, weather, and environmental state
3. **Plant**: Individual plant simulation with genetics
4. **TileCanvas**: Visual representation of garden tiles
5. **Inventory**: Seed and pollen storage
6. **TraitInheritanceExplorer**: Pedigree viewer and analysis tool
File Structure:
---------------
- Lines 1-365: Imports, configuration, helper classes
- Lines 366-5892: GardenApp class (main application)
- Event handlers
- UI building (_build_ui)
- Rendering (render_all, selection panel)
- Plant interactions (pollinate, harvest, etc.)
- Time and simulation controls
- Archive and save system
Version: v69
Author: Based on Gregor Mendel's pea experiments (1856-1863)
"""
# ============================================================================
# Imports
# ============================================================================
# --- Standard Library (Built-ins) ---
import csv
import json
import logging
import os
import random
import re
import sys
import time
import datetime as dt
import math
from collections import defaultdict
from pathlib import Path
from typing import List, Set
# --- Third-Party / Installed Modules ---
from PIL import Image, ImageDraw, ImageTk
import tkinter as tk
from tkinter import (
colorchooser,
messagebox,
simpledialog,
Toplevel,
ttk,
)
# --- Local Modules / Single-File Embeds ---
from crashhandler import CrashHandler
from tile import TileCanvas
from plant import Plant, STAGE_NAMES
from traitinheritanceexplorer import TraitInheritanceExplorer
from garden import GardenEnvironment
from mendelclimate import MendelClimate
from icon_loader import *
# Wildlife (bees, butterflies, Bruchus pisi) — optional, fails silently if missing
try:
from wildlife import WildlifeManager as _WildlifeManager
except ImportError:
_WildlifeManager = None
from inventory import Inventory, InventoryPopup, PollenChooserPopup, Seed, Pollen
from mendel_temperature_tracker import TemperatureTracker
from emasculation_dialog import EmasculationDialog
from pollination_dialog import PollinationDialog
from mendelian_law_wizard import MendelianLawWizard
# ============================================================================
# Logging Configuration
# ============================================================================
def _pg_base_dir():
"""Get base directory for the application."""
try:
return os.path.dirname(os.path.abspath(__file__))
except Exception:
return os.getcwd()
_PG_BASE_DIR = _pg_base_dir()
_PG_LOG_PATH = os.path.join(_PG_BASE_DIR, "pea_garden.log")
# Configure logging (if not already configured)
if not logging.getLogger().handlers:
logging.basicConfig(
filename=_PG_LOG_PATH,
filemode="a",
level=logging.ERROR,
format="%(asctime)s %(levelname)s %(message)s"
)
# ============================================================================
# Resource Path Management
# ============================================================================
def __pg_script_dir():
"""
Get script directory, handling both normal and PyInstaller execution.
Returns:
Path object pointing to script directory
"""
try:
if getattr(sys, "frozen", False):
return Path(getattr(sys, "_MEIPASS", os.path.dirname(sys.executable)))
return Path(os.path.dirname(os.path.abspath(__file__)))
except Exception:
return Path(os.getcwd())
__PG_BASE_DIR = __pg_script_dir()
def resource_path(*parts) -> Path:
"""
Get path to resource file relative to application base.
Args:
*parts: Path components to join
Returns:
Path object to resource
"""
return __PG_BASE_DIR.joinpath(*parts)
# Set working directory to script location
try:
os.chdir(__PG_BASE_DIR)
except Exception:
pass
# ============================================================================
# Helper Function for Pollen Day Tracking
# ============================================================================
def _today(self) -> int:
"""
Get current day of month from garden environment.
Single source of truth for "today" used by pollen, seeds, UI, fast-forward.
Args:
self: Object with garden attribute
Returns:
Current day of month (0 if unavailable)
"""
return int(getattr(self.garden, "day_of_month", getattr(self.garden, "day", 0)))
# ============================================================================
# Visual Configuration
# ============================================================================
SOIL_COLORS = [
"#7f9f7a", # muted meadow green
"#88a884", # fresh spring grass
"#8fb28b", # sunlit patch
"#6f8f6a", # cool, dense grass
"#9abf97", # young growth
"#83a37f", # slightly dry grass
"#7a9a76", # balanced neutral
"#8caf89", # warm green
"#a3c6a0", # very light, fresh
"#8fae8b", # soft garden green
"#93b28f", # spring grass
"#9ab89a", # sunlit patch
"#84a77f", # cool green
]
# ============================================================================
# Dialog Classes
# ============================================================================
class FFDialog(simpledialog.Dialog):
"""
Fast-Forward dialog with options for:
- Number of days to advance
- Daily rendering toggle
- Hourly render interval (1-23 hours)
"""
def body(self, master):
"""
Build dialog body with input fields.
Args:
master: Parent widget
Returns:
Widget to receive initial focus
"""
tk.Label(
master,
text="Enter the number of days to fast-forward:"
).grid(row=0, column=0, sticky="w", pady=4)
# Days to fast-forward
self.days_var = tk.StringVar()
self.entry = tk.Entry(master, textvariable=self.days_var)
self.entry.grid(row=1, column=0, sticky="ew", pady=(0, 6))
# Daily rendering checkbox (ticked by default)
self.daily_var = tk.BooleanVar(value=True)
self.cb = tk.Checkbutton(
master,
text="Daily render (once per day)",
variable=self.daily_var,
anchor="w"
)
self.cb.grid(row=2, column=0, sticky="w", pady=(0, 4))
# Hourly render interval
tk.Label(
master,
text="Render every N simulated h (1–23):"
).grid(row=3, column=0, sticky="w", pady=(4, 2))
self.interval_var = tk.IntVar(value=9) # Default 9 hours
self.interval_spin = tk.Spinbox(
master,
from_=1,
to=23,
textvariable=self.interval_var,
width=5
)
self.interval_spin.grid(row=4, column=0, sticky="w", pady=(0, 6))
return self.entry # Initial focus on day entry
def apply(self):
"""Store dialog results when OK is pressed."""
self.result = {
"days": self.days_var.get(),
"daily": self.daily_var.get(),
"interval": self.interval_var.get(),
}
"""
pea_garden_ui_topbar.py — UI reorganized
- All buttons at the top (global + plant actions)
- Mendel image no longer at the bottom; sidebar on the left
- Grid on the right
"""
def _infer_pair_from_trait(dom, rec, is_dom_pheno, rng):
# Bias toward heterozygote when phenotype is dominant
if is_dom_pheno:
return (dom, rec) if rng.random() < 0.5 else (dom, dom)
else:
return (rec, rec)
def infer_genotype_from_traits(traits, rng):
t = {k.lower(): (v or "").lower() for k,v in (traits or {}).items()}
# Loci: R/r (seed shape), I/i (cotyledon), A/a (flower color), Le/le (height), Gp/gp (pod color),
# P/p and V/v (pod parchment/shape), Fa/fa with Mfa/mfa (modifier)
pair_R = _infer_pair_from_trait('R','r', t.get('seed_shape','') in ('round',''), rng)
pair_I = _infer_pair_from_trait('I','i', t.get('seed_color','') in ('yellow',''), rng)
pair_A = _infer_pair_from_trait('A','a', t.get('flower_color','') in ('purple','pigmented',''), rng)
pair_Le= _infer_pair_from_trait('Le','le', t.get('plant_height','') in ('tall',''), rng)
pair_Gp= _infer_pair_from_trait('Gp','gp', t.get('pod_color','') in ('green',''), rng)
ps = t.get('pod_shape','')
if ps in ('inflated',''):
pair_P = _infer_pair_from_trait('P','p', True, rng)
pair_V = _infer_pair_from_trait('V','v', True, rng)
else:
if rng.random() < 0.5:
pair_P = ('p','p'); pair_V = _infer_pair_from_trait('V','v', True, rng)
else:
pair_V = ('v','v'); pair_P = _infer_pair_from_trait('P','p', True, rng)
fp = t.get('flower_position','')
if fp.startswith('terminal'):
pair_Fa = ('fa','fa')
pair_Mfa= ('Mfa','Mfa')
else:
pair_Fa = _infer_pair_from_trait('Fa','fa', True, rng)
pair_Mfa= _infer_pair_from_trait('Mfa','mfa', True, rng)
return {'R':pair_R,'I':pair_I,'A':pair_A,'Le':pair_Le,'Gp':pair_Gp,'P':pair_P,'V':pair_V,'Fa':pair_Fa,'Mfa':pair_Mfa}
def random_gamete(geno, rng):
"""
Create a gamete from a genotype.
Genetics model:
- By default, loci assort independently.
- We add explicit linkage for Mendel loci that are on the same chromosome:
* Le (plant height) and V (pod form): ~12.6 cM apart -> recomb_frac ≈ 0.126
* R (seed shape) and Gp (pod colour): very weakly linked -> here we approximate recomb_frac ≈ 0.30
- All other Mendel loci (including A and I) are treated as unlinked.
"""
# Start with independent assortment for all non-internal loci
gam = {loc: rng.choice(pair) for loc, pair in geno.items()
if not str(loc).startswith("_")}
def _apply_pair_linkage(locus1, locus2, hap_tag, recomb_frac):
"""
Adjust the gamete for a pair of linked loci if the parent is
double-heterozygous at these loci.
We cache the parental phase (two haplotypes) in geno[hap_tag]
so that repeated meioses from the same parent are consistent.
"""
pair1 = geno.get(locus1)
pair2 = geno.get(locus2)
if not (pair1 and pair2):
return
# Need heterozygous at both loci, otherwise linkage is irrelevant
if len(set(pair1)) != 2 or len(set(pair2)) != 2:
return
# Get or establish parental haplotypes
hap = geno.get(hap_tag)
if hap is None:
a1, a2 = pair1[0], pair1[1]
b1, b2 = pair2[0], pair2[1]
# Randomly choose coupling-like vs repulsion-like phase
if rng.random() < 0.5:
# hap1 = (a1, b1), hap2 = (a2, b2)
hap = ((a1, b1), (a2, b2))
else:
# hap1 = (a1, b2), hap2 = (a2, b1)
hap = ((a1, b2), (a2, b1))
try:
geno[hap_tag] = hap
except Exception:
pass
# Decide whether this gamete is non-recombinant or recombinant
if rng.random() < (1.0 - recomb_frac):
# Non-recombinant: choose one of the parental haplotypes
chosen = hap[0] if rng.random() < 0.5 else hap[1]
else:
# Recombinant: mix the two parental haplotypes
h1, h2 = hap
recomb_options = ((h1[0], h2[1]), (h2[0], h1[1]))
chosen = recomb_options[0] if rng.random() < 0.5 else recomb_options[1]
gam[locus1], gam[locus2] = chosen[0], chosen[1]
# Real linkage pairs from pea genetics
_apply_pair_linkage("Le", "V", "_LeV_haps", recomb_frac=0.126) # strong-ish linkage
_apply_pair_linkage("R", "Gp", "_RGp_haps", recomb_frac=0.30) # weak linkage (almost independent)
return gam
def child_genotype(maternal_geno, pollen_gamete, rng):
child = {}
for loc,pair in maternal_geno.items():
a_m = rng.choice(pair)
a_p = pollen_gamete.get(loc, rng.choice(pair))
dom = loc
# sort dominant-first for stable display
child[loc] = tuple(sorted([a_m,a_p], key=lambda x: (0 if dom in str(x) else 1, str(x))))
# If child is double-heterozygous at I and A, assign a random phase for its future gametogenesis
try:
if len(set(child.get('I', ('?','?')))) == 2 and len(set(child.get('A', ('?','?')))) == 2:
child['_IA_haplotypes'] = (('I','A'), ('i','a')) if rng.random() < 0.5 else (('I','a'), ('i','A'))
except Exception:
pass
return child
def phenotype_from_genotype(geno):
# Resolve phenotype strings from genotype with simple dominance/epistasis
def has_dom(loc):
a1,a2 = geno.get(loc, ('?','?'))
return (loc in str(a1)) or (loc in str(a2))
def is_homo(loc, allele):
a1,a2 = geno.get(loc, ('?','?'))
return a1==allele and a2==allele
ph = {}
ph['seed_shape'] = 'round' if has_dom('R') else 'wrinkled'
ph['seed_color'] = 'yellow' if has_dom('I') else 'green'
ph['flower_color'] = 'purple' if has_dom('A') else 'white'
ph['plant_height'] = 'tall' if has_dom('Le') else 'dwarf'
ph['pod_color'] = 'green' if has_dom('Gp') else 'yellow'
ph['pod_shape'] = 'constricted' if (is_homo('P','p') or is_homo('V','v')) else 'inflated'
ph['flower_position']= 'axial' if (not is_homo('Fa','fa') or is_homo('Mfa','mfa')) else 'terminal'
return ph
class _Tooltip:
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tip = None
widget.bind("<Enter>", self._show)
widget.bind("<Leave>", self._hide)
widget.bind("<ButtonPress>", self._hide)
def _show(self, event=None):
if self.tip or not self.text:
return
try:
x = self.widget.winfo_rootx() + 12
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
except Exception:
x, y = 0, 0
self.tip = tk.Toplevel(self.widget)
self.tip.wm_overrideredirect(True)
self.tip.wm_geometry(f"+{x}+{y}")
lbl = tk.Label(self.tip, text=self.text, justify="left",
relief="solid", borderwidth=1, font=("Segoe UI", 12), bg="#ffffe0")
lbl.pack(ipadx=4, ipady=2)
def _hide(self, event=None):
try:
if self.tip:
self.tip.destroy()
except Exception:
pass
self.tip = None
def _attach_tooltip(widget, text):
try:
_Tooltip(widget, text)
except Exception:
pass
ROWS = 7
COLS = 16
GRID_SIZE = ROWS * COLS
TILES_PER_ROW = COLS
TILE_SIZE = 85 # change to 64 or 128 later
INNER_ICON = int(TILE_SIZE * 0.8125)
# unified bar thickness (same for water + health)
BAR_THICK = max(4, TILE_SIZE // 8)
# keep water thickness as before
WATER_BAR_W = BAR_THICK
# make health bar slimmer
HEALTH_BAR_H = max(3, TILE_SIZE // 14) # ~6 @85-90, ~4 @64, ~9 @128
# optional: keep if you use it elsewhere
WATER_BAR_H = TILE_SIZE
WATER_BAR_MAX = int(TILE_SIZE * 0.80)
BORDER_THICKNESS = max(2, TILE_SIZE // 21)
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
EXPORT_DIR = os.path.join(ROOT_DIR, "export")
os.makedirs(EXPORT_DIR, exist_ok=True)
SEEDS_CSV = os.path.join(ICONS_DIR, "seeds.csv") # keep next to icons for convenience
TRAITS_CSV = os.path.join(ROOT_DIR, "traits_export.csv") # export of selected plant traits
class GardenApp:
SEASON_MODES = ["off", "overlay", "enforce"]
@staticmethod
def _hex_to_rgb(h):
h = h.lstrip("#")
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
@staticmethod
def _rgb_to_hex(rgb):
r, g, b = rgb
return f"#{r:02x}{g:02x}{b:02x}"
@staticmethod
def _mix(c1, c2, t):
t = max(0.0, min(1.0, float(t)))
r1, g1, b1 = GardenApp._hex_to_rgb(c1)
r2, g2, b2 = GardenApp._hex_to_rgb(c2)
r = int(r1 + (r2 - r1) * t)
g = int(g1 + (g2 - g1) * t)
b = int(b1 + (b2 - b1) * t)
return GardenApp._rgb_to_hex((r, g, b))
@staticmethod
def _darken(c, amount):
return GardenApp._mix(c, "#000000", amount)
# ============================================================================
# Event Handlers
# ============================================================================
def _on_inspect_unified(self):
idx = getattr(self, "selected_index", None)
plant = self.tiles[idx].plant if (idx is not None and 0 <= idx < len(self.tiles)) else None
if not plant:
self._toast("Select a plant first.", level="info")
return
if not getattr(plant, "alive", True):
self._toast("Dead plant.", level="warn")
return
# Keep your original behavior: reveal one trait
try:
plant.reveal_trait()
self._sel_traits_sig = None # force sidebar refresh
except Exception:
pass
# Do the biological anther check (only matters at stage 5)
pollen_ok = self._ensure_anther_check_today(plant) # True/False/None
# Build one concise line
parts = []
stage_name = STAGE_NAMES.get(plant.stage, f"Stage {plant.stage}")
parts.append(f"Stage: {stage_name}")
# actions
try:
ok, _ = plant.can_emasculate()
if ok:
parts.append("Can be emasculated")
except Exception:
pass
if getattr(plant, "stage", 0) >= 5 and not getattr(plant, "pollinated", False):
parts.append("Can be pollinated")
# pollen status (only if flowering)
if pollen_ok is True:
parts.append("Pollen available")
elif pollen_ok is False:
parts.append("No pollen available")
# pods / harvest
if getattr(plant, "stage", 0) >= 6:
pods = int(getattr(plant, "pods_remaining", 0) or 0)
is_emasculated = getattr(plant, "emasculated", False)
if is_emasculated and pods == 0:
# Emasculated plant with no pods - explain why
parts.append("No pods (emasculated, not pollinated)")
elif getattr(plant, "stage", 0) >= 7 and pods > 0:
parts.append(f"Harvestable ({pods})")
elif pods > 0:
parts.append(f"Pods: {pods}")
elif pods == 0:
parts.append("No pods")
if len(parts) == 1:
parts.append("Growing")
# Fully harvested override
if getattr(plant, "fully_harvested", False):
parts = ["Fully harvested — no pods remain"]
# Prepend weak note (short, first in line)
if getattr(plant, "is_weak", False):
parts.insert(0, "Weak plant")
self._toast(" | ".join(parts), level="info")
self.render_all()
try:
self._ensure_auto_loop(delay_ms=50)
except Exception:
pass
# Start the smooth day/night animation loop
try:
self._start_daynight_animation()
except Exception:
pass
def _on_tile_double_click(self, event, index: int):
print("DOUBLE CLICK", index)
self._toast(f"Double-click #{index}", level="info")
# ensure the tile becomes selected (same behavior as click)
try:
self._on_tile_left_release(event, index)
except Exception:
# fallback: at least set selected_index
self.selected_index = index
# open TIE only if there's a plant
plant = self.tiles[index].plant if (0 <= index < len(self.tiles)) else None
if plant is None:
return
self._open_tie_for_selected()
def _test_mendelian_laws_now(self):
"""Open the Mendelian Law Unlock wizard."""
try:
# Ensure archive is current
try:
self._seed_archive_safe()
except Exception:
pass
# Require a selected plant
idx = getattr(self, "selected_index", None)
plant = None
if idx is not None:
try:
if 0 <= idx < len(self.tiles):
plant = self.tiles[idx].plant
except Exception:
pass
if not plant:
self._toast("Select a plant first.", level="info")
return
MendelianLawWizard(self.root, self)
except Exception as e:
try:
self._toast(f"Wizard failed to open: {e}", level="warn")
except Exception:
print("Wizard error:", e)
def _ensure_anther_check_today(self, plant):
"""If plant is flowering (stage 5), ensure today's anther check is computed."""
try:
stage = int(getattr(plant, "stage", 0))
except Exception:
stage = 0
if stage != 5:
return None # not applicable
today = self._today()
# Emasculated flowers have no anthers -> never show pollen availability
if bool(getattr(plant, "emasculated", False)):
plant.last_anther_check_day = today
plant.anthers_available_today = False
plant.anthers_collected_day = None
return False
# Only roll once per day
if getattr(plant, "last_anther_check_day", None) != today:
plant.last_anther_check_day = today
plant.anthers_available_today = (random.random() < 0.5)
plant.anthers_collected_day = None # reset daily collection flag
return bool(getattr(plant, "anthers_available_today", False))
def _compute_light_factor(self, date_obj: dt.date, hour_float: float) -> float:
# Prefer using GardenEnvironment’s sunrise/sunset (Brno+DST), already in garden.py
sr, ss = self.garden._sunrise_sunset_local_hours(date_obj) # :contentReference[oaicite:6]{index=6}
h = hour_float % 24.0
twilight = 0.35
twilight_peak = 0.18
if h < sr - twilight or h > ss + twilight:
return 0.0
if sr - twilight <= h < sr:
t = (h - (sr - twilight)) / twilight
return twilight_peak * t
if ss < h <= ss + twilight:
t = (h - ss) / twilight
return twilight_peak * (1.0 - t)
# daytime dome
mid = (sr + ss) / 2.0
half = max(1e-6, (ss - sr) / 2.0)
x = abs(h - mid) / half
core = max(0.0, 1.0 - x**3.0)
return twilight_peak + (1.0 - twilight_peak) * core
def _toggle_daynight(self):
self.enable_daynight = bool(self.daynight_var.get())
if not self.enable_daynight:
# restore original soil colors immediately
for t in self.tiles:
base = getattr(t, "base_soil", None)
if base:
t.set_soil_color(base)
self.render_all()
# ========================================================================
# Snow Cover Management
# ========================================================================
def _update_snow_covers(self):
"""
Gradually update per-tile snow coverage once per simulated hour.
Design goals
------------
- Accumulation: spreads across tiles over ~3–5 hours (not all at once)
because each tile has only a ~38 % chance of gaining snow per hour.
- Persistence: snow stays until it has been on the ground for at least
48 sim-hours (≈ 2 simulation days) *and* temperature is above 4 °C.
- Fast melt: ignored when temperature exceeds 8 °C.
- Staggered melt: same probabilistic approach, so tiles clear one by one.
- Everything is wrapped in try/except so a bug here never breaks the sim.
"""
try:
# ── Season change: flush photo cache so new season textures bake ──
month = int(getattr(self.garden, 'month', 4))
season = ('spring' if month in (3,4,5) else
'summer' if month in (6,7,8) else
'autumn' if month in (9,10,11) else 'winter')
if season != getattr(self, '_bg_last_season', None):
self._bg_last_season = season
self._bg_current_season = season
# Reset tile keys so they rebake for the new season.
# Do NOT clear _bg_photo_cache — keeping all PhotoImages alive
# prevents tkinter from losing references mid-frame (the flash).
for tile in self.tiles:
tile._bg_cache_key = None
elif not hasattr(self, '_bg_current_season'):
self._bg_current_season = season
# Monotonic sim-hour counter (unique per calendar hour sequence)
sim_hour = getattr(self, '_snow_sim_hour', 0)
self._snow_sim_hour = sim_hour + 1
# Current hourly temperature from today's climate curve
try:
h = int(getattr(self.garden, 'clock_hour', 12)) % 24
hours_data = getattr(self.garden, 'target_temps', {}).get('hours', [])
temp = float(hours_data[h]) if (hours_data and h < len(hours_data)) else 5.0
except Exception:
temp = 5.0
# Is snow currently falling? (garden.weather set by _recompute_weather_for_date)
is_snowing = '❄' in str(getattr(self.garden, 'weather', ''))
ACCUM_MAX_TEMP = 2.5 # °C — snow accumulates at or below this
SLOW_MELT_TEMP = 4.0 # °C — slow melt starts above this (if old enough)
FAST_MELT_TEMP = 8.0 # °C — fast melt, overrides minimum-age check
MIN_SNOW_HOURS = 48 # sim-hours before borderline-warm melt begins
for tile in self.tiles:
try:
cover = getattr(tile, 'snow_cover', 0.0)
snow_since = getattr(tile, '_snow_since_hour', None)
# Per-tile RNG — different outcome each hour
rng = random.Random(tile.idx * 6271 + sim_hour * 7919)
if is_snowing and temp <= ACCUM_MAX_TEMP:
# ── Accumulation phase ──────────────────────────────
# ~38 % chance per hour → most tiles covered in 3-5 h
if rng.random() < 0.38:
cover = min(1.0, cover + tile._snow_rate)
if snow_since is None and cover > 0.05:
tile._snow_since_hour = sim_hour
elif cover > 0.0:
# ── Melt phase ──────────────────────────────────────
snow_age = (sim_hour - snow_since) if snow_since is not None else MIN_SNOW_HOURS
if temp > FAST_MELT_TEMP:
# Hot: fast staggered melt (ignore minimum age)
if rng.random() < 0.55:
rate = tile._snow_melt_rate * (1.0 + (temp - FAST_MELT_TEMP) * 0.08)
cover = max(0.0, cover - rate)
elif temp > SLOW_MELT_TEMP and snow_age >= MIN_SNOW_HOURS:
# Warm enough AND old enough: slow staggered melt
if rng.random() < 0.22:
cover = max(0.0, cover - tile._snow_melt_rate * 0.5)
# Cold, or not old enough → snow stays untouched
if cover <= 0.0:
tile._snow_since_hour = None # reset for next snowfall
tile.set_snow_cover(cover)
except Exception:
pass
# ── Linger expiry: switch tiles from soil back to grass ───────
# When _soil_linger_until expires, the mode should change from
# 'soil' to 'grass'. But if lighting is stable, set_soil_color
# is never called, so the stale _bg_cache_key is never noticed.
# Detect expiry here and force an immediate refresh.
for tile in self.tiles:
try:
linger = tile._soil_linger_until
if 0 < linger <= sim_hour:
tile._soil_linger_until = 0 # reset so we don't re-fire
tile._bg_cache_key = None
tile.set_soil_color(
getattr(tile, '_last_applied_hex', tile.soil))
except Exception:
pass
except Exception:
pass
# ========================================================================
# Background Textures (grass / soil)
# ========================================================================
def _load_bg_textures(self):
"""
Pre-bake day/night-tinted PIL Images for all grass and soil variants.
File discovery
──────────────
Soil: icons/textures/soil1.png … icons/textures/soil9.png (whichever exist)
Grass: icons/textures/grass1.png … icons/textures/grass9.png (base / fallback)
Seasonal overrides (fall back to base variant if missing):
icons/textures/grass_spring1.png … icons/textures/grass_spring9.png
icons/textures/grass_summer1.png … icons/textures/grass_summer9.png
icons/textures/grass_autumn1.png … icons/textures/grass_autumn9.png
icons/textures/grass_winter1.png … icons/textures/grass_winter9.png
PIL image dict key
──────────────────
('soil', variant_idx, bucket) — 0-based variant, bucket 0..100
('grass', season, variant_idx, bucket) — season: 'spring'/'summer'/…
('snow', snow_bkt) — shared overlay
PhotoImages are created lazily by tile._try_set_bg_image().
The photo cache is cleared when the in-game season changes so only the
current season's images stay alive; old ones are garbage collected.
Stores on self
──────────────
_bg_pil_images — the dict above
_bg_photo_cache — lazy PhotoImage cache
_bg_grass_variants — number of grass base variants loaded (int)
_bg_soil_variants — number of soil variants loaded (int)
"""
try:
from PIL import Image
except ImportError:
self._bg_pil_images = {}
self._bg_photo_cache = {}
self._bg_grass_variants = 0
self._bg_soil_variants = 0
return
try:
TS = TILE_SIZE
N = 101 # buckets 0..100
DIR = 'icons/textures'
SEASONS = ('spring', 'summer', 'autumn', 'winter')
resample = (Image.Resampling.LANCZOS
if hasattr(Image, 'Resampling') else Image.LANCZOS)
self._bg_pil_images = {}
self._bg_photo_cache = {}
# ── Helper: load + resize one PNG ────────────────────────────
def _load(path):
return (Image.open(path).convert('RGBA')
.resize((TS, TS), resample))
# ── Sun-tint (must match day/night knobs exactly) ─────────────
sun_r, sun_g, sun_b = 0xbf, 0xe3, 0xb0 # "#bfe3b0"
def _bake(src_rgba, bkt):
"""Return one day/night-tinted copy of *src_rgba* at *bkt*."""
L = bkt / 100.0
night_dark = 0.35 * (1.0 - L)
day_bright = 0.08 * L
factor = (1.0 - night_dark) * (1.0 - day_bright)
lut_r = bytes(min(255, int(x * factor + sun_r * day_bright))
for x in range(256))
lut_g = bytes(min(255, int(x * factor + sun_g * day_bright))
for x in range(256))
lut_b = bytes(min(255, int(x * factor + sun_b * day_bright))
for x in range(256))
r, g, b, a = src_rgba.split()
return Image.merge('RGBA', (r.point(lut_r),
g.point(lut_g),
b.point(lut_b), a))
# ── Load soil numbered fallbacks (soil1.png … soil9.png) ──────
soil_numbered = {}
for i in range(1, 10):
try:
soil_numbered[i - 1] = _load(f"{DIR}/soil{i}.png")
except Exception:
pass
# ── Load seasonal soil and grass ──────────────────────────────
# For each mode, scan how many files exist per season (1-9).
# _bg_*_variants is set to the MIN count across seasons that have
# at least one file — so every tile vi is valid for every season,
# with no gap-fill, no modulo trick, and no fallback search needed.
def _load_mode(mode, seasonal_fmt, numbered_fallbacks, plain_fallback):
"""
Load all seasonal variants for one mode ('grass' or 'soil').
Returns (per_season_counts, safe_variant_count).
per_season_counts: {season: int} — actual files loaded per season
safe_variant_count: int — min across populated seasons
"""
per_season = {} # season -> count of loaded variants
for season in SEASONS:
count = 0
for i in range(1, 10):
vi = i - 1
# Try both naming conventions, then numbered fallback, then plain:
# {mode}_{season}{i}.png e.g. soil_spring1.png
# {mode}{i}_{season}.png e.g. soil1_spring.png
src = None
candidates = [
seasonal_fmt.format(season=season, i=i),
seasonal_fmt.format(season=season, i=i)
.replace(f'_{season}{i}', f'{i}_{season}'),
]
for path in candidates:
try:
src = _load(path)
break
except Exception:
pass
if src is None:
src = (numbered_fallbacks.get(vi)
if numbered_fallbacks else None) or plain_fallback
if src is None:
continue
count += 1
for bkt in range(N):
self._bg_pil_images[(mode, season, vi, bkt)] = _bake(src, bkt)
per_season[season] = count
populated = [c for c in per_season.values() if c > 0]
safe = min(populated) if populated else 0
return per_season, safe
# Soil: soil_{season}{i}.png → soil{i}.png → soil.png
soil_numbered = {}
for i in range(1, 10):
try:
soil_numbered[i - 1] = _load(f"{DIR}/soil{i}.png")
except Exception:
pass
try:
soil_plain = _load(f"{DIR}/soil.png")
except Exception:
soil_plain = None
soil_counts, safe_soil = _load_mode(
'soil',
f"{DIR}/soil_{{season}}{{i}}.png",
soil_numbered, soil_plain)
self._bg_soil_variants = safe_soil
self._bg_soil_counts = soil_counts
# Grass: grass_{season}{i}.png → grass.png
try:
grass_plain = _load(f"{DIR}/grass.png")
except Exception:
grass_plain = None
grass_counts, safe_grass = _load_mode(
'grass',
f"{DIR}/grass_{{season}}{{i}}.png",
{}, grass_plain)
self._bg_grass_variants = safe_grass
self._bg_grass_counts = grass_counts
# Snow is handled in _try_set_bg_image by blending the current
# season's texture toward the winter texture using snow_cover as
# the blend factor. No pre-baked overlays needed here.
except Exception:
self._bg_pil_images = {}