https://github.com/hectorgimenez/d2go 여기야
- User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
오케이! hectorgimenez/d2go 레포지토리를 살펴봤어. 이건 Diablo II: Resurrected (D2R)의 메모리를 읽기 위한 Go 언어 라이브러리네. 이걸 Python이나 C#에서 활용하는 방안을 생각해보자.
핵심 분석:
d2go는 D2R 게임 클라이언트의 메모리에 직접 접근해서 게임 내의 다양한 정보(플레이어 상태, 아이템, 몬스터, 오브젝트 등)를 읽어오는 기능을 제공해.memory/: 실제 메모리 읽기 로직 (프로세스 핸들링, 바이트 읽기 등)data/: 게임 내 데이터 구조체 정의 (예: Player, Item, Monster). 이 구조체들은 메모리에서 읽어온 바이트를 어떻게 해석할지 정의해.d2r_reader.go (또는 유사한 파일): d2go의 메인 인터페이스. 이 파일을 통해 게임 데이터를 가져오는 함수들이 제공될 거야.d2go는 특정 정보 (예: 플레이어 체력)가 메모리의 어느 위치에 있는지 알아야 해. 이 위치 정보(오프셋)는 게임 버전에 따라 달라질 수 있어. d2go는 이 오프셋을 관리하는 메커니즘을 가지고 있을 거야. (종종 offsets.json 같은 파일로 관리하거나, 코드 내에 하드코딩 또는 포인터 스캔을 통해 동적으로 찾기도 해.)
koolo (이 라이브러리를 사용하는 봇) 프로젝트를 보면 assets/offsets/offsets.json 파일이 있어. 이 파일이 우리가 Python/C#에서 활용할 핵심 정보가 될 거야!Python/C#에서 d2go의 정보를 활용하는 방법:
d2go는 Go 라이브러리이므로 직접 Python/C#에서 호출하기는 어려워. 대신, d2go가 메모리를 읽는 방식과 오프셋 정보를 "번역"해서 Python/C#으로 재구현하는 전략을 사용해야 해.
단계별 접근:
오프셋 정보 확보:
koolo 프로젝트의 assets/offsets/offsets.json 파일을 가져와. 이 JSON 파일에는 "PlayerHP", "PlayerMana" 같은 이름과 해당 정보가 있는 메모리 주소(또는 베이스 주소로부터의 상대 오프셋, 포인터 경로)가 매핑되어 있을 거야.offsets.json 내용 추정):
{
"player": {
"base": ["some_base_pointer_or_pattern", 0xABC], // 포인터 경로
"hp": [0x10, 0x18, 0x24], // base로부터의 포인터 오프셋 체인
"x": [0x30],
"y": [0x34]
},
// ... 기타 정보
}
메모리 읽기 라이브러리 선택:
pymem 라이브러리가 사용하기 좋아.MemorySharp 또는 기본적인 ReadProcessMemory WinAPI 호출을 사용할 수 있어.프로세스 접근 및 기본 주소 획득:
d2go나 koolo가 이를 어떻게 얻는지 확인해야 해 (보통 프로세스 이름으로 모듈을 찾음).오프셋과 포인터 경로 해석:
offsets.json에 정의된 포인터 경로를 따라 메모리를 읽어야 해.BaseAddress + player_base_offset 주소에서 포인터 값을 읽는다.읽은_포인터값 + hp_offset_1 주소에서 다음 포인터 값을 읽는다.데이터 구조체 재현:
d2go/data/ 폴더의 Go 구조체를 참고해서 Python 클래스나 C# 클래스/구조체로 만들어. 메모리에서 읽어온 바이트 덩어리를 이 구조체에 맞게 파싱해야 해.d2go/data/player.go에 type Player struct { Name string; HP uint32; ... } 가 있다면, Python에서도 해당 바이트 순서대로 name 문자열과 hp (unsigned int 32-bit)를 읽도록 파싱 로직을 짜야 해.Python 예시 (개념적인 코드):
import pymem
import pymem.process
import json
import struct
OFFSETS_FILE = "path/to/koolo/assets/offsets/offsets.json" # 실제 경로로 수정
class D2RMemoryReader:
def __init__(self, process_name="D2R.exe"):
self.pm = None
self.base_address = None
self.offsets = {}
try:
self.pm = pymem.Pymem(process_name)
# D2R.exe 모듈을 찾아 베이스 주소 확보 (d2go/koolo 방식 확인 필요)
# 여기서는 간단히 첫 번째 모듈의 베이스 주소를 사용한다고 가정
self.base_address = self.pm.process_base # 실제로는 D2R.exe 모듈을 찾아야 함
# koolo의 로직을 보면 D2R.exe 모듈의 base address를 찾음
for mod in list(self.pm.list_modules()):
if mod.name.lower() == process_name.lower():
self.base_address = mod.lpBaseOfDll
print(f"Found {process_name} at {hex(self.base_address)}")
break
if not self.base_address:
raise Exception(f"{process_name} module not found.")
with open(OFFSETS_FILE, 'r') as f:
self.offsets = json.load(f)
except pymem.exception.ProcessNotFound:
print(f"Process {process_name} not found.")
raise
except FileNotFoundError:
print(f"Offsets file {OFFSETS_FILE} not found.")
raise
def resolve_pointer_chain(self, base, ptr_offsets):
addr = base
try:
for offset in ptr_offsets:
addr = self.pm.read_longlong(addr + offset) # D2R은 64비트이므로 longlong
if addr == 0: # 포인터가 null이면 더 이상 진행 불가
return 0
return addr
except Exception as e:
# print(f"Error resolving pointer chain: {e} at {hex(addr)} with offset {hex(offset if 'offset' in locals() else 0)}")
return 0
def get_player_data(self):
player_offsets_config = self.offsets.get("player")
if not player_offsets_config:
print("Player offsets not found in config.")
return None
# 예시: "base"는 실제 D2R.exe 모듈의 베이스 주소를 의미할 수 있음
# koolo offsets.json의 "player"는 단순 오프셋 배열임.
# "unit": [ 0x1D904A8, 0x0, 0x98 ]
# 이는 [[BaseAddress + 0x1D904A8] + 0x0] + 0x98 로 해석될 수 있음 (HP의 경우)
# PlayerUnit 포인터 주소 계산 (koolo의 offsets.json "unit" 참고)
# 예: PlayerUnitPtrAddr = self.base_address + self.offsets["pointers"]["PlayerUnit"]
# player_unit_ptr_val = self.pm.read_longlong(PlayerUnitPtrAddr)
# koolo의 offsets.json player 키는 이런식임: "name": [104, 0]
# 이건 PlayerUnit 구조체 내에서 Name 필드의 오프셋임.
# 먼저 PlayerUnit의 주소를 알아내야 함.
# offsets.json 의 최상단 키가 Global Pointer를 나타내는 경우가 많음
# "unitTable": [ 0xOFFSET_FROM_BASE, 0xANOTHER_OFFSET_IF_NEEDED ]
# koolo의 `koolo/game_stats/base_stats.go` `CharacterStats.updateUnitPtr`를 보면
# gameReader.GamePointers.UnitTable -> 이 값을 기준으로 플레이어 유닛을 찾음.
# 즉, GamePointers.UnitTable을 먼저 읽어야 함.
# offsets.json에서 "unitTable" 같은 키를 찾아야 함.
ptr_unit_table_config = self.offsets.get("unitTable")
if not ptr_unit_table_config:
print("unitTable offset not found in config.")
return None
# unitTable_address = self.resolve_pointer_chain(self.base_address, ptr_unit_table_config)
# 위 방식은 offsets.json의 구조에 따라 다름.
# koolo의 offsets.json은 최상위 키가 모듈 베이스로부터의 직접적인 포인터 오프셋인 경우가 많음
# 예: "unitTable": 0x1D904A8 -> 실제로는 이게 포인터가 아니라 포인터를 담고있는 주소의 오프셋일 가능성
# d2go/koolo에서는 패턴 스캔이나 정적 오프셋을 사용할 수 있음.
# offsets.json을 보면 최상위 키가 있고, 그 값이 배열이면 포인터 체인으로 해석 가능.
# "playerUnit": "2D D0 ?? ?? ?? ?? ?? 0F B7 ?? 8B" (AOB 패턴일 경우)
# "playerUnit": 0x1CF0F88 (직접 오프셋일 경우) -> base + 0x1CF0F88 에서 플레이어 유닛 포인터를 읽음
# 여기서는 offsets.json의 "playerUnit"이 베이스 주소로부터의 오프셋이라고 가정
player_unit_ptr_offset = self.offsets.get("playerUnit") # 가상의 키
if player_unit_ptr_offset is None:
# koolo의 offsets.json에는 "playerUnit"이라는 직접적인 키는 없고,
# "unitTable"에서 특정 인덱스(0번째)로 플레이어를 식별하는 방식일 수 있음.
# d2go/memory/player.go -> PlayerData() 함수를 봐야 정확함.
# `func (gd *GameReader) PlayerData(hovered bool) data.PlayerData`
# `playerUnitAddress := gd.Process.moduleBaseAddressPtr + gd.offset.PlayerUnit`
# `playerPtr := gd.Process.ReadUInt(playerUnitAddress)`
# -> offsets.json 에서 "PlayerUnit" 키를 사용하고 있음!
# Koolo의 offsets.json에는 "PlayerUnit"이라는 키가 *있다*.
# "PlayerUnit": [ 16, 832, 0 ] -> 이건 "Roster"에서 시작하는 체인같음.
# "Roster": 0x1D92540
# 가장 단순하게 접근하려면, d2go가 PlayerUnit의 주소를 어떻게 얻는지 봐야 함.
# d2go/memory/game_reader.go -> Init() 함수에서 각종 포인터를 초기화.
# self.offset.PlayerUnit -> 이걸 사용.
# 이 self.offset은 offsets.json에서 로드됨.
print("playerUnit offset configuration not found. Check offsets.json structure.")
return None
# PlayerUnit 포인터 자체를 읽어옴
# player_unit_actual_ptr = self.pm.read_longlong(self.base_address + player_unit_ptr_offset)
# PlayerUnit 주소를 얻었다고 가정 (이 부분은 d2go 코드를 더 자세히 봐야 함)
# 여기서는 가장 중요한 'PlayerUnit' 포인터 주소를 이미 알고 있다고 가정
# (예: Cheat Engine 등으로 직접 찾았거나, d2go/koolo의 정확한 로직을 파악했다고 가정)
# === d2go/memory/player.go PlayerData() 분석 ===
# 1. gd.offset.PlayerUnit: offsets.json에서 "PlayerUnit" 키의 값 (정수 오프셋)
# 2. playerUnitAddress := gd.Process.moduleBaseAddressPtr + gd.offset.PlayerUnit
# 3. playerPtr := gd.Process.ReadUInt(playerUnitAnnotation.Address) (ReadUInt64 여야 할듯)
# 4. If playerPtr > 0 then, 실제 PlayerUnit 데이터 읽기 시작.
# HP: gd.Process.ReadUInt(playerPtr + gd.offset.HP)
if "PlayerUnit" not in self.offsets: # koolo의 offsets.json에는 있음
print("Key 'PlayerUnit' not found in offsets.json")
return None
player_unit_offset_from_base = self.offsets["PlayerUnit"] # 이것 자체가 오프셋
# player_unit_address_location = self.base_address + player_unit_offset_from_base
# player_unit_ptr = self.pm.read_longlong(player_unit_address_location)
# koolo offsets.json의 PlayerUnit 은 [16, 832, 0] 같은 배열임.
# 이는 Roster -> RosterMember -> PlayerUnit 으로 이어지는 포인터 체인으로 보임.
# "Roster": 0x1D92540 (이게 base + offset)
roster_ptr_addr = self.base_address + self.offsets["Roster"]
roster_ptr = self.pm.read_longlong(roster_ptr_addr)
if roster_ptr == 0: return {"error": "Roster pointer is null"}
player_unit_ptr = self.resolve_pointer_chain(roster_ptr, self.offsets["PlayerUnit"]) # PlayerUnit 배열은 오프셋 체인
if player_unit_ptr == 0: return {"error": "PlayerUnit pointer is null after chain."}
# 이제 player_unit_ptr이 실제 PlayerUnit 구조체를 가리킴
# 이 구조체 내에서 HP, MP 등의 오프셋은 offsets.json의 player_stats 섹션 참고
stats_offsets = self.offsets.get("player_stats", {})
try:
# d2go/data/player.go PlayerStats struct 참고
# HP는 보통 StatsListEx -> Stat배열 에서 찾음.
# 여기서는 단순화하여 직접 오프셋이 있다고 가정.
# 실제로는 StatList 주소를 얻고, 거기서 Stat ID로 찾아야 함.
# d2go/memory/character_stats.go -> ReadStatsList() 참고
# 가장 간단한 예시 (실제로는 복잡함)
# 이름 읽기 (d2go/data/player.go -> Name string `offset:"0x10"`)
# name_addr = player_unit_ptr + 0x10 # 이 0x10이 이름 오프셋이라고 가정
# name_bytes = self.pm.read_bytes(name_addr, 16) # D2 이름 최대 15자 + 널
# player_name = name_bytes.split(b'\x00', 1)[0].decode('utf-8', errors='ignore')
# 체력 (매우 단순화된 예시, 실제로는 스탯 리스트 파싱 필요)
# hp_offset = stats_offsets.get("hp", 0x60) # 가상의 직접 HP 오프셋
# current_hp = self.pm.read_int(player_unit_ptr + hp_offset)
# d2go/memory/character_stats.go의 GetStat func를 재현해야 함
# Path: PlayerUnitPtr -> 0x0178 (StatList Ptr) -> 0x78 (pStatsListEx) -> 0x08 (pStats) -> Stat Array
# Stat: ID (word), Value (dword)
stat_list_ptr_offset = self.offsets.get("statList", 0x178) # player_unit 내의 StatList 포인터 오프셋
stat_list_ptr = self.pm.read_longlong(player_unit_ptr + stat_list_ptr_offset)
if stat_list_ptr == 0: return {"error": "StatList pointer is null"}
# pStatsListEx (0x78 from StatList)
p_stats_list_ex = self.pm.read_longlong(stat_list_ptr + self.offsets.get("pStatsListEx", 0x78))
if p_stats_list_ex == 0: return {"error": "pStatsListEx is null"}
# pStats (0x08 from pStatsListEx)
p_stats_array_ptr = self.pm.read_longlong(p_stats_list_ex + self.offsets.get("pStats", 0x08))
if p_stats_array_ptr == 0: return {"error": "pStats array pointer is null"}
# Array length (0x0C from pStatsListEx)
stats_count = self.pm.read_int(p_stats_list_ex + self.offsets.get("statsCount", 0x0C))
player_data = {"name": "Unknown", "hp": -1, "max_hp": -1, "mp": -1, "max_mp": -1}
# Stat ID (https://github.com/hectorgimenez/d2go/blob/master/data/stat.go)
STAT_HP_ID = 6
STAT_MAXHP_ID = 7
STAT_MP_ID = 8
STAT_MAXMP_ID = 9
for i in range(stats_count):
stat_entry_addr = p_stats_array_ptr + (i * self.offsets.get("statSize", 8)) # 각 Stat 항목 크기 (ID:word, Val:dword, padding)
stat_id = self.pm.read_short(stat_entry_addr + self.offsets.get("statIdOffset", 0x00)) # StatID 위치
stat_value = self.pm.read_int(stat_entry_addr + self.offsets.get("statValueOffset", 0x02)) # StatValue 위치
if stat_id == STAT_HP_ID: player_data["hp"] = stat_value
elif stat_id == STAT_MAXHP_ID: player_data["max_hp"] = stat_value
elif stat_id == STAT_MP_ID: player_data["mp"] = stat_value
elif stat_id == STAT_MAXMP_ID: player_data["max_mp"] = stat_value
# 이름은 다른 곳에서 읽어야 함 (PlayerUnit + NameOffset)
name_offset = self.offsets.get("name", 0x58) # player_unit 내의 이름 오프셋 (PlayerTxt)
name_ptr = self.pm.read_longlong(player_unit_ptr + name_offset)
if name_ptr != 0:
name_bytes = self.pm.read_bytes(name_ptr, 16)
player_data["name"] = name_bytes.split(b'\x00', 1)[0].decode('utf-8', errors='ignore')
return player_data
except Exception as e:
print(f"Error reading player data: {e}")
return None
if __name__ == '__main__':
try:
reader = D2RMemoryReader()
if reader.pm: # Process가 성공적으로 열렸다면
player_info = reader.get_player_data()
if player_info:
print(f"Player Info: {player_info}")
else:
print("Failed to get player info.")
except Exception as e:
print(f"An error occurred: {e}")
주의사항 및 추가 작업:
d2go와 koolo의 소스코드, 특히 offsets.json을 로드하고 사용하는 부분을 면밀히 분석해서 정확한 포인터 경로와 오프셋을 알아내야 해. 위 코드는 매우 단순화된 가정을 포함하고 있어. d2go/memory/player.go, d2go/memory/character_stats.go 등의 파일을 보고 실제 메모리 접근 로직을 파악해야 해.offsets.json을 업데이트하거나, AOB(Array of Bytes) 스캔 같은 동적 주소 찾기 기법을 도입해야 할 수 도 있어.uint32, int16, float64 등)과 Python/C#에서 읽을 때의 바이트 크기, 부호 여부 등을 정확히 맞춰야 해. (예: Go uint32 -> Python struct.unpack("<I", bytes)).내가 도와줄 수 있는 부분:
d2go의 특정 Go 코드 조각을 보고, 그것이 어떤 메모리 주소를 어떻게 읽는지 분석해 줄 수 있어.offsets.json의 특정 항목이 어떤 의미인지 해석하는 데 도움을 줄 수 있어.d2go의 실제 로직에 더 가깝게 개선하는 데 도움을 줄 수 있어. (예: d2go/memory/character_stats.go의 GetStat 함수 로직을 Python으로 옮기기)어떤 부분을 먼저 집중적으로 분석하고 Python/C# 코드로 옮겨보고 싶어? 예를 들어, "플레이어의 현재 HP와 MP를 읽는 부분"부터 시작할 수 있어.
그러면 플레이어 인벤토리나 바닥에 떨어진 아이템 읽는 코드 만들어줘
알았어! 플레이어 인벤토리 아이템과 바닥에 떨어진 아이템을 읽는 것은 꽤 복잡한 작업이야. d2go와 koolo의 구조를 참고해서 Python 코드를 만들어 볼게.
핵심 가정 및 준비물:
offsets.json: koolo/assets/offsets/offsets.json 파일이 필요해. 이 파일 경로를 코드 내에 정확히 지정해야 해.ITEMS_BY_TXT_FILE_NO.json: koolo/assets/ITEMS_BY_TXT_FILE_NO.json 파일도 필요해. 아이템 코드를 이름으로 변환하는 데 사용돼.pymem 라이브러리: 설치되어 있어야 해 (pip install pymem).데이터 구조 및 상수 정의 (d2go/data/ 참고):
# d2go/data/item.go, d2go/data/unit.go 등을 참고하여 필요한 상수 정의
class ItemQuality:
LOW_QUALITY = 1
NORMAL = 2
SUPERIOR = 3
MAGIC = 4
SET = 5
RARE = 6
UNIQUE = 7
CRAFTED = 8
TEMPERED = 9
class ItemFlag: # d2go/data/item.go ItemFlag
IDENTIFIED = 0x10
SOCKETED = 0x800
ETHEREAL = 0x400000
RUNEWORD = 0x4000000 # IsRuneword
class UnitType:
PLAYER = 0
MONSTER = 1
OBJECT = 2
MISSILE = 3
ITEM = 4
TILE = 5
# Stat IDs (d2go/data/stat.go) - 일부만 예시
class StatId:
STRENGTH = 0
ENERGY = 1
DEXTERITY = 2
VITALITY = 3
# ... 기타 스탯 ID들
ITEM_LEVELREQ = 80
# 인벤토리 위치 (d2go/data/inventory.go)
class InventoryLocation:
NONE = 0
EQUIPPED = 1
BELT = 2
INVENTORY = 3 # Main inventory
CUBE = 4
STASH = 5
# ...
메인 코드 (D2RMemoryReader 클래스 확장):
import pymem
import pymem.process
import json
import struct
import time # 디버깅 및 안정성을 위해
OFFSETS_FILE = "path/to/your/koolo/assets/offsets/offsets.json" # 실제 경로로 수정
ITEMS_MAPPING_FILE = "path/to/your/koolo/assets/ITEMS_BY_TXT_FILE_NO.json" # 실제 경로로 수정
class D2RMemoryReader:
def __init__(self, process_name="D2R.exe"):
self.pm = None
self.base_address = None
self.offsets = {}
self.item_name_map = {} # TxtFileNo to Name/Code mapping
try:
self.pm = pymem.Pymem(process_name)
for mod in list(self.pm.list_modules()):
if mod.name.lower() == process_name.lower():
self.base_address = mod.lpBaseOfDll
print(f"Found {process_name} at {hex(self.base_address)}")
break
if not self.base_address:
raise Exception(f"{process_name} module not found.")
with open(OFFSETS_FILE, 'r') as f:
self.offsets = json.load(f)
with open(ITEMS_MAPPING_FILE, 'r') as f:
self.item_name_map = json.load(f)
except pymem.exception.ProcessNotFound:
print(f"Process {process_name} not found.")
raise
except FileNotFoundError as e:
print(f"Required file not found: {e.filename}")
raise
except Exception as e:
print(f"Initialization error: {e}")
raise
def resolve_pointer_chain(self, base_addr, ptr_offsets):
addr = base_addr
try:
for i, offset in enumerate(ptr_offsets):
addr = self.pm.read_longlong(addr + offset)
if addr == 0:
# print(f"Pointer chain broke at offset index {i} (offset {hex(offset)})")
return 0
return addr
except Exception as e:
# print(f"Error resolving pointer chain: {e} at {hex(addr)} with offset {hex(ptr_offsets[i] if i < len(ptr_offsets) else 0)}")
return 0
def _read_stat_list(self, stat_list_owner_ptr, stat_list_offset_in_owner):
"""
Reads stats from a unit's stat list.
stat_list_owner_ptr: Pointer to the structure containing the pStatList (e.g., PlayerUnit or ItemData).
stat_list_offset_in_owner: Offset from stat_list_owner_ptr to pStatList.
"""
stats_data = []
if stat_list_owner_ptr == 0: return stats_data
try:
p_stat_list = self.pm.read_longlong(stat_list_owner_ptr + stat_list_offset_in_owner)
if p_stat_list == 0: return stats_data
# pStatsListEx (offset from pStatList, e.g., 0x48 in d2go, 0x78 in some other sources for player)
# koolo offsets.json has "pStatsListEx": 0x48 relative to pStatList for items.
# And "pStatsListEx": 0x78 for character stats. We need to be careful.
# For items, d2go/memory/item.go -> ReadStatsList -> uses ItemStasListOffset (0x38 from ItemData) for pStatList
# Then pStatList + 0x48 for pStatsListEx
p_stats_list_ex_offset = self.offsets.get("item_pStatsListEx", self.offsets.get("pStatsListEx", 0x48)) # Use specific or general
p_stats_list_ex = self.pm.read_longlong(p_stat_list + p_stats_list_ex_offset)
if p_stats_list_ex == 0: return stats_data
p_stats_array_ptr = self.pm.read_longlong(p_stats_list_ex + self.offsets.get("pStats", 0x08))
stats_count = self.pm.read_int(p_stats_list_ex + self.offsets.get("statsCount", 0x0C))
if p_stats_array_ptr == 0 or stats_count <= 0 or stats_count > 50: # Sanity check for count
return stats_data
for i in range(stats_count):
stat_entry_addr = p_stats_array_ptr + (i * self.offsets.get("statSize", 8))
stat_id = self.pm.read_short(stat_entry_addr + self.offsets.get("statIdOffset", 0x00))
# Stat value depends on the layer for some stats (like skills)
# For simplicity, reading the direct value. Layer is at +0x02 (word), Value is at +0x04 (dword)
# d2go reads Value at +0x02 (int), which is likely correct if Id is word, val is int, and layer is not always present/needed.
# koolo's offset.json implies statIdOffset=0, statValueOffset=2 (sizeof(WORD)=2)
stat_value = self.pm.read_int(stat_entry_addr + self.offsets.get("statValueOffset", 0x02))
stats_data.append({"id": stat_id, "value": stat_value})
return stats_data
except Exception as e:
# print(f"Error reading stat list: {e}")
return stats_data
def _read_item_data(self, item_unit_ptr, unit_id):
"""
Reads detailed data for a single item unit.
item_unit_ptr: Pointer to the UnitAny structure for the item.
unit_id: The item's unique UnitID.
"""
if item_unit_ptr == 0: return None
item_details = {"unit_id": unit_id, "name": "Unknown", "code": "", "quality": -1, "flags": [], "stats": [], "position": None, "ethereal": False, "socketed": False, "runeword": False}
try:
# ItemData pointer (offset from ItemUnit)
p_item_data_offset = self.offsets.get("ItemData", 0xD8) # Common offset for pItemData in UnitAny
p_item_data = self.pm.read_longlong(item_unit_ptr + p_item_data_offset)
if p_item_data == 0: return item_details # Cannot proceed without item data
item_details["quality"] = self.pm.read_ubyte(p_item_data + self.offsets.get("ItemQuality", 0x09)) # Or 0x0B in some structs
# TxtFileNo (item code/type)
txt_file_no = self.pm.read_int(p_item_data + self.offsets.get("ItemType", 0x51)) # Offset for TxtFileNo / ItemType in ItemData
item_type_info = self.item_name_map.get(str(txt_file_no))
if item_type_info:
item_details["name"] = item_type_info.get("name", "Unknown")
item_details["code"] = item_type_info.get("Code", "")
# item_details["type"] = item_type_info.get("type", "") # e.g. 'armo', 'weap'
# Item Flags (e.g., Identified, Ethereal, Socketed, Runeword)
# d2go: ItemData + 0x1B (DWORD) -> ItemFlags
item_flags_val = self.pm.read_int(p_item_data + self.offsets.get("ItemFlags", 0x1B))
if item_flags_val & ItemFlag.IDENTIFIED: item_details["flags"].append("Identified")
if item_flags_val & ItemFlag.ETHEREAL:
item_details["ethereal"] = True
item_details["flags"].append("Ethereal")
if item_flags_val & ItemFlag.SOCKETED:
item_details["socketed"] = True
item_details["flags"].append("Socketed")
if item_flags_val & ItemFlag.RUNEWORD: # IsRuneword flag
item_details["runeword"] = True
item_details["flags"].append("Runeword")
item_details["level"] = self.pm.read_ubyte(p_item_data + self.offsets.get("ItemLevel", 0x48)) # ilvl
# Item Stats (pStatList is within ItemData)
# d2go: ItemData + 0x38 (ItemStats -> pStatList)
item_stats_list_offset_in_item_data = self.offsets.get("ItemStats", 0x38)
item_details["stats"] = self._read_stat_list(p_item_data, item_stats_list_offset_in_item_data)
return item_details
except Exception as e:
# print(f"Error reading item data for unit_id {unit_id}: {e}")
return item_details # Return partial data
def _get_player_unit_ptr(self):
"""Helper to get the current player's UnitAny pointer."""
# This logic is based on common D2/Koolo/d2go approaches
# Roster -> PlayerUnit array -> Current Player
# Offsets from koolo's offsets.json
roster_ptr_addr = self.base_address + self.offsets["Roster"]
roster_ptr = self.pm.read_longlong(roster_ptr_addr)
if roster_ptr == 0: return 0
# koolo's PlayerUnit offset is a chain from Roster. [16, 832, 0] etc.
# This usually points to the *first* player in the roster.
# For single player, this is usually correct.
player_unit_ptr = self.resolve_pointer_chain(roster_ptr, self.offsets["PlayerUnit"])
return player_unit_ptr
def get_inventory_items(self):
"""Reads items from the player's main inventory grid."""
inventory_items = []
player_unit_ptr = self._get_player_unit_ptr()
if player_unit_ptr == 0:
print("Could not get player unit pointer.")
return inventory_items
try:
# Get pointer to the player's inventory component
# d2go: playerUnit + gd.offset.InventoryOffset (e.g. 0x98)
# This offset is *within* the PlayerUnit struct
inventory_comp_offset = self.offsets.get("InventoryOffset", 0x98) # A common offset for inventory component in PlayerUnit
p_inventory_component = self.pm.read_longlong(player_unit_ptr + inventory_comp_offset)
if p_inventory_component == 0:
print("Inventory component pointer is null.")
return inventory_items
# The inventory component likely contains a pointer to an array of item pointers (the grid)
# d2go/memory/item.go GetInventoryItems iterates a grid.
# The p_inventory_component itself might be the start of this item pointer array.
# Or it might be p_inventory_component + some_offset_to_grid_array
# Let's assume p_inventory_component points directly to the grid array (array of item UnitAny ptrs)
# d2go uses data.InventoryMaxSlotsY (10) and data.InventoryMaxSlotsX (4 for main inv)
# For simplicity, let's assume a fixed number of slots if grid dimensions are not in offsets.json
# This part is highly dependent on the exact D2R inventory structure.
# d2go's GetInventoryItems: playerInventoryOffset + uintptr(y*data.InventoryMaxSlotsX+x) * gd.Process.PointerSize()
# Here, playerInventoryOffset IS p_inventory_component.
# For a simpler approach (like iterating a linked list of items in inventory if available):
# Some D2 versions have pFirstItemInInventory in the inventory component.
# However, d2go's grid iteration is more likely for D2R.
# We need the dimensions of the inventory grid (e.g., main inventory 10x4)
# Let's assume for main inventory:
inv_grid_y_max = 10
inv_grid_x_max = 4
pointer_size = 8 # 64-bit pointers
for y in range(inv_grid_y_max):
for x in range(inv_grid_x_max):
item_ptr_offset_in_grid = (y * inv_grid_x_max + x) * pointer_size
item_unit_ptr_in_slot = self.pm.read_longlong(p_inventory_component + item_ptr_offset_in_grid)
if item_unit_ptr_in_slot > 0:
# Need UnitID for the item. ItemUnit usually has it at a fixed offset.
unit_id_offset = self.offsets.get("UnitID", 0x08) # Offset for UnitID in UnitAny
item_unit_id = self.pm.read_int(item_unit_ptr_in_slot + unit_id_offset)
item_data = self._read_item_data(item_unit_ptr_in_slot, item_unit_id)
if item_data:
item_data["inventory_pos"] = {"x": x, "y": y}
inventory_items.append(item_data)
return inventory_items
except Exception as e:
print(f"Error reading inventory items: {e}")
return inventory_items
def get_ground_items(self, max_items=50):
"""Reads items currently on the ground near the player."""
ground_items = []
try:
# unitTable is a global array of 128 pointers to linked lists of units
unit_table_ptr_addr = self.base_address + self.offsets["unitTable"]
unit_table_start_ptr = self.pm.read_longlong(unit_table_ptr_addr)
if unit_table_start_ptr == 0:
print("Unit table start pointer is null.")
return ground_items
# Iterate through the 128 lists in the unit table
items_found_count = 0
for i in range(128): # Max 128 unit type lists
if items_found_count >= max_items: break
current_list_head_ptr = self.pm.read_longlong(unit_table_start_ptr + uintptr(i) * 8)
current_unit_ptr = current_list_head_ptr
while current_unit_ptr > 0:
if items_found_count >= max_items: break
try:
# Read UnitType (offset from UnitAny base)
unit_type_val = self.pm.read_int(current_unit_ptr + self.offsets.get("UnitType", 0x04))
if unit_type_val == UnitType.ITEM:
unit_id_offset = self.offsets.get("UnitID", 0x08)
item_unit_id = self.pm.read_int(current_unit_ptr + unit_id_offset)
item_data = self._read_item_data(current_unit_ptr, item_unit_id)
if item_data:
# Read item position (Path data)
p_path_offset = self.offsets.get("pPath", 0xE8) # Offset to Path* in UnitAny
p_path = self.pm.read_longlong(current_unit_ptr + p_path_offset)
if p_path > 0:
# Offsets within Path struct for X and Y
# d2go Path struct: PosX (0x10), PosY (0x14)
# koolo offsets.json: "PathX": 16, "PathY": 20
item_x = self.pm.read_short(p_path + self.offsets.get("PathX", 0x10)) # Or 0x02 for RoomX then convert
item_y = self.pm.read_short(p_path + self.offsets.get("PathY", 0x14)) # Or 0x04 for RoomY
item_data["position"] = {"x": item_x, "y": item_y}
ground_items.append(item_data)
items_found_count += 1
# Move to next unit in this list
# Offset for pNextUnit in UnitAny
next_unit_ptr_offset = self.offsets.get("NextUnit", 0x150) # Common offset for pNext
current_unit_ptr = self.pm.read_longlong(current_unit_ptr + next_unit_ptr_offset)
except Exception as unit_iter_ex:
# print(f"Error processing a unit in list {i}: {unit_iter_ex}")
current_unit_ptr = 0 # Break from this list on error
if current_unit_ptr == list_head_ptr: # Safety break for circular lists
# print(f"Warning: Circular list detected in unit table list {i}")
break
return ground_items
except Exception as e:
print(f"Error reading ground items: {e}")
return ground_items
if __name__ == '__main__':
try:
print(f"Attempting to connect to D2R... Ensure it's running in offline single player.")
print(f"Using offsets: {OFFSETS_FILE}")
print(f"Using item names: {ITEMS_MAPPING_FILE}")
reader = D2RMemoryReader()
if reader.pm:
print("\n--- Player Inventory Items ---")
inventory = reader.get_inventory_items()
if inventory:
for item in inventory:
print(f" Name: {item['name']} (Code: {item['code']}), Quality: {item['quality']}, Flags: {item['flags']}, Stats: {len(item['stats'])} mods, Pos: {item.get('inventory_pos')}")
else:
print(" No inventory items found or failed to read.")
print("\n--- Ground Items (first few) ---")
ground = reader.get_ground_items(max_items=10) # Limit for display
if ground:
for item in ground:
print(f" Name: {item['name']} (Code: {item['code']}), Quality: {item['quality']}, Pos: {item.get('position')}, Stats: {len(item['stats'])} mods")
else:
print(" No ground items found or failed to read.")
else:
print("Failed to initialize D2RMemoryReader (process not found or other init error).")
except FileNotFoundError:
print(f"ERROR: Ensure '{OFFSETS_FILE}' and '{ITEMS_MAPPING_FILE}' exist at the specified paths.")
except pymem.exception.ProcessNotFound:
print(f"ERROR: D2R.exe process not found. Please start the game.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
import traceback
traceback.print_exc()
오픈소스보고 지도관련 데이터 정리해서 알려줄수있어?
오케이! hectorgimenez/d2go (그리고 이를 사용하는 koolo) 프로젝트에서 지도/맵 관련 데이터를 어떻게 처리하는지 정리해줄게. 디아블로 2의 맵 시스템은 꽤 복잡하지만, 핵심적인 개념들을 파악하면 이해할 수 있어.
디아블로 2 맵 시스템의 기본 개념:
맵(Map) vs 레벨(Level) vs 구역(Area):
data.AreaBloodMoor, data.AreaTristram). d2go/data/area.go에 정의되어 있어.d2go/data/level.go에 Level 구조체가 정의되어 있음.d2go/data/room.go에 Room 구조체가 있어.좌표계:
핵심 데이터 구조체 (d2go/data/ 및 d2go/memory/ 참고):
Act (메모리 구조체): 현재 액트에 대한 정보를 담고 있으며, 현재 로드된 Level에 대한 포인터를 포함하는 경우가 많아. (d2go/memory/common.go 등에서 pAct를 찾는 로직 확인)
koolo/offsets.json에 Act 또는 유사한 이름의 전역 포인터 오프셋이 있을 거야.Level (메모리 구조체, d2go/data/level.go):
Area: 현재 레벨의 구역 ID (예: data.AreaTristram).PositionX, PositionY: 레벨의 원점 X, Y 좌표.SizeX, SizeY: 레벨의 전체 크기 (타일 단위).pRoom1, pRoom2: 해당 레벨에 속한 룸들의 연결 리스트 시작점 포인터 (또는 룸 그리드 포인터).Room (메모리 구조체, d2go/data/room.go):
pRoomNext: 다음 Room에 대한 포인터 (연결 리스트).pPresetUnit: 이 룸이 어떤 종류의 미리 디자인된 템플릿(프리셋)인지 가리키는 포인터 배열.PositionX, PositionY: 레벨 원점 기준 이 룸의 X, Y 좌표.SizeX, : 이 룸의 크기 (타일 단위).중요한 참고 사항 및 개선점:
0x98, 0xD8 등)은 일반적인 값이나 d2go, koolo에서 보이는 값들을 기반으로 한 추정치야. koolo/assets/offsets/offsets.json 파일의 내용을 면밀히 보고, 해당 JSON 파일의 키를 코드 내의 self.offsets.get("KeyName", default_value) 호출에 정확히 매핑해야 해. offsets.json의 구조를 잘 이해하는 것이 핵심이야.get_inventory_items)은 D2R의 정확한 인벤토리 메모리 구조에 따라 크게 달라질 수 있어. 위 코드는 아이템 포인터들이 그리드 형태로 배열되어 있다고 가정했어. 다른 구조(예: 연결 리스트)일 수도 있어. d2go/memory/item.go의 GetInventoryItems 함수 로직을 Python으로 정확히 옮기는 것이 중요해.get_ground_items에서 Unit Table을 순회하는 방식은 d2go의 unitIterator를 단순화한 버전이야. 실제로는 더 복잡한 동기화나 필터링 로직이 있을 수 있어._read_stat_list 함수는 기본적인 스탯 ID와 값만 읽어. 일부 스탯(예: 스킬 레벨, 오오라)은 여러 레이어나 파라미터를 가질 수 있어서 더 복잡한 파싱이 필요할 수 있어.try-except 블록을 더 많이 사용하고, 포인터가 유효한지 자주 확인해야 해.koolo/assets/offsets/offsets.json 매핑: ItemQuality, ItemFlags, ItemType, PathX, PathY, NextUnit, UnitType, UnitID, statList (아이템용), ItemStats (pStatList를 가리키는 오프셋), InventoryOffset (플레이어 유닛 내에서 인벤토리 데이터 시작점) 등의 키가 offsets.json에 어떻게 정의되어 있는지 확인하고 코드에 반영해야 해.이 코드를 실행하기 전에 OFFSETS_FILE과 ITEMS_MAPPING_FILE 경로를 실제 파일 위치로 꼭 수정해야 해. 그리고 offsets.json의 내용을 보면서 코드 내의 오프셋 값들을 조정해야 할 가능성이 매우 높아.
만약 특정 부분 (예: offsets.json의 특정 키가 코드의 어느 부분에 해당되는지)이 헷갈리면 알려줘!
SizeYColl: 이 룸의 충돌(Collision) 맵 데이터에 대한 포인터. (가장 중요!)Path (유닛 구조체 내, d2go/data/path.go): 플레이어나 몬스터 같은 유닛(UnitAny)은 Path 데이터를 가리키는 포인터(pPath)를 가져.
RoomX, RoomY: 유닛이 현재 있는 룸의 좌표 (레벨 원점 기준).TargetX, TargetY: 유닛의 실제 X, Y 좌표 (타일 단위, 룸 원점 기준 또는 레벨 원점 기준일 수 있음 - d2go 코드 확인 필요).WorldX, WorldY (koolo에서 추가한 필드일 수 있음): 월드 좌표계 기준 X, Y.CollMap (Collision Map 데이터, Room 구조체 내 Coll 포인터가 가리킴):
d2go/data/collision.go에 플래그 상수들이 정의되어 있음.d2go에서 지도 데이터를 읽어오는 방식 (개념적):
UnitAny 구조체 포인터를 얻어와.pPath 얻기: 플레이어 유닛에서 pPath 오프셋을 이용해 Path 데이터 포인터를 읽어와.
Path 데이터에서 플레이어의 현재 RoomX, RoomY 및 정밀 TargetX, TargetY를 알 수 있어.Level 정보 얻기:
pAct (전역 포인터)를 통해 현재 Act 구조체를 찾고, 거기서 pLevel 포인터를 읽어와 현재 Level 정보를 얻을 수 있어. (koolo/offsets.json에 Act 관련 오프셋이 있을 것).Level 정보에서 현재 구역 ID (Area), 레벨 크기 등을 알 수 있어.Room 정보 얻기:
Level의 pRoom1 (또는 pRoomGrid)에서 시작하여 연결된 Room들을 순회할 수 있어.Room의 좌표, 크기, Coll 포인터 등을 읽어올 수 있어.Room의 Coll 포인터를 통해 해당 룸의 충돌 맵 데이터를 읽어와.d2go/memory/map.go의 GetCollMapData 함수가 이 역할을 할 거야. 이 함수는 룸의 충돌 데이터를 2차원 배열 형태로 가공해서 반환해줄 가능성이 높아.Python으로 구현한다면 필요한 핵심 정보 (from offsets.json and d2go logic):
Act 전역 포인터 오프셋.Act 구조체 내 pLevel 오프셋.Level 구조체 내 pRoom1 (또는 pRoomGrid), Area, PositionX/Y, SizeX/Y 등의 오프셋.Room 구조체 내 pRoomNext, pPresetUnit, PositionX/Y, SizeX/Y, Coll 등의 오프셋.UnitAny 구조체 내 pPath 오프셋.Path 구조체 내 RoomX/Y, TargetX/Y 등의 오프셋.Python 예시 (개념적인 접근 - 플레이어 주변 맵 일부 읽기):
# D2RMemoryReader 클래스 내부에 추가될 메소드들 (개념)
# ... (기존 D2RMemoryReader 코드) ...
def get_player_current_level_area(self):
# 1. pAct 읽기 (BaseAddress + offsets["Act"])
# 2. pAct 에서 pLevel 읽기 (pAct_ptr + offsets["ActToPLevel"])
# 3. pLevel 에서 Area ID 읽기 (pLevel_ptr + offsets["LevelAreaID"])
# 4. pLevel 에서 Level PositionX, PositionY, SizeX, SizeY 읽기
# ... (실제 구현은 포인터 체인과 오프셋을 정확히 따라가야 함)
act_ptr_addr = self.base_address + self.offsets["Act"] # 'Act'는 koolo offsets.json의 키여야 함
act_ptr = self.pm.read_longlong(act_ptr_addr)
if act_ptr == 0: return None
p_level_offset_in_act = self.offsets.get("ActToPLevel", 0x20) # 가상의 오프셋
level_ptr = self.pm.read_longlong(act_ptr + p_level_offset_in_act)
if level_ptr == 0: return None
area_id = self.pm.read_int(level_ptr + self.offsets.get("LevelArea", 0x0C)) # Level.Area 오프셋
level_pos_x = self.pm.read_int(level_ptr + self.offsets.get("LevelPosX", 0x14))
level_pos_y = self.pm.read_int(level_ptr + self.offsets.get("LevelPosY", 0x18))
level_size_x = self.pm.read_int(level_ptr + self.offsets.get("LevelSizeX", 0x1C)) # 혹은 0x08
level_size_y = self.pm.read_int(level_ptr + self.offsets.get("LevelSizeY", 0x20)) # 혹은 0x0A
return {
"area_id": area_id,
"level_origin_x": level_pos_x, "level_origin_y": level_pos_y,
"level_size_x": level_size_x, "level_size_y": level_size_y,
"p_level": level_ptr # 다른 함수에서 사용하기 위해
}
def get_player_path_data(self):
player_unit_ptr = self._get_player_unit_ptr() # 이전 답변에서 구현
if player_unit_ptr == 0: return None
p_path_offset = self.offsets.get("pPath", 0xE8) # UnitAny.pPath 오프셋
path_ptr = self.pm.read_longlong(player_unit_ptr + p_path_offset)
if path_ptr == 0: return None
# Path 구조체 오프셋 (d2go/data/path.go 참고)
# Koolo offsets.json 에는 PathX, PathY 등이 있음
room_x = self.pm.read_short(path_ptr + self.offsets.get("PathRoomX", 0x0E)) # Path.RoomX
room_y = self.pm.read_short(path_ptr + self.offsets.get("PathRoomY", 0x10)) # Path.RoomY
target_x = self.pm.read_short(path_ptr + self.offsets.get("PathTargetX", 0x02)) # Path.TargetX (이름은 offsets.json과 다를 수 있음. 실제로는 Path.PosX일 수 있음)
target_y = self.pm.read_short(path_ptr + self.offsets.get("PathTargetY", 0x04)) # Path.TargetY (Path.PosY)
# d2go Path.go 에는 PosX (0x10), PosY (0x14) 가 있음. 이걸 TargetX/Y로 볼 수 있음.
# RoomX(0x0E), RoomY(0x10)도 있는데, 이는 Path 구조체 내에서의 상대적인 룸 위치일 수 있음.
# 실제 플레이어의 "월드 좌표"는 Room의 월드 좌표 + Path의 상대 좌표로 계산해야 할 수도 있음.
# Koolo는 WorldX, WorldY를 직접 Path구조체에서 읽으려 할 수 있음 (오프셋 0x44, 0x48)
return {
"room_x": room_x, "room_y": room_y, # 유닛이 속한 룸의 좌표 (레벨 기준)
"target_x": target_x, "target_y": target_y # 룸 내에서의 정밀 좌표
}
def get_room_collision_data(self, level_ptr, room_x, room_y):
"""
특정 좌표의 Room에 대한 Collision Map을 가져옴.
level_ptr: 현재 Level 구조체 포인터.
room_x, room_y: 찾고자 하는 Room의 레벨 기준 좌표.
"""
if level_ptr == 0: return None
# 1. Level 구조체에서 pRoom1 (또는 pRoomGrid)을 얻는다.
# 2. Room들을 순회하며 (room_x, room_y)에 해당하는 Room을 찾는다.
# d2go/memory/map.go GetRoomByPos() 참고.
# Room은 pRoomNext로 연결된 리스트이거나, pRoomGrid[y][x] 형태의 2D 배열일 수 있다.
# Koolo offsets.json 에는 Level.pRoom1 (0x60), Level.pRoom2 (0xD0)가 있음.
# 이 두 포인터는 서로 다른 룸 타입(예: 실내/실외)의 시작점일 수 있음.
p_room1 = self.pm.read_longlong(level_ptr + self.offsets.get("LevelRoom1", 0x60))
# p_room2 = self.pm.read_longlong(level_ptr + self.offsets.get("LevelRoom2", 0xD0))
# 여기서는 p_room1만 순회한다고 가정. 실제로는 더 복잡함.
current_room_ptr = p_room1
target_room_coll_map = None
visited_rooms = set() # 무한 루프 방지
while current_room_ptr != 0 and current_room_ptr not in visited_rooms:
visited_rooms.add(current_room_ptr)
try:
# Room 구조체 오프셋 (d2go/data/room.go)
r_pos_x = self.pm.read_int(current_room_ptr + self.offsets.get("RoomPosX", 0x08))
r_pos_y = self.pm.read_int(current_room_ptr + self.offsets.get("RoomPosY", 0x0C))
r_size_x = self.pm.read_int(current_room_ptr + self.offsets.get("RoomSizeX", 0x10))
r_size_y = self.pm.read_int(current_room_ptr + self.offsets.get("RoomSizeY", 0x14))
# 플레이어의 Path.RoomX/Y가 이 Room의 범위 내에 있는지 확인.
# Path.RoomX/Y는 Level 기준 Room의 시작 타일 좌표일 수 있음.
if r_pos_x == room_x and r_pos_y == room_y:
p_coll = self.pm.read_longlong(current_room_ptr + self.offsets.get("RoomColl", 0x68)) # Room.Coll
if p_coll > 0:
# Collision Map 데이터 읽기 (1차원 배열)
# CollMap 구조체는 첫 부분에 width, height 정보가 있을 수 있음.
# d2go/data/map.go -> CollMap 구조체 참고 (pMapStart, pMapEnd)
# Koolo offsets.json: CollMapSizeX (0x08), CollMapSizeY (0x0C), CollMapData (0x10)
coll_size_x = self.pm.read_int(p_coll + self.offsets.get("CollMapSizeX", 0x08))
coll_size_y = self.pm.read_int(p_coll + self.offsets.get("CollMapSizeY", 0x0C))
# pMapStart는 p_coll + 0x10 (Data pointer)일 가능성이 높음.
p_map_data_start = p_coll + self.offsets.get("CollMapData", 0x10)
# 데이터 크기: coll_size_x * coll_size_y * sizeof(WORD or BYTE)
# d2go는 WORD(2바이트)로 읽음
coll_data_bytes = self.pm.read_bytes(p_map_data_start, coll_size_x * coll_size_y * 2)
# 2차원 배열로 변환
target_room_coll_map = []
for cy in range(coll_size_y):
row = []
for cx in range(coll_size_x):
index = (cy * coll_size_x + cx) * 2
# WORD (unsigned short, little-endian)
value = struct.unpack("<H", coll_data_bytes[index:index+2])[0]
row.append(value)
target_room_coll_map.append(row)
break # 찾았으므로 루프 종료
# 다음 Room으로 이동
p_room_next_offset = self.offsets.get("RoomNext", 0x20) # Room.pNextRoom
current_room_ptr = self.pm.read_longlong(current_room_ptr + p_room_next_offset)
except Exception as e:
# print(f"Error iterating rooms: {e}")
current_room_ptr = 0 # 에러 시 중단
return target_room_coll_map
# ... (main 부분에서 호출) ...
if __name__ == '__main__':
# ... (기존 코드) ...
if reader.pm:
# ... (인벤토리, 바닥 아이템 코드) ...
print("\n--- Map Data ---")
level_info = reader.get_player_current_level_area()
path_info = reader.get_player_path_data()
if level_info and path_info:
print(f" Current Area ID: {level_info['area_id']}")
print(f" Level Origin: ({level_info['level_origin_x']}, {level_info['level_origin_y']})")
print(f" Level Size: {level_info['level_size_x']}x{level_info['level_size_y']}")
print(f" Player Path Room Coords (Level): ({path_info['room_x']}, {path_info['room_y']})")
print(f" Player Path Target Coords (Room): ({path_info['target_x']}, {path_info['target_y']})")
# 현재 플레이어가 있는 Room의 Collision Map 가져오기
collision_map = reader.get_room_collision_data(level_info['p_level'], path_info['room_x'], path_info['room_y'])
if collision_map:
print(f" Collision map for current room (size {len(collision_map[0])}x{len(collision_map)}):")
# 전체 맵을 출력하는 것은 너무 크므로, 일부만 예시로 출력하거나 요약 정보만 제공
print(f" First row, first 5 elements: {collision_map[0][:5] if collision_map and collision_map[0] else 'N/A'}")
else:
print(" Could not retrieve collision map for the current room.")
else:
print(" Failed to get level or path info.")
핵심 포인트 및 주의사항:
offsets.json 의존성: 위 코드의 모든 오프셋 값 (offsets.get("KeyName", defaultValue))은 koolo의 offsets.json 파일에 있는 키 이름과 값에 정확히 맞춰야 해. JSON 파일의 구조를 보면서 키 이름을 올바르게 사용해야 해.A -> B -> C 와 같이 여러 단계를 거쳐야 원하는 데이터에 도달할 수 있어. 각 단계의 포인터가 유효한지 (0이 아닌지) 확인하는 것이 중요해.struct.unpack을 적절히 활용해야 할 수도 있어.d2go 코드 참고: 가장 정확한 정보는 d2go/memory/ 와 d2go/data/ 폴더의 Go 코드를 직접 보는 것이야. Go 구조체 정의와 메모리 읽기 로직을 Python으로 번역한다고 생각하면 돼.try-except와 유효성 검사를 철저히 해야 해.어떤 특정 지도 정보(예: "현재 플레이어 위치에서 반경 10타일 내의 이동 가능/불가능 정보")를 얻고 싶은지 알려주면, 그 부분에 맞춰서 코드를 더 구체화해 줄 수 있어.