-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmemory.visualizer.js
More file actions
367 lines (300 loc) · 10.4 KB
/
Copy pathmemory.visualizer.js
File metadata and controls
367 lines (300 loc) · 10.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
/**
* Memory Visualizer - メモリを視覚化する楽しいシステム
*/
const utilsMemory = require('./utils.memory');
const cache = require('./src/utils/cache');
/**
* セキュリティ: メモリDoSを防ぐためのメモリ消費構造の制限。
* Screepsのメモリは2MBに制限されており、制限のないオブジェクトはAIをクラッシュさせる可能性があります。
*/
const MAX_EXPLORED_ROOMS = 100;
const MAX_ROOM_DATA = 50;
const MAX_DIARY_MESSAGE_LENGTH = 200;
const MAX_LEADERBOARD_ENTRIES = 50;
const MAX_LEADERBOARD_TYPES = 10;
const memoryVisualizer = {
/**
* メモリ全体の統計を表示
*/
showStats: function () {
const stats = {
totalSize: JSON.stringify(Memory).length,
creeps: Object.keys(Memory.creeps || {}).length,
rooms: Object.keys(Memory.rooms || {}).length,
flags: Object.keys(Memory.flags || {}).length,
spawns: Object.keys(Memory.spawns || {}).length,
};
console.log(`Total Size: ${(stats.totalSize / 1024).toFixed(2)} KB`);
return stats;
},
/**
* メモリの大きい順にソート表示
*/
showTopMemoryUsers: function (limit = 10) {
const sizes = [];
for (const name in Memory.creeps) {
if (
utilsMemory.isSafeKey(name) &&
Object.prototype.hasOwnProperty.call(Memory.creeps, name)
) {
sizes.push({
type: 'creep',
name,
size: JSON.stringify(Memory.creeps[name]).length,
});
}
}
for (const name in Memory.rooms) {
if (
utilsMemory.isSafeKey(name) &&
Object.prototype.hasOwnProperty.call(Memory.rooms, name)
) {
sizes.push({
type: 'room',
name,
size: JSON.stringify(Memory.rooms[name]).length,
});
}
}
sizes.sort((a, b) => b.size - a.size);
const slicedSizes = sizes.slice(0, limit);
slicedSizes.forEach((item, index) => {
console.log(`- ${item.type} ${item.name}: ${(item.size / 1024).toFixed(2)} KB`);
});
return slicedSizes;
},
/**
* メモリタイムマシン
*/
initTimeMachine: function () {
if (!Memory.timeMachine) {
Memory.timeMachine = {
snapshots: [],
maxSnapshots: 100,
enabled: true,
};
}
},
recordSnapshot: function () {
this.initTimeMachine();
if (!Memory.timeMachine.enabled) {
return;
}
const snapshot = {
time: Game.time,
gcl: Game.gcl.level,
cpu: Game.cpu.getUsed(),
bucket: Game.cpu.bucket,
creeps: Object.keys(Game.creeps).length,
energy: Object.values(Game.rooms).reduce((sum, room) => {
return sum + (room.energyAvailable || 0);
}, 0),
};
Memory.timeMachine.snapshots.push(snapshot);
if (Memory.timeMachine.snapshots.length > Memory.timeMachine.maxSnapshots) {
Memory.timeMachine.snapshots.shift();
}
},
showHistory: function (ticks = 10) {
this.initTimeMachine();
const snapshots = Memory.timeMachine.snapshots.slice(-ticks);
console.log(`History (last ${snapshots.length} ticks):`);
snapshots.forEach((snap) => {
console.log(`[${snap.time}] CPU=${snap.cpu.toFixed(2)}, Bucket=${snap.bucket}, Creeps=${snap.creeps}, Energy=${snap.energy}`);
});
return snapshots;
},
/**
* メモリリーダーボード
*/
initLeaderboard: function () {
if (!Memory.leaderboard) {
Memory.leaderboard = {
harvested: {},
built: {},
upgraded: {},
repaired: {},
distance: {},
};
}
},
recordAchievement: function (creepName, type, amount) {
this.initLeaderboard();
// セキュリティ: プロトタイプ汚染とデータ破損を防ぐための入力バリデーション
if (!utilsMemory.isSafeKey(creepName) || !utilsMemory.isSafeKey(type)) {
return;
}
// セキュリティ: メモリ破損/NaNを防ぐため、amountが有効な数値であることを確認
const numericAmount = Number(amount);
if (!Number.isFinite(numericAmount)) {
return;
}
if (!Memory.leaderboard[type]) {
// セキュリティ: メモリDoSを防ぐため、リーダーボードのタイプ数を制限
if (Object.keys(Memory.leaderboard).length >= MAX_LEADERBOARD_TYPES) {
return;
}
Memory.leaderboard[type] = {};
}
const board = Memory.leaderboard[type];
// セキュリティ: メモリDoSを防ぐため、リーダーボードあたりのエントリ数を制限
if (!board[creepName] && Object.keys(board).length >= MAX_LEADERBOARD_ENTRIES) {
// 追い出しポリシー: 最も低いスコアのエントリを削除
const lowestEntry = Object.entries(board).sort((a, b) => a[1] - b[1])[0];
if (lowestEntry && numericAmount > lowestEntry[1]) {
delete board[lowestEntry[0]];
} else if (!lowestEntry || numericAmount <= (lowestEntry[1] || 0)) {
// If the new score is not better than the lowest, don't add it
return;
}
}
if (!board[creepName]) {
board[creepName] = 0;
}
board[creepName] += numericAmount;
},
showLeaderboard: function (type = 'harvested', limit = 10) {
this.initLeaderboard();
const board = Memory.leaderboard[type] || {};
const sorted = Object.entries(board)
.sort((a, b) => b[1] - a[1])
.slice(0, limit);
sorted.forEach((entry, index) => {
const medal = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : ' ';
console.log(`${medal} ${entry[0]}: ${entry[1]}`);
});
return sorted;
},
/**
* Creep日記
*/
initDiary: function (creepName) {
// Security: Validate creepName to prevent prototype pollution
if (!utilsMemory.isSafeKey(creepName) || !Memory.creeps[creepName]) {
return;
}
if (!Memory.creeps[creepName]?.diary) {
Memory.creeps[creepName].diary = {
entries: [],
maxEntries: 20,
};
}
},
addDiaryEntry: function (creepName, message) {
// Security: Validate creepName to prevent prototype pollution
if (!utilsMemory.isSafeKey(creepName)) {
return;
}
this.initDiary(creepName);
if (!Memory.creeps[creepName]?.diary) {
return;
}
// Security: Truncate message to avoid Memory DoS
const sanitizedMessage = String(message).substring(0, MAX_DIARY_MESSAGE_LENGTH);
const entry = {
time: Game.time,
message: sanitizedMessage,
};
Memory.creeps[creepName].diary.entries.push(entry);
const diary = Memory.creeps[creepName].diary;
if (diary.entries.length > diary.maxEntries) {
diary.entries.shift();
}
},
readDiary: function (creepName) {
// Security: Validate creepName to prevent prototype pollution
if (!utilsMemory.isSafeKey(creepName) || !Memory.creeps[creepName]?.diary) {
return [];
}
const diary = Memory.creeps[creepName].diary;
diary.entries.forEach((entry) => {
console.log(`[${entry.time}] ${entry.message}`);
});
return diary.entries;
},
/**
* メモリマップ
*/
initMemoryMap: function () {
if (!Memory.map) {
Memory.map = {
rooms: {},
explored: [],
};
}
},
/**
* メモリクリーナー
*/
cleanup: function () {
let cleaned = 0;
cleaned += utilsMemory.cleanMemory();
if (Memory.flags) {
for (const name in Memory.flags) {
if (
utilsMemory.isSafeKey(name) &&
Object.prototype.hasOwnProperty.call(Memory.flags, name) &&
!Game.flags[name]
) {
delete Memory.flags[name];
cleaned++;
}
}
}
if (Memory.map?.rooms) {
for (const roomName in Memory.map.rooms) {
if (
utilsMemory.isSafeKey(roomName) &&
Object.prototype.hasOwnProperty.call(Memory.map.rooms, roomName)
) {
const lastVisit = Memory.map.rooms[roomName].lastVisit;
if (Game.time - lastVisit > 1000) {
delete Memory.map.rooms[roomName];
cleaned++;
}
}
}
}
return cleaned;
},
/**
* メモリバックアップ
*/
backup: function () {
if (!Memory.backups) {
Memory.backups = [];
}
const memoryClone = { ...Memory };
delete memoryClone.backups;
const backup = {
time: Game.time,
data: JSON.parse(JSON.stringify(memoryClone)),
};
Memory.backups.push(backup);
if (Memory.backups.length > 5) {
Memory.backups.shift();
}
// log backup saved
},
restore: function (index = 0) {
if (!Memory.backups || Memory.backups.length === 0) {
return false;
}
const backup = Memory.backups[index];
if (backup === undefined || backup === null) {
return false;
}
const backups = Memory.backups;
for (const key in Memory) {
delete Memory[key];
}
for (const key in backup.data) {
if (utilsMemory.isSafeKey(key)) {
Memory[key] = backup.data[key];
}
}
Memory.backups = backups;
return true;
},
};
module.exports = memoryVisualizer;