前言
在screeps游戏中,你可能有这样的疑问,我想让别人打我,但是一个一个发消息太慢了,作为程序员,我们得想办法偷懒。
于是你在github上找到了screeps游戏的接口文档
思路
批量发送消息的思路很简单,你先选定一个房间,然后获取周围一定范围内的玩家id,据此就可以给对方发送消息。
源码
const baseURL = "https://screeps.com/api";
const token = "你的token";
// 获取地图数据
async function getMapStats(rooms, shard = "shard3") {
const response = await fetch(`${baseURL}/game/map-stats`, {
method: "POST",
body: JSON.stringify({
rooms,
shard,
statName: "owner0",
}),
headers: {
"Content-Type": "application/json",
"X-Token": token,
},
});
return response.json();
}
// 发送消息
async function sendMessage(respondent, text = "Hello Screeps") {
const response = await fetch(`${baseURL}/user/messages/send`, {
method: "POST",
body: JSON.stringify({
respondent,
text,
}),
headers: {
"Content-Type": "application/json",
"X-Token": token,
},
});
return response.json();
}
const roomNameToXY = (roomName) => {
// 解析房间名
const parse = roomName.match(/([EW])(\d+)([NS])(\d+)/);
const x = parse[1] === "W" ? ~parseInt(parse[2]) : parseInt(parse[2]);
const y = parse[3] === "N" ? ~parseInt(parse[4]) : parseInt(parse[4]);
return {
x,
y,
};
};
const xyToRoomName = (x, y) => {
return (x < 0 ? "W" + ~x : "E" + x) + (y < 0 ? "N" + ~y : "S" + y);
};
const isHighWayRoom = (roomName) => {
return roomName.includes("0");
};
// 给一个房间周围20格内的玩家发送消息
function autoSendMessage(
roomName,
message = "Can u respawn",
shard = "shard3",
range = 20
) {
const { x, y } = roomNameToXY(roomName);
const rooms = [];
for (let i = -range; i <= range; i++) {
for (let j = -range; j <= range; j++) {
const room = xyToRoomName(x + i, y + j);
if (isHighWayRoom(room)) continue;
rooms.push(room);
}
}
getMapStats(rooms, shard).then((data) => {
if (!data.ok) return;
const users = data.users;
for (const user in users) {
sendMessage(user, message);
}
});
}
使用
在源码第二行换上你的token,然后调用autoSendMessage函数即可,注意该函数传参。