-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1741 lines (1524 loc) · 69.4 KB
/
Copy pathmain.py
File metadata and controls
1741 lines (1524 loc) · 69.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
from __future__ import annotations
import asyncio
import json
import math
import os
import re
import signal
import sys
import threading
import time
import traceback
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Tuple
try:
from blessed import Terminal
except ModuleNotFoundError:
if os.environ.get("TERMINALMC_LANG", "en").lower() == "it":
print("ERRORE: dipendenza mancante: blessed")
print("Installa le dipendenze con:")
print(" python -m pip install -r requirements.txt")
print("oppure:")
print(" python -m pip install blessed")
prompt = "Premi INVIO per chiudere..."
else:
print("ERROR: missing dependency: blessed")
print("Install dependencies with:")
print(" python -m pip install -r requirements.txt")
print("or:")
print(" python -m pip install blessed")
prompt = "Press ENTER to close..."
try:
input(prompt)
except EOFError:
pass
raise SystemExit(1)
try:
from pynput import mouse as pynput_mouse
except Exception:
pynput_mouse = None
Vec3 = Tuple[float, float, float]
IVec3 = Tuple[int, int, int]
RGB = Tuple[int, int, int]
SCRIPT_FILE = os.path.abspath(__file__)
SCRIPT_DIR = os.path.dirname(SCRIPT_FILE)
APP_DIR = os.path.dirname(SCRIPT_DIR) if os.path.basename(SCRIPT_DIR).lower() == "scripts" else SCRIPT_DIR
SCRIPTS_DIR = os.path.join(APP_DIR, "scripts")
DEPS_DIR = os.path.join(APP_DIR, "deps")
DOCS_DIR = os.path.join(APP_DIR, "docs")
LOG_DIR = os.path.join(APP_DIR, "log")
WORLDS_DIR = os.path.join(APP_DIR, "worlds")
VERSION_FILE = os.path.join(SCRIPTS_DIR, "version")
WORLD_FILE_CACHE: Dict[str, str] = {}
AUTHOR_NAME = "PiBOH"
def ensure_log_dir() -> None:
os.makedirs(os.environ.get("TERMINALMC_LOG_DIR", LOG_DIR), exist_ok=True)
def current_log_stamp() -> str:
stamp = os.environ.get("TERMINALMC_LOG_STAMP", "").strip()
if stamp:
return stamp
return time.strftime("%Y%m%d_%H%M%S")
def log_dir() -> str:
return os.environ.get("TERMINALMC_LOG_DIR", LOG_DIR)
class ActionLogger:
def __init__(self) -> None:
ensure_log_dir()
configured = os.environ.get("TERMINALMC_ACTION_LOG", "").strip()
self.path = configured if configured else os.path.join(log_dir(), f"actions_{current_log_stamp()}.log")
def write(self, source: str, message: str) -> None:
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
try:
with open(self.path, "a", encoding="utf-8") as action_file:
action_file.write(f"[{timestamp}] [{source}] {message}\n")
except OSError:
pass
ACTION_LOGGER = ActionLogger()
def log_action(source: str, message: str) -> None:
ACTION_LOGGER.write(source, message)
def read_game_version() -> str:
try:
with open(VERSION_FILE, "r", encoding="utf-8") as version_file:
value = version_file.read().strip()
return value if value else "0.1.6-alpha"
except OSError:
return "0.1.6-alpha"
GAME_VERSION = read_game_version()
PROJECT_LINKS = [
"Author website: https://piboh.github.io/",
"Repository locale: ./",
"Terminale consigliato: https://alacritty.org",
"Libreria blessed: https://pypi.org/project/blessed/",
]
class BlockKind(Enum):
GRASS = "Erba"
DIRT = "Terra"
STONE = "Pietra"
WOOD = "Legno"
LEAVES = "Foglie"
@dataclass(frozen=True)
class Block:
kind: BlockKind
color: RGB
@dataclass(frozen=True)
class RayHit:
position: IVec3
previous_position: IVec3
block: Block
distance: float
normal: IVec3
@dataclass
class Player:
x: float
y: float
z: float
yaw: float
pitch: float
velocity_y: float
grounded: bool
@dataclass(frozen=True)
class Config:
target_fps: int = 60
world_radius: int = 52
max_world_height: int = 28
min_world_height: int = 2
render_distance: float = 36.0
interaction_distance: float = 6.0
fov_degrees: float = 72.0
turn_speed: float = 2.6
pitch_speed: float = 2.1
move_speed: float = 7.0
jump_speed: float = 7.2
gravity: float = 18.0
# Il giocatore è alto esattamente 2 blocchi; l'occhio resta poco sotto la testa.
eye_height: float = 1.62
player_height: float = 2.0
player_radius: float = 0.25
input_hold_seconds: float = 0.115
class Palette:
GRASS: RGB = (75, 185, 65)
DIRT: RGB = (132, 88, 48)
STONE: RGB = (130, 132, 136)
WOOD: RGB = (88, 56, 28)
LEAVES: RGB = (35, 120, 48)
SKY_TOP: RGB = (78, 142, 220)
SKY_BOTTOM: RGB = (170, 210, 255)
VOID: RGB = (10, 12, 18)
HUD: RGB = (235, 238, 245)
HUD_ACCENT: RGB = (255, 220, 90)
CROSSHAIR: RGB = (255, 255, 255)
BLOCKS: Dict[BlockKind, Block] = {
BlockKind.GRASS: Block(BlockKind.GRASS, Palette.GRASS),
BlockKind.DIRT: Block(BlockKind.DIRT, Palette.DIRT),
BlockKind.STONE: Block(BlockKind.STONE, Palette.STONE),
BlockKind.WOOD: Block(BlockKind.WOOD, Palette.WOOD),
BlockKind.LEAVES: Block(BlockKind.LEAVES, Palette.LEAVES),
}
HOTBAR: List[BlockKind] = [
BlockKind.GRASS,
BlockKind.DIRT,
BlockKind.STONE,
BlockKind.WOOD,
BlockKind.LEAVES,
]
LANGUAGE = "en"
L10N: Dict[str, Dict[str, str]] = {
"en": {
"new_world": "Create new world",
"load_world": "Load world",
"info_links": "Info, author and links",
"language": "Language: English",
"exit": "Exit",
"menu_subtitle": "",
"author": "Author",
"menu_help": "Menu: Arrows/W/S select, ENTER/Space confirm, mouse click supported, ESC exits",
"save_hint": "Select an option",
"saves_log": "",
"enter_world_name": "Enter world name",
"confirm": "ENTER confirms | ESC cancels",
"no_worlds": "No saved worlds found. Create a new world first.",
"choose_world": "Choose a world to load",
"back": "Back",
"info_title": "TerminalMC - Info, author and links",
"version": "Version",
"progress_path": "Progress: automatically saved in ./worlds/<world_name>.json",
"manual_save": "Manual in-game save: P or F5",
"links": "Links",
"saved_worlds": "Saved worlds",
"none": "None",
"press_key": "Press any key to return to the menu",
"block": "Block",
"controls": "WASD move | Arrows/mouse view | Space jump | E/LeftClick mine | Q/RightClick build | P/F5 save | O autosave | ESC pause",
"grass": "Grass",
"dirt": "Dirt",
"stone": "Stone",
"wood": "Wood",
"leaves": "Leaves",
"saved_in": "Progress saved in: ",
"world": "World",
"save": "Save",
"saving": "Saving in progress...",
"saved": "Saved",
"world_border": "You reached the end of the world",
"autosave_option": "Autosave interval",
"autosave_disabled": "Autosave: disabled",
"autosave_10": "Autosave: every 10 min",
"autosave_20": "Autosave: every 20 min",
"autosave_30": "Autosave: every 30 min",
"autosave_done": "Autosave completed",
"pause_title": "Paused",
"continue_game": "Continue game",
"save_and_exit": "Save and exit",
"exit_game": "Exit without saving",
"pause_help": "Arrows/W/S select | ENTER/Space confirm | ESC continue",
},
"it": {
"new_world": "Crea nuovo mondo",
"load_world": "Carica mondo",
"info_links": "Info, autore e collegamenti",
"language": "Lingua: Italiano",
"exit": "Esci",
"menu_subtitle": "",
"author": "Autore",
"menu_help": "Menu: Frecce/W/S selezione, INVIO/Spazio conferma, click mouse supportato, ESC esce",
"save_hint": "Seleziona un'opzione",
"saves_log": "",
"enter_world_name": "Inserisci il nome del mondo",
"confirm": "INVIO conferma | ESC annulla",
"no_worlds": "Nessun mondo salvato trovato. Crea prima un nuovo mondo.",
"choose_world": "Scegli un mondo da caricare",
"back": "Indietro",
"info_title": "TerminalMC - Info, autore e collegamenti",
"version": "Versione",
"progress_path": "Progressi: salvati automaticamente in ./worlds/<nome_mondo>.json",
"manual_save": "Salvataggio manuale in gioco: P oppure F5",
"links": "Collegamenti",
"saved_worlds": "Mondi salvati",
"none": "Nessuno",
"press_key": "Premi un tasto per tornare al menu",
"block": "Blocco",
"controls": "WASD movimento | Frecce/mouse visuale | Spazio salto | E/ClickSx mina | Q/ClickDx piazza | P/F5 salva | O autosave | ESC pausa",
"grass": "Erba",
"dirt": "Terra",
"stone": "Pietra",
"wood": "Legno",
"leaves": "Foglie",
"saved_in": "Progressi salvati in: ",
"world": "Mondo",
"save": "Salvataggio",
"saving": "Salvataggio in corso...",
"saved": "Salvato",
"world_border": "Hai raggiunto la fine del mondo",
"autosave_option": "Intervallo salvataggio automatico",
"autosave_disabled": "Salvataggio automatico: disattivato",
"autosave_10": "Salvataggio automatico: ogni 10 min",
"autosave_20": "Salvataggio automatico: ogni 20 min",
"autosave_30": "Salvataggio automatico: ogni 30 min",
"autosave_done": "Salvataggio automatico completato",
"pause_title": "Pausa",
"continue_game": "Continua il gioco",
"save_and_exit": "Salva ed esci",
"exit_game": "Esci senza salvare",
"pause_help": "Frecce/W/S selezione | INVIO/Spazio conferma | ESC continua",
},
}
BLOCK_LABEL_KEYS: Dict[BlockKind, str] = {
BlockKind.GRASS: "grass",
BlockKind.DIRT: "dirt",
BlockKind.STONE: "stone",
BlockKind.WOOD: "wood",
BlockKind.LEAVES: "leaves",
}
def tr(key: str) -> str:
return L10N.get(LANGUAGE, L10N["en"]).get(key, key)
def block_label(kind: BlockKind) -> str:
return tr(BLOCK_LABEL_KEYS[kind])
def autosave_label(minutes: Optional[int]) -> str:
if minutes == 10:
return tr("autosave_10")
if minutes == 20:
return tr("autosave_20")
if minutes == 30:
return tr("autosave_30")
return tr("autosave_disabled")
def clamp(value: float, low: float, high: float) -> float:
return max(low, min(high, value))
def lerp(a: int, b: int, t: float) -> int:
return int(a + (b - a) * t)
def rgb_lerp(a: RGB, b: RGB, t: float) -> RGB:
t = clamp(t, 0.0, 1.0)
return (lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t))
def shade_color(color: RGB, factor: float) -> RGB:
factor = clamp(factor, 0.0, 1.4)
return (
int(clamp(color[0] * factor, 0, 255)),
int(clamp(color[1] * factor, 0, 255)),
int(clamp(color[2] * factor, 0, 255)),
)
def fg_rgb(color: RGB) -> str:
return f"\x1b[38;2;{color[0]};{color[1]};{color[2]}m"
def bg_rgb(color: RGB) -> str:
return f"\x1b[48;2;{color[0]};{color[1]};{color[2]}m"
def ansi_reset() -> str:
return "\x1b[0m"
@dataclass(frozen=True)
class MouseEvent:
button: int
x: int
y: int
pressed: bool
motion: bool
def parse_sgr_mouse(sequence: str) -> Optional[MouseEvent]:
# Decodifica eventi mouse SGR: ESC [ < button ; x ; y M/m.
match = re.search(r"\x1b\[<(\d+);(\d+);(\d+)([Mm])", sequence)
if match is None:
return None
button = int(match.group(1))
x = int(match.group(2))
y = int(match.group(3))
pressed = match.group(4) == "M"
motion = (button & 32) == 32
base_button = button & 3
return MouseEvent(button=base_button, x=x, y=y, pressed=pressed, motion=motion)
def enable_mouse_reporting() -> str:
# 1000: click, 1002: drag con pulsante premuto, 1006: coordinate SGR estese.
# Nota: 1003 any-motion resta disabilitato perché su Windows/Alacritty può saturare la TUI.
return "\x1b[?1000h\x1b[?1002h\x1b[?1006h"
def disable_mouse_reporting() -> str:
return "\x1b[?1006l\x1b[?1002l\x1b[?1000l"
def collect_escape_sequence(term: Terminal, first_key: object, max_wait_seconds: float = 0.035) -> str:
# Blessed può restituire ESC separato dal resto della sequenza mouse.
# Senza questo accumulo, un click mouse può sembrare un ESC e chiudere il gioco/menu.
sequence = str(first_key)
if not sequence.startswith("\x1b"):
return sequence
deadline = time.perf_counter() + max_wait_seconds
while time.perf_counter() < deadline:
next_key = term.inkey(timeout=0.002)
if not next_key:
break
sequence += str(next_key)
# Mouse SGR completo: ESC [ < b ; x ; y M/m.
if parse_sgr_mouse(sequence) is not None:
break
# Sequenza tastiera ANSI generica completa.
if re.search(r"\x1b\[[0-9;?]*[A-Za-z~]$", sequence):
break
return sequence
class NativeMouseBridge:
def __init__(self) -> None:
self.available = pynput_mouse is not None
self.listener: Any = None
self.lock = threading.Lock()
self.last_x: Optional[int] = None
self.last_y: Optional[int] = None
self.delta_x = 0.0
self.delta_y = 0.0
self.left_clicks = 0
self.right_clicks = 0
def start(self) -> None:
# Fallback mouse nativo: utile su Windows/Alacritty quando ConPTY non inoltra mouse SGR.
if not self.available or self.listener is not None:
return
try:
self.listener = pynput_mouse.Listener(on_move=self.on_move, on_click=self.on_click)
self.listener.start()
except Exception:
self.available = False
self.listener = None
def stop(self) -> None:
if self.listener is not None:
try:
self.listener.stop()
except Exception:
pass
self.listener = None
def on_move(self, x: int, y: int) -> None:
# Accumulo movimento nativo con clamp: evita flood ma rende il mouse utilizzabile.
with self.lock:
if self.last_x is not None and self.last_y is not None:
self.delta_x = clamp(self.delta_x + float(x - self.last_x), -120.0, 120.0)
self.delta_y = clamp(self.delta_y + float(y - self.last_y), -120.0, 120.0)
self.last_x = x
self.last_y = y
def on_click(self, _x: int, _y: int, button: object, pressed: bool) -> None:
if not pressed or pynput_mouse is None:
return
with self.lock:
if button == pynput_mouse.Button.left:
self.left_clicks += 1
elif button == pynput_mouse.Button.right:
self.right_clicks += 1
def consume(self) -> Tuple[float, float, int, int]:
with self.lock:
dx = self.delta_x
dy = self.delta_y
left = self.left_clicks
right = self.right_clicks
self.delta_x = 0.0
self.delta_y = 0.0
self.left_clicks = 0
self.right_clicks = 0
return dx, dy, left, right
class VoxelWorld:
def __init__(self, config: Config, generate: bool = True) -> None:
self.config = config
self.blocks: Dict[IVec3, Block] = {}
if generate:
self.generate()
def generate(self) -> None:
radius = self.config.world_radius
for x in range(-radius, radius + 1):
for z in range(-radius, radius + 1):
height = self.terrain_height(x, z)
for y in range(0, height + 1):
if y == height:
block = BLOCKS[BlockKind.GRASS]
elif y >= height - 3:
block = BLOCKS[BlockKind.DIRT]
else:
block = BLOCKS[BlockKind.STONE]
self.blocks[(x, y, z)] = block
if self.should_place_tree(x, z, height):
self.place_tree(x, height + 1, z)
def terrain_height(self, x: int, z: int) -> int:
# Rumore procedurale deterministico tramite sinusoidi stratificate.
n1 = math.sin(x * 0.135 + z * 0.071) * 3.2
n2 = math.sin((x + z) * 0.055) * 4.0
n3 = math.cos(math.sqrt(float(x * x + z * z)) * 0.155) * 2.3
n4 = math.sin(x * 0.031) * math.cos(z * 0.047) * 5.2
radial = -0.018 * math.sqrt(float(x * x + z * z))
raw = 8.0 + n1 + n2 + n3 + n4 + radial
return int(clamp(round(raw), self.config.min_world_height, self.config.max_world_height))
def should_place_tree(self, x: int, z: int, height: int) -> bool:
if abs(x) < 3 and abs(z) < 3 or height < 5:
return False
value = (x * 734287 + z * 912271 + x * z * 1013) & 0xFFFFFFFF
return value % 97 == 0
def place_tree(self, x: int, y: int, z: int) -> None:
trunk_height = 4 + abs((x * 17 + z * 31) % 3)
for dy in range(trunk_height):
self.blocks[(x, y + dy, z)] = BLOCKS[BlockKind.WOOD]
leaf_center_y = y + trunk_height
for lx in range(-2, 3):
for ly in range(-2, 3):
for lz in range(-2, 3):
if abs(lx) + abs(ly) + abs(lz) <= 4 and not (lx == 0 and lz == 0 and ly < 0):
pos = (x + lx, leaf_center_y + ly, z + lz)
if pos not in self.blocks:
self.blocks[pos] = BLOCKS[BlockKind.LEAVES]
def get_block(self, position: IVec3) -> Optional[Block]:
return self.blocks.get(position)
def set_block(self, position: IVec3, block_kind: BlockKind) -> None:
self.blocks[position] = BLOCKS[block_kind]
def remove_block(self, position: IVec3) -> None:
self.blocks.pop(position, None)
def is_solid(self, position: IVec3) -> bool:
return position in self.blocks
def highest_solid_y(self, x: int, z: int) -> Optional[int]:
highest: Optional[int] = None
for bx, by, bz in self.blocks.keys():
if bx == x and bz == z and (highest is None or by > highest):
highest = by
return highest
def to_save_data(self) -> List[List[Any]]:
# Serializza i blocchi in una forma JSON semplice e portabile.
return [[x, y, z, block.kind.name] for (x, y, z), block in self.blocks.items()]
@classmethod
def from_save_data(cls, config: Config, block_data: List[List[Any]]) -> "VoxelWorld":
# Ricostruisce il mondo senza rigenerarlo proceduralmente.
world = cls(config, generate=False)
for item in block_data:
if len(item) != 4:
continue
x = int(item[0])
y = int(item[1])
z = int(item[2])
kind_name = str(item[3])
if kind_name in BlockKind.__members__:
world.blocks[(x, y, z)] = BLOCKS[BlockKind[kind_name]]
return world
def ensure_worlds_dir() -> None:
os.makedirs(WORLDS_DIR, exist_ok=True)
def candidate_world_dirs() -> List[str]:
# Directory corrente ufficiale + vecchie posizioni usate durante le riorganizzazioni.
dirs = [
WORLDS_DIR,
os.path.join(SCRIPTS_DIR, "worlds"),
os.path.join(os.getcwd(), "worlds"),
]
unique: List[str] = []
for directory in dirs:
normalized = os.path.abspath(directory)
if normalized not in unique:
unique.append(normalized)
return unique
def sanitize_world_name(world_name: str) -> str:
safe_name = "".join(ch if ch.isalnum() or ch in {"_", "-"} else "_" for ch in world_name).strip("_")
return safe_name[:48]
def world_path(world_name: str) -> str:
safe_name = sanitize_world_name(world_name)
if not safe_name:
safe_name = "world" if LANGUAGE == "en" else "mondo"
ensure_worlds_dir()
return os.path.join(WORLDS_DIR, f"{safe_name}.json")
def existing_world_path(world_name: str) -> Optional[str]:
cached = WORLD_FILE_CACHE.get(world_name)
if cached and os.path.exists(cached):
return cached
safe_name = sanitize_world_name(world_name)
for directory in candidate_world_dirs():
candidate = os.path.join(directory, f"{safe_name}.json")
if os.path.exists(candidate):
WORLD_FILE_CACHE[world_name] = candidate
return candidate
return None
def list_saved_worlds() -> List[str]:
ensure_worlds_dir()
WORLD_FILE_CACHE.clear()
discovered: Dict[str, str] = {}
for directory in candidate_world_dirs():
if not os.path.isdir(directory):
continue
for filename in os.listdir(directory):
if not filename.lower().endswith(".json"):
continue
full_path = os.path.join(directory, filename)
if not os.path.isfile(full_path):
continue
name = filename[:-5]
previous = discovered.get(name)
if previous is None or os.path.getmtime(full_path) > os.path.getmtime(previous):
discovered[name] = full_path
for name, path in discovered.items():
WORLD_FILE_CACHE[name] = path
worlds = list(discovered.keys())
worlds.sort(key=lambda name: os.path.getmtime(discovered[name]), reverse=True)
log_action("worlds", f"list_saved_worlds found={len(worlds)} dirs={candidate_world_dirs()} names={worlds}")
return worlds
def default_world_name() -> str:
prefix = "world" if LANGUAGE == "en" else "mondo"
return prefix + "_" + time.strftime("%Y%m%d_%H%M%S")
class InputState:
def __init__(self, config: Config) -> None:
self.config = config
self.active_until: Dict[str, float] = {}
self.just_pressed: Set[str] = set()
def begin_frame(self) -> None:
self.just_pressed.clear()
def press(self, action: str, now: float) -> None:
self.active_until[action] = now + self.config.input_hold_seconds
self.just_pressed.add(action)
def is_active(self, action: str, now: float) -> bool:
return self.active_until.get(action, 0.0) >= now
def consume_just_pressed(self, action: str) -> bool:
return action in self.just_pressed
class Raycaster:
def __init__(self, world: VoxelWorld, config: Config) -> None:
self.world = world
self.config = config
def camera_forward(self, yaw: float, pitch: float) -> Vec3:
cp = math.cos(pitch)
return (math.sin(yaw) * cp, math.sin(pitch), math.cos(yaw) * cp)
def normalize(self, vector: Vec3) -> Vec3:
x, y, z = vector
length = math.sqrt(x * x + y * y + z * z)
if length <= 0.000001:
return (0.0, 0.0, 1.0)
return (x / length, y / length, z / length)
def basis(self, yaw: float, pitch: float) -> Tuple[Vec3, Vec3, Vec3]:
forward = self.camera_forward(yaw, pitch)
right = (math.cos(yaw), 0.0, -math.sin(yaw))
fx, fy, fz = forward
rx, ry, rz = right
# Vettore alto della camera.
# Nota importante: usare forward x right, non right x forward.
# Con yaw=0 e pitch=0 vogliamo up=(0, 1, 0); invertire l'ordine
# produce up=(0, -1, 0) e rende il mondo visivamente sottosopra.
up = (fy * rz - fz * ry, fz * rx - fx * rz, fx * ry - fy * rx)
return self.normalize(forward), self.normalize(right), self.normalize(up)
def screen_ray(self, player: Player, column: int, row: int, width: int, height: int) -> Vec3:
forward, right, up = self.basis(player.yaw, player.pitch)
fov = math.radians(self.config.fov_degrees)
aspect = max(0.1, width / max(1.0, height * 2.0))
sx = ((column + 0.5) / max(1, width) * 2.0 - 1.0) * math.tan(fov / 2.0) * aspect
sy = (1.0 - (row + 0.5) / max(1, height) * 2.0) * math.tan(fov / 2.0)
dx = forward[0] + right[0] * sx + up[0] * sy
dy = forward[1] + right[1] * sx + up[1] * sy
dz = forward[2] + right[2] * sx + up[2] * sy
return self.normalize((dx, dy, dz))
def cast(self, origin: Vec3, direction: Vec3, max_distance: float) -> Optional[RayHit]:
ox, oy, oz = origin
dx, dy, dz = direction
x = math.floor(ox)
y = math.floor(oy)
z = math.floor(oz)
step_x = 1 if dx > 0.0 else -1
step_y = 1 if dy > 0.0 else -1
step_z = 1 if dz > 0.0 else -1
inv_dx = 1.0 / abs(dx) if abs(dx) > 0.000001 else float("inf")
inv_dy = 1.0 / abs(dy) if abs(dy) > 0.000001 else float("inf")
inv_dz = 1.0 / abs(dz) if abs(dz) > 0.000001 else float("inf")
t_max_x = ((math.floor(ox) + 1.0 - ox) if dx > 0.0 else (ox - math.floor(ox))) * inv_dx
t_max_y = ((math.floor(oy) + 1.0 - oy) if dy > 0.0 else (oy - math.floor(oy))) * inv_dy
t_max_z = ((math.floor(oz) + 1.0 - oz) if dz > 0.0 else (oz - math.floor(oz))) * inv_dz
t_delta_x = inv_dx
t_delta_y = inv_dy
t_delta_z = inv_dz
distance = 0.0
previous = (x, y, z)
normal: IVec3 = (0, 0, 0)
while distance <= max_distance:
position = (x, y, z)
block = self.world.get_block(position)
if block is not None:
real_distance = math.sqrt((x + 0.5 - ox) ** 2 + (y + 0.5 - oy) ** 2 + (z + 0.5 - oz) ** 2)
return RayHit(position, previous, block, real_distance, normal)
previous = position
if t_max_x < t_max_y and t_max_x < t_max_z:
x += step_x
distance = t_max_x
t_max_x += t_delta_x
normal = (-step_x, 0, 0)
elif t_max_y < t_max_z:
y += step_y
distance = t_max_y
t_max_y += t_delta_y
normal = (0, -step_y, 0)
else:
z += step_z
distance = t_max_z
t_max_z += t_delta_z
normal = (0, 0, -step_z)
return None
class Renderer:
def __init__(self, term: Terminal, raycaster: Raycaster, config: Config) -> None:
self.term = term
self.raycaster = raycaster
self.config = config
def render(self, player: Player, selected: BlockKind, fps: float, status_message: str = "") -> str:
width = max(20, int(self.term.width or 80))
height = max(10, int(self.term.height or 24))
pixel_count = width * height
# Campionamento adattivo: quando lo zoom del terminale è molto basso la griglia diventa enorme.
# Calcoliamo meno raggi e ripetiamo il carattere per mantenere il frame-rate più fluido.
if pixel_count >= 14000:
step_x = 3
elif pixel_count >= 6500:
step_x = 2
else:
step_x = 1
lines: List[str] = []
origin = (player.x, player.y, player.z)
max_distance = self.config.render_distance * (0.85 if step_x > 1 else 1.0)
for row in range(height):
cells: List[str] = []
column = 0
while column < width:
ray = self.raycaster.screen_ray(player, column, row, width, height)
hit = self.raycaster.cast(origin, ray, max_distance)
if hit is None:
color = self.sky_color(row, height, ray)
cell = f"{bg_rgb(color)} "
else:
color = self.hit_color(hit)
cell = f"{fg_rgb(color)}{self.hit_glyph(hit)}"
repeat = min(step_x, width - column)
cells.append(cell * repeat)
column += repeat
lines.append("".join(cells) + ansi_reset())
self.overlay_hud(lines, player, selected, fps, width, height, status_message)
return "\x1b[H" + "\n".join(lines) + ansi_reset()
def sky_color(self, row: int, height: int, ray: Vec3) -> RGB:
t = row / max(1, height - 1)
sky = rgb_lerp(Palette.SKY_TOP, Palette.SKY_BOTTOM, t)
if ray[1] < -0.20:
return rgb_lerp(sky, Palette.VOID, clamp((-ray[1] - 0.20) / 0.8, 0.0, 1.0))
return sky
def hit_color(self, hit: RayHit) -> RGB:
fog = clamp(hit.distance / self.config.render_distance, 0.0, 1.0)
distance_factor = 1.0 - fog * 0.72
nx, ny, nz = hit.normal
# Luce direzionale più ricca per una lettura 3D migliore nel terminale.
sun = self.raycaster.normalize((-0.35, 0.85, -0.40))
lambert = max(0.0, nx * sun[0] + ny * sun[1] + nz * sun[2])
ambient = 0.52
face_boost = 0.22 if ny > 0 else (-0.16 if ny < 0 else 0.0)
light = ambient + lambert * 0.58 + face_boost
color = shade_color(hit.block.color, distance_factor * light)
return rgb_lerp(color, Palette.SKY_TOP, fog * 0.24)
def hit_glyph(self, hit: RayHit) -> str:
# Dithering ASCII/Unicode leggero: aumenta la percezione di dettaglio.
fog = clamp(hit.distance / self.config.render_distance, 0.0, 1.0)
if fog > 0.82:
return "░"
if fog > 0.62:
return "▒"
if fog > 0.38:
return "▓"
return "█"
def overlay_hud(self, lines: List[str], player: Player, selected: BlockKind, fps: float, width: int, height: int, status_message: str = "") -> None:
self.overlay_text(lines, 1, 0, f"TerminalMC FPS:{fps:5.1f} XYZ:{player.x:6.2f},{player.y:5.2f},{player.z:6.2f}", Palette.HUD)
self.overlay_text(lines, 1, 1, f"{tr('block')}: {block_label(selected)} | [1]{tr('grass')} [2]{tr('dirt')} [3]{tr('stone')} [4]{tr('wood')} [5]{tr('leaves')}", Palette.HUD_ACCENT)
self.overlay_text(lines, 1, 2, tr("controls"), Palette.HUD)
if status_message:
self.overlay_text(lines, 1, max(0, height - 2), status_message, Palette.HUD_ACCENT)
self.overlay_text(lines, width // 2, height // 2, "+", Palette.CROSSHAIR)
def overlay_text(self, lines: List[str], x: int, y: int, text: str, color: RGB) -> None:
if y < 0 or y >= len(lines):
return
visible_width = len(strip_ansi(lines[y]))
if x >= visible_width:
return
safe_text = text[: max(0, visible_width - x)]
prefix = take_visible_prefix(lines[y], x)
suffix = take_visible_suffix(lines[y], x + len(safe_text))
lines[y] = f"{prefix}{fg_rgb(color)}{safe_text}{ansi_reset()}{suffix}"
def strip_ansi(text: str) -> str:
result: List[str] = []
i = 0
while i < len(text):
if text[i] == "\x1b":
i += 1
while i < len(text) and text[i] != "m":
i += 1
i += 1
else:
result.append(text[i])
i += 1
return "".join(result)
def take_visible_prefix(text: str, count: int) -> str:
result: List[str] = []
visible = 0
i = 0
while i < len(text) and visible < count:
if text[i] == "\x1b":
start = i
i += 1
while i < len(text) and text[i] != "m":
i += 1
if i < len(text):
i += 1
result.append(text[start:i])
else:
result.append(text[i])
visible += 1
i += 1
return "".join(result)
def take_visible_suffix(text: str, start_visible: int) -> str:
result: List[str] = []
visible = 0
i = 0
copying = False
while i < len(text):
if text[i] == "\x1b":
esc_start = i
i += 1
while i < len(text) and text[i] != "m":
i += 1
if i < len(text):
i += 1
if copying:
result.append(text[esc_start:i])
else:
if visible >= start_visible:
copying = True
result.append(text[i])
visible += 1
i += 1
return "".join(result)
class Game:
def __init__(self, world_name: str, load_existing: bool, language: str, autosave_minutes: Optional[int]) -> None:
global LANGUAGE
LANGUAGE = language
self.config = Config()
self.term = Terminal()
self.world_name = world_name
self.save_path = existing_world_path(world_name) if load_existing else None
if self.save_path is None:
self.save_path = world_path(world_name)
self.autosave_minutes = autosave_minutes
self.last_autosave_time = time.perf_counter()
self.status_flash_until = 0.0
self.selected_index = 0
loaded_player: Optional[Player] = None
if load_existing and os.path.exists(self.save_path):
loaded_player = self.load_game_state()
else:
self.world = VoxelWorld(self.config)
self.raycaster = Raycaster(self.world, self.config)
self.renderer = Renderer(self.term, self.raycaster, self.config)
self.input_state = InputState(self.config)
self.native_mouse = NativeMouseBridge()
self.player = loaded_player if loaded_player is not None else self.create_player()
self.running = True
self.save_on_exit = True
self.fps = 0.0
self.frame_counter = 0
self.fps_accumulator = 0.0
self.last_mouse_x: Optional[int] = None
self.last_mouse_y: Optional[int] = None
self.world_border_last_warning = 0.0
self.status_message = f"{tr('world')}: {self.world_name} | {autosave_label(self.autosave_minutes)}"
log_action("game", f"game started world={self.world_name} autosave={self.autosave_minutes}")
def create_player(self) -> Player:
ground = self.world.highest_solid_y(0, 0)
start_y = float((ground if ground is not None else 8) + 1) + self.config.eye_height
return Player(0.5, start_y, 0.5, 0.0, 0.0, 0.0, True)
def load_game_state(self) -> Optional[Player]:
# Carica mondo, giocatore e hotbar da file JSON.
with open(self.save_path, "r", encoding="utf-8") as save_file:
data = json.load(save_file)
block_data = data.get("blocks", [])
if not isinstance(block_data, list):
block_data = []
self.world = VoxelWorld.from_save_data(self.config, block_data)
selected = data.get("selected_index", 0)
if isinstance(selected, int):
self.selected_index = int(clamp(float(selected), 0.0, float(len(HOTBAR) - 1)))
saved_autosave = data.get("autosave_minutes", self.autosave_minutes)
if saved_autosave in (None, 10, 20, 30):
self.autosave_minutes = saved_autosave
elif isinstance(saved_autosave, int) and saved_autosave in {10, 20, 30}:
self.autosave_minutes = saved_autosave
log_action("game", f"loaded autosave setting: {self.autosave_minutes}")
player_data = data.get("player", {})
if not isinstance(player_data, dict):
return None
return Player(
x=float(player_data.get("x", 0.5)),
y=float(player_data.get("y", 12.0)),
z=float(player_data.get("z", 0.5)),
yaw=float(player_data.get("yaw", 0.0)),
pitch=float(player_data.get("pitch", 0.0)),
velocity_y=0.0,
grounded=bool(player_data.get("grounded", True)),
)
def save_game_state(self) -> None:
# Salva i progressi in ./worlds/<nome_mondo>.json.
self.flash_status(tr("saving"), 1.0)
log_action("game", "save started")
ensure_worlds_dir()
data: Dict[str, Any] = {
"format_version": "1",
"game_version": GAME_VERSION,
"language": LANGUAGE,
"saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),