-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
1630 lines (1426 loc) · 53.5 KB
/
main.lua
File metadata and controls
1630 lines (1426 loc) · 53.5 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
--[[
The Binding of Isaac: Repentance - 模块化数据采集框架
架构设计:
1. CollectorRegistry - 可扩展的数据收集器注册系统
2. Network - 网络通信层
3. Protocol - 消息协议层
4. InputExecutor - 输入执行模块
5. EventSystem - 事件系统
支持功能:
- 分频采集 (HIGH/MEDIUM/LOW/ON_CHANGE)
- 动态启用/禁用采集通道
- 增量数据更新
- 双向命令通信
]]
local mod = RegisterMod("SocketBridge", 1)
local json = require("json")
-- ============================================================================
-- 配置系统
-- ============================================================================
local Config = {
HOST = "127.0.0.1",
PORT = 9527,
-- 采集频率配置(帧数间隔)
CollectIntervals = {
HIGH = 1, -- 每帧采集
MEDIUM = 5, -- 5帧一次
LOW = 30, -- 30帧一次
RARE = 90, -- 90帧一次
ON_CHANGE = -1 -- 仅在变化时采集
},
}
-- ============================================================================
-- 全局状态
-- ============================================================================
local State = {
connected = false,
socket = nil,
frameCounter = 0,
currentRoomIndex = -1,
-- 时序扩展字段 (v2.1)
messageSeq = 0,
prevFrameSent = 0,
channelLastCollect = {},
-- 控制模式
-- 模式选项:
-- "MANUAL" - 手动控制
-- "AUTO" - 自动切换(有敌人AI,无敌人手动)
-- "FORCE_AI" - 强制AI模式(无敌人也生效)
controlMode = "AUTO",
-- 内部状态追踪
lastEnemyCount = 0,
wasInCombat = false, -- 上一帧是否在战斗中
aiActive = false, -- AI 是否正在发送非零输入
toggleCooldown = 0,
showModeMessage = false,
modeMessageTimer = 0,
}
-- ============================================================================
-- 输入执行模块
-- ============================================================================
local InputExecutor = {
moveDirection = {x = 0, y = 0},
shootDirection = {x = 0, y = 0},
useItem = false,
useBomb = false,
useCard = false,
usePill = false,
drop = false,
}
function InputExecutor.applyCommand(command)
if not command then return end
local hasInput = false
if command.move then
InputExecutor.moveDirection = command.move
-- 检查是否有非零移动输入
if command.move.x ~= 0 or command.move.y ~= 0 then
hasInput = true
end
end
if command.shoot then
InputExecutor.shootDirection = command.shoot
-- 检查是否有非零射击输入
if command.shoot.x ~= 0 or command.shoot.y ~= 0 then
hasInput = true
end
end
if command.use_item ~= nil then
InputExecutor.useItem = command.use_item
if command.use_item then hasInput = true end
end
if command.use_bomb ~= nil then
InputExecutor.useBomb = command.use_bomb
if command.use_bomb then hasInput = true end
end
if command.use_card ~= nil then
InputExecutor.useCard = command.use_card
if command.use_card then hasInput = true end
end
if command.use_pill ~= nil then
InputExecutor.usePill = command.use_pill
if command.use_pill then hasInput = true end
end
if command.drop ~= nil then
InputExecutor.drop = command.drop
if command.drop then hasInput = true end
end
-- 标记 AI 是否正在发送有效输入
State.aiActive = hasInput
end
function InputExecutor.reset()
InputExecutor.moveDirection = {x = 0, y = 0}
InputExecutor.shootDirection = {x = 0, y = 0}
InputExecutor.useItem = false
InputExecutor.useBomb = false
InputExecutor.useCard = false
InputExecutor.usePill = false
InputExecutor.drop = false
State.aiActive = false
end
-- 获取当前控制模式
function GetControlMode()
return State.controlMode
end
-- 设置控制模式
function SetControlMode(mode)
if mode == "MANUAL" or mode == "AUTO" or mode == "FORCE_AI" then
State.controlMode = mode
State.forceAI = (mode == "FORCE_AI")
-- 切换到手动模式时立即重置输入
if mode == "MANUAL" then
InputExecutor.reset()
State.wasInCombat = false
end
print("[SocketBridge] Control mode set to: " .. mode)
end
end
-- 判断当前是否应该由 AI 控制
local function shouldAIControl()
local mode = State.controlMode
if mode == "MANUAL" then
-- 总是确保手动模式下没有残留的 AI 输入
if State.wasInCombat then
InputExecutor.reset()
State.wasInCombat = false
end
-- 即使 wasInCombat 为 false,也确保重置输入(处理从未战斗的情况)
InputExecutor.reset()
return false
elseif mode == "FORCE_AI" then
State.wasInCombat = true
return true
end
-- AUTO 模式: 根据敌人存在与否自动切换
local room = Game():GetRoom()
local enemyCount = room and room:GetAliveEnemiesCount() or 0
-- 检测战斗状态变化
local isInCombat = enemyCount > 0
-- 状态变化检测
-- 只有当 AI 实际发送输入时,才认为 AI 在控制
if State.aiActive then
State.wasInCombat = true
end
-- AI 正在控制且有敌人时,阻止玩家输入
if isInCombat and State.aiActive then
return true
end
-- 如果没有敌人,或者敌人存在但 AI 未发送输入,玩家可以手动控制
if not isInCombat then
-- 战斗结束,切换回手动
if State.wasInCombat then
InputExecutor.reset()
State.wasInCombat = false
end
end
return false
end
-- ============================================================================
-- 辅助函数
-- ============================================================================
local Helpers = {}
function Helpers.vectorToTable(vec)
if vec then
return { x = vec.X, y = vec.Y }
end
return { x = 0, y = 0 }
end
function Helpers.colorToTable(color)
if color then
return { r = color.R, g = color.G, b = color.B, a = color.A }
end
return nil
end
function Helpers.getGame()
return Game()
end
function Helpers.getRoom()
return Game():GetRoom()
end
function Helpers.getLevel()
return Game():GetLevel()
end
function Helpers.getPlayers()
local game = Game()
local players = {}
for i = 0, game:GetNumPlayers() - 1 do
local player = Isaac.GetPlayer(i)
if player then
table.insert(players, player)
end
end
return players
end
-- ============================================================================
-- 网络层
-- ============================================================================
local Network = {
retryInterval = 60,
lastRetryFrame = 0,
}
function Network.connect()
if State.connected then return true end
if State.frameCounter - Network.lastRetryFrame < Network.retryInterval then
return false
end
Network.lastRetryFrame = State.frameCounter
local success, result = pcall(function()
local socket = require("socket.core")
local tcp = socket.tcp()
tcp:settimeout(0.01)
local connectResult = tcp:connect(Config.HOST, Config.PORT)
return tcp, connectResult
end)
if success and result then
State.socket = result
State.connected = true
print("[SocketBridge] Connected to server")
return true
end
return false
end
function Network.disconnect()
if State.socket then
pcall(function() State.socket:close() end)
State.socket = nil
end
State.connected = false
end
function Network.send(data)
if not State.connected then return false end
local success, err = pcall(function()
local payload = json.encode(data) .. "\n"
State.socket:send(payload)
end)
if not success then
Network.disconnect()
return false
end
return true
end
function Network.receive()
if not State.connected then return nil end
local success, line, err = pcall(function()
return State.socket:receive("*l")
end)
if success and line then
local ok, data = pcall(json.decode, line)
if ok then
return data
end
elseif err == "closed" then
Network.disconnect()
end
return nil
end
-- ============================================================================
-- 协议层
-- ============================================================================
local Protocol = {
VERSION = "2.1",
MessageType = {
DATA = "DATA",
FULL_STATE = "FULL",
EVENT = "EVENT",
COMMAND = "CMD",
}
}
function Protocol.createDataMessage(data, channels)
State.messageSeq = State.messageSeq + 1
local channelMeta = {}
for _, channelName in ipairs(channels) do
local meta = State.channelLastCollect[channelName]
if meta then
channelMeta[channelName] = {
collect_frame = meta.collect_frame,
collect_time = meta.collect_time,
interval = meta.interval,
stale_frames = State.frameCounter - meta.collect_frame,
}
end
end
local msg = {
version = Protocol.VERSION,
type = Protocol.MessageType.DATA,
timestamp = Isaac.GetTime(),
frame = State.frameCounter,
room_index = State.currentRoomIndex,
-- 时序字段 (v2.1)
seq = State.messageSeq,
game_time = Isaac.GetTime(),
prev_frame = State.prevFrameSent or 0,
channel_meta = channelMeta,
payload = data,
channels = channels
}
State.prevFrameSent = State.frameCounter
return msg
end
function Protocol.createFullStateMessage(fullState, channels)
State.messageSeq = State.messageSeq + 1
local channelMeta = {}
for _, channelName in ipairs(channels or {}) do
local meta = State.channelLastCollect[channelName]
if meta then
channelMeta[channelName] = {
collect_frame = meta.collect_frame,
collect_time = meta.collect_time,
interval = meta.interval,
stale_frames = State.frameCounter - meta.collect_frame,
}
end
end
local msg = {
version = Protocol.VERSION,
type = Protocol.MessageType.FULL_STATE,
timestamp = Isaac.GetTime(),
frame = State.frameCounter,
-- 时序字段 (v2.1)
seq = State.messageSeq,
game_time = Isaac.GetTime(),
prev_frame = State.prevFrameSent or 0,
channel_meta = channelMeta,
payload = fullState,
}
State.prevFrameSent = State.frameCounter
return msg
end
function Protocol.createEventMessage(eventType, eventData)
return {
version = Protocol.VERSION,
type = Protocol.MessageType.EVENT,
timestamp = Isaac.GetTime(),
frame = State.frameCounter,
event = eventType,
data = eventData
}
end
-- ============================================================================
-- 收集器注册系统
-- ============================================================================
local CollectorRegistry = {
collectors = {},
cache = {},
frameCounters = {},
changeHashes = {},
}
function CollectorRegistry:register(name, config)
self.collectors[name] = {
name = name,
enabled = config.enabled ~= false,
interval = config.interval or "MEDIUM",
priority = config.priority or 5,
collect = config.collect,
hash = config.hash,
}
self.frameCounters[name] = 0
self.cache[name] = nil
self.changeHashes[name] = nil
end
function CollectorRegistry:setEnabled(name, enabled)
if self.collectors[name] then
self.collectors[name].enabled = enabled
end
end
function CollectorRegistry:setInterval(name, interval)
if self.collectors[name] then
self.collectors[name].interval = interval
end
end
function CollectorRegistry:shouldCollect(name)
local collector = self.collectors[name]
if not collector or not collector.enabled then
return false
end
local interval = Config.CollectIntervals[collector.interval]
if interval == -1 then
return true -- ON_CHANGE 模式
end
self.frameCounters[name] = (self.frameCounters[name] or 0) + 1
if self.frameCounters[name] >= interval then
self.frameCounters[name] = 0
return true
end
return false
end
-- 简单哈希用于变化检测
local function simpleHash(data)
if type(data) ~= "table" then
return tostring(data)
end
local str = ""
for k, v in pairs(data) do
if type(v) == "table" then
str = str .. k .. simpleHash(v)
else
str = str .. k .. tostring(v)
end
end
return str
end
function CollectorRegistry:collect(name, forceCollect)
local collector = self.collectors[name]
if not collector then return nil, nil end
if not forceCollect and not self:shouldCollect(name) then
return nil, nil
end
local success, data = pcall(collector.collect)
if not success or data == nil then
return nil, nil
end
-- ON_CHANGE 变化检测
if collector.interval == "ON_CHANGE" and not forceCollect then
local hashFunc = collector.hash or simpleHash
local newHash = hashFunc(data)
if self.changeHashes[name] == newHash then
return nil, nil
end
self.changeHashes[name] = newHash
end
self.cache[name] = data
local collectMeta = {
collect_frame = State.frameCounter,
collect_time = Isaac.GetTime(),
interval = collector.interval,
}
State.channelLastCollect[name] = collectMeta
return data, collectMeta
end
function CollectorRegistry:collectAll()
local results = {}
local collectedChannels = {}
for name, _ in pairs(self.collectors) do
local data, meta = self:collect(name, false)
if data ~= nil then
results[name] = data
table.insert(collectedChannels, name)
end
end
return results, collectedChannels
end
function CollectorRegistry:forceCollectAll()
local results = {}
local channels = {}
for name, _ in pairs(self.collectors) do
local data, meta = self:collect(name, true)
if data ~= nil then
results[name] = data
table.insert(channels, name)
end
end
return results, channels
end
function CollectorRegistry:getCached(name)
return self.cache[name]
end
function CollectorRegistry:getAllCached()
local results = {}
for name, data in pairs(self.cache) do
if data ~= nil then
results[name] = data
end
end
return results
end
function CollectorRegistry:getConfig()
local config = {}
for name, collector in pairs(self.collectors) do
config[name] = {
enabled = collector.enabled,
interval = collector.interval,
priority = collector.priority
}
end
return config
end
-- ============================================================================
-- 数据收集器定义
-- ============================================================================
-- 玩家位置 (高频)
CollectorRegistry:register("PLAYER_POSITION", {
interval = "HIGH",
priority = 10,
collect = function()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
data[i] = {
pos = Helpers.vectorToTable(player.Position),
vel = Helpers.vectorToTable(player.Velocity),
move_dir = player:GetMovementDirection(),
fire_dir = player:GetFireDirection(),
head_dir = player:GetHeadDirection(),
aim_dir = Helpers.vectorToTable(player:GetAimDirection()),
}
end
return data
end
})
-- 玩家属性 (低频)
CollectorRegistry:register("PLAYER_STATS", {
interval = "LOW",
priority = 5,
collect = function()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
local tearRange = player.TearRange
data[i] = {
player_type = player:GetPlayerType(),
damage = player.Damage,
speed = player.MoveSpeed,
tears = player.MaxFireDelay,
range = player.TearRange,
tear_range = tearRange,
shot_speed = player.ShotSpeed,
luck = player.Luck,
tear_height = player.TearHeight,
tear_falling_speed = player.TearFallingSpeed,
can_fly = player.CanFly,
size = player.Size,
sprite_scale = player.SpriteScale.X,
}
end
return data
end
})
-- 玩家生命值 (实时检测,稍低频率)
CollectorRegistry:register("PLAYER_HEALTH", {
interval = "LOW",
priority = 8,
collect = function()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
data[i] = {
red_hearts = player:GetHearts(),
max_hearts = player:GetMaxHearts(),
soul_hearts = player:GetSoulHearts(),
black_hearts = player:GetBlackHearts(),
bone_hearts = player:GetBoneHearts(),
golden_hearts = player:GetGoldenHearts(),
eternal_hearts = player:GetEternalHearts(),
rotten_hearts = player:GetRottenHearts(),
broken_hearts = player:GetBrokenHearts(),
extra_lives = player:GetExtraLives(),
}
end
return data
end
})
-- 玩家物品栏 (低频采集)
CollectorRegistry:register("PLAYER_INVENTORY", {
interval = "RARE",
priority = 3,
collect = function()
local players = Helpers.getPlayers()
local data = {}
for i, player in ipairs(players) do
-- 基础资源(这些应该总是能获取到)
local playerData = {
-- 消耗品
coins = player:GetNumCoins(),
bombs = player:GetNumBombs(),
keys = player:GetNumKeys(),
-- 饰品
trinket_0 = player:GetTrinket(0),
trinket_1 = player:GetTrinket(1),
-- 卡牌/药丸
card_0 = player:GetCard(0),
pill_0 = player:GetPill(0),
-- 收集品总数
collectible_count = player:GetCollectibleCount(),
}
-- 收集物品(使用安全的固定上限)
local items = {}
local maxItemId = 733 -- Repentance 最大物品 ID(固定值避免常量问题)
-- 只在有收集品时才遍历
if playerData.collectible_count > 0 then
for itemId = 1, maxItemId do
-- 先用 HasCollectible 检查(更快)
if player:HasCollectible(itemId, true) then
local count = player:GetCollectibleNum(itemId, true)
if count > 0 then
items[tostring(itemId)] = count
end
end
end
end
playerData.collectibles = items
-- 主动道具槽位
local activeSlots = {}
for slot = 0, 3 do
local activeItem = player:GetActiveItem(slot)
if activeItem > 0 then
activeSlots[tostring(slot)] = {
item = activeItem,
charge = player:GetActiveCharge(slot),
max_charge = player:GetActiveMaxCharge(slot),
battery_charge = player:GetBatteryCharge(slot)
}
end
end
playerData.active_items = activeSlots
data[i] = playerData
end
return data
end
})
-- 敌人 (高频)
CollectorRegistry:register("ENEMIES", {
interval = "HIGH",
priority = 7,
collect = function()
local player = Isaac.GetPlayer(0)
if not player then return {} end
local playerPos = player.Position
local enemies = {}
for _, entity in ipairs(Isaac.GetRoomEntities()) do
if entity:IsActiveEnemy(false) and entity:IsVulnerableEnemy() then
local npc = entity:ToNPC()
local targetPos = {x = 0, y = 0}
if npc then
local target = npc:GetPlayerTarget()
if target then
targetPos = Helpers.vectorToTable(target.Position)
end
end
local dist = playerPos:Distance(entity.Position)
table.insert(enemies, {
id = entity.Index,
type = entity.Type,
variant = entity.Variant,
subtype = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
hp = entity.HitPoints,
max_hp = entity.MaxHitPoints,
is_boss = entity:IsBoss(),
is_champion = npc and npc:IsChampion() or false,
state = npc and npc.State or 0,
state_frame = npc and npc.StateFrame or 0,
projectile_cooldown = npc and npc.ProjectileCooldown or 0,
projectile_delay = npc and npc.ProjectileDelay or 0,
collision_radius = entity.Size,
distance = dist,
target_pos = targetPos,
v1 = npc and Helpers.vectorToTable(npc.V1) or {x=0, y=0},
v2 = npc and Helpers.vectorToTable(npc.V2) or {x=0, y=0},
})
end
end
return enemies
end
})
-- 投射物 (高频)
CollectorRegistry:register("PROJECTILES", {
interval = "HIGH",
priority = 9,
collect = function()
local player = Isaac.GetPlayer(0)
if not player then return {} end
local playerPos = player.Position
local data = {
enemy_projectiles = {},
player_tears = {},
lasers = {},
}
for _, entity in ipairs(Isaac.GetRoomEntities()) do
if entity.Type == EntityType.ENTITY_PROJECTILE then
local proj = entity:ToProjectile()
table.insert(data.enemy_projectiles, {
id = entity.Index,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
variant = entity.Variant,
collision_radius = entity.Size,
height = proj and proj.Height or 0,
falling_speed = proj and proj.FallingSpeed or 0,
falling_accel = proj and proj.FallingAccel or 0,
})
elseif entity.Type == EntityType.ENTITY_TEAR then
local tear = entity:ToTear()
local tearData = {
id = entity.Index,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
variant = entity.Variant,
collision_radius = entity.Size,
height = tear and tear.Height or 0,
scale = tear and tear.Scale or 1,
}
if entity.SpawnerType == EntityType.ENTITY_PLAYER then
table.insert(data.player_tears, tearData)
else
table.insert(data.enemy_projectiles, tearData)
end
elseif entity.Type == EntityType.ENTITY_LASER then
local laser = entity:ToLaser()
if laser then
table.insert(data.lasers, {
id = entity.Index,
pos = Helpers.vectorToTable(entity.Position),
angle = laser.Angle,
max_distance = laser.MaxDistance,
is_enemy = entity:IsEnemy(),
})
end
end
::continue::
end
return data
end
})
-- 房间信息 (中频 - 战斗中 is_clear 状态变化频繁)
CollectorRegistry:register("ROOM_INFO", {
interval = "LOW",
priority = 4,
collect = function()
local room = Helpers.getRoom()
local level = Helpers.getLevel()
if not room then return nil end
local tl = room:GetTopLeftPos()
local br = room:GetBottomRightPos()
local roomDesc = level:GetCurrentRoomDesc()
return {
room_type = room:GetType(),
room_shape = room:GetRoomShape(),
room_idx = level:GetCurrentRoomIndex(),
stage = level:GetStage(),
stage_type = level:GetStageType(),
difficulty = Game().Difficulty,
is_clear = room:IsClear(),
is_first_visit = room:IsFirstVisit(),
grid_width = room:GetGridWidth(),
grid_height = room:GetGridHeight(),
top_left = Helpers.vectorToTable(tl),
bottom_right = Helpers.vectorToTable(br),
has_boss = room:GetBossID() > 0,
enemy_count = room:GetAliveEnemiesCount(),
room_variant = roomDesc and roomDesc.Data and roomDesc.Data.Variant or 0,
}
end
})
-- 房间布局/障碍物 (变化时)
-- 采集所有 GridEntityType 枚举的实体 (ID 0-27)
-- Python端负责分类逻辑(可破坏物、障碍物、危险区域等)
CollectorRegistry:register("ROOM_LAYOUT", {
interval = "LOW",
priority = 2,
collect = function()
local room = Helpers.getRoom()
if not room then return nil end
local grid = {}
local doors = {}
local width = room:GetGridWidth()
-- GridEntityType 枚举常量 (参考游戏源码)
-- 0: NULL, 1: DECORATION, 2: ROCK, 3: ROCKB, 4: ROCKT, 5: ROCK_BOMB, 6: ROCK_ALT
-- 7: PIT, 8: SPIKES, 9: SPIKES_ONOFF, 10: SPIDERWEB, 11: LOCK, 12: TNT, 13: FIREPLACE (not used)
-- 14: POOP, 15: WALL, 16: DOOR, 17: TRAPDOOR, 18: STAIRS, 19: GRAVITY, 20: PRESSURE_PLATE
-- 21: STATUE, 22: ROCK_SS, 23: TELEPORTER, 24: PILLAR, 25: ROCK_SPIKED, 26: ROCK_ALT2, 27: ROCK_GOLD
for i = 0, room:GetGridSize() - 1 do
local gridEntity = room:GetGridEntity(i)
if gridEntity then
local gridType = gridEntity:GetType()
-- 收集所有 GridEntityType 枚举的实体 (0-27)
-- 排除: 13 (FIREPLACE - 已弃用,改用 ENTITY_EFFECT 处理)
-- 排除: 16 (DOOR - 门由 doors 单独处理)
-- 排除: 20 (PRESSURE_PLATE - 由 BUTTONS 通道单独处理)
if gridType >= 0 and gridType <= 27 and gridType ~= 13 and gridType ~= 16 and gridType ~= 20 then
local collision = gridEntity.CollisionClass
local variant = gridEntity:GetVariant()
local state = gridEntity.State
local pos = room:GetGridPosition(i)
-- 发送原始字段,Python端负责分类
grid[tostring(i)] = {
type = gridType, -- GridEntityType ID
variant = variant, -- 变体ID (0-255)
state = state, -- 状态值
collision = collision, -- 碰撞类型 (GridCollision)
x = pos.X, -- 世界坐标X
y = pos.Y, -- 世界坐标Y
}
end
end
end
for slot = 0, DoorSlot.NUM_DOOR_SLOTS - 1 do
local door = room:GetDoor(slot)
if door then
-- 获取门的世界坐标
local doorPos = door.Position
doors[tostring(slot)] = {
target_room = door.TargetRoomIndex,
target_room_type = door.TargetRoomType,
is_open = door:IsOpen(),
is_locked = door:IsLocked(),
x = doorPos.X,
y = doorPos.Y,
}
end
end
return {
grid = grid,
doors = doors,
grid_size = room:GetGridSize(),
width = width,
height = room:GetGridHeight(),
}
end
})
-- 炸弹 (中频)
CollectorRegistry:register("BOMBS", {
interval = "LOW",
priority = 5,
collect = function()
local player = Isaac.GetPlayer(0)
if not player then return {} end
local playerPos = player.Position
local bombs = {}
-- 炸弹变种类型定义
local BOMB_VARIANTS = {
[0] = "NORMAL", -- 普通炸弹
[1] = "BIG", -- 大型炸弹
[2] = "DECOY", -- 诱饵
[3] = "TROLL", -- 即爆炸弹
[4] = "MEGA_TROLL", -- 超级即爆炸弹
[5] = "POISON", -- 毒性炸弹
[6] = "BIG_POISON", -- 大型毒性炸弹
[7] = "SAD", -- 伤心炸弹
[8] = "HOT", -- 燃烧炸弹
[9] = "BUTT", -- 大便炸弹
[10] = "MR_MEGA", -- 大爆弹先生炸弹
[11] = "BOBBY", -- 波比炸弹
[12] = "GLITTER", -- 闪光炸弹
[13] = "THROWABLE", -- 可投掷炸弹
[14] = "SMALL", -- 小炸弹
[15] = "BRIMSTONE", -- 硫磺火炸弹
[16] = "BLOODY_SAD", -- 鲜血伤心炸弹
[17] = "GIGA", -- 巨型炸弹
[18] = "GOLDEN_TROLL", -- 金即爆炸弹
[19] = "ROCKET", -- 火箭
[20] = "GIGA_ROCKET", -- 巨型火箭
}
for _, entity in ipairs(Isaac.GetRoomEntities()) do
if entity.Type == EntityType.ENTITY_BOMB then
local variant = entity.Variant
local bomb = entity:ToBomb()
local dist = playerPos:Distance(entity.Position)
local bombType = BOMB_VARIANTS[variant] or ("UNKNOWN_" .. tostring(variant))
table.insert(bombs, {
id = entity.Index,
type = entity.Type,
variant = variant,
variant_name = bombType,
sub_type = entity.SubType,
pos = Helpers.vectorToTable(entity.Position),
vel = Helpers.vectorToTable(entity.Velocity),
explosion_radius = bomb and bomb.ExplosionRadius or 0,
timer = bomb and bomb.Timer or 0,
distance = dist,
})
end