text-adventure-template / spatial_memory.py
OctaveLeroy's picture
Upload 9 files
1f5351c verified
"""
spatial_memory.py
Analyseur de mouvements et générateur de contexte spatial.
"""
from map_graph import MapGraph
import os
class SpatialMemorySystem:
def __init__(self, map_file="zork_map_data.json"):
self.graph = MapGraph()
self.map_file = map_file
self.last_id = None
self.last_action = None
self.load()
def update(self, current_id: int, current_name: str, last_action: str):
"""
C'est le COEUR du système. Analyse le changement d'état.
"""
# 1. Enregistrer la salle actuelle
self.graph.add_or_update_room(current_id, current_name)
# 2. Analyse du mouvement
if self.last_id is not None and last_action:
# Nettoyage de l'action (garder juste la direction)
direction = self._extract_direction(last_action)
if direction:
if current_id != self.last_id:
# SUCCÈS : On a bougé -> Créer connexion
self.graph.add_connection(self.last_id, current_id, direction)
else:
# ÉCHEC : On est resté sur place -> C'est un mur
self.graph.record_failure(self.last_id, direction)
# 3. Sauvegarde automatique
self.save()
# Mise à jour de l'état mémoire
self.last_id = current_id
self.last_action = last_action
def get_context_for_llm(self, current_id: int) -> str:
"""Génère le texte 'Spatial Intelligence' pour le prompt."""
if current_id not in self.graph.rooms:
return "Spatial Info: analyzing..."
room = self.graph.rooms[current_id]
# Exits Vérifiées (Sûres à 100%)
verified = [f"{d}->{self.graph.rooms[c.to_id].name}"
for d, c in room.exits.items() if c.is_verified]
# Exits Inférées (Probables, à tester)
inferred = [f"{d}?" for d, c in room.exits.items() if not c.is_verified]
# Murs (À ne pas réessayer)
blocked = [d for d, count in room.failed_exits.items() if count >= 1]
# Directions inexplorées (Pour l'exploration)
cardinals = {"north", "south", "east", "west", "up", "down", "ne", "nw", "se", "sw"}
known = set(room.exits.keys()) | set(room.failed_exits.keys())
unexplored = list(cardinals - known)
return f"""
*** SPATIAL INTELLIGENCE (Room ID: {current_id}) ***
📍 CURRENT LOCATION: {room.name} (Visited {room.visited_count} times)
✅ VERIFIED PATHS: {', '.join(verified) if verified else 'None'}
🤔 POSSIBLE PATHS (Unverified): {', '.join(inferred) if inferred else 'None'}
⛔ BLOCKED / DEAD ENDS: {', '.join(blocked) if blocked else 'None'}
🔍 UNEXPLORED DIRECTIONS: {', '.join(unexplored)}
"""
def _extract_direction(self, action: str) -> str:
"""Extrait 'north' de 'go north'."""
valid_dirs = ["north", "south", "east", "west", "up", "down",
"ne", "nw", "se", "sw", "enter", "exit", "n", "s", "e", "w"]
tokens = action.lower().split()
for t in tokens:
if t in valid_dirs:
return t
return None
def save(self):
self.graph.save(self.map_file)
def load(self):
self.graph.load(self.map_file)