screeps游戲 打接口

前置依賴(lài)+獲取當(dāng)前賬號(hào)x-token

let xToken
let updateXToken = ()=>{
    if(!xToken){
        let t = window.location.href
        window.location.href = t+"1"
        window.location.href = t
    }
}

if(!XMLHttpRequest.prototype._open){
    XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (...args) {
        return XMLHttpRequest.prototype._open.apply(this, args);
    };
    let responseHook = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, "response");
    let responseProcess = e=>e;
    responseProcess = e=>{return e};
    Object.defineProperty(XMLHttpRequest.prototype, "response", {
        get: function () {
            let response = responseHook.get.call(this);
            response=responseProcess(response)
            return response;
        },
        set: function (str) {
            return responseHook.set.call(this, str);
        },
        configurable: true,
    });
    let sendProcess = (req)=>{
        const oldOnreadystatechange = req.onreadystatechange
        req.onreadystatechange = function () {
            oldOnreadystatechange && oldOnreadystatechange(arguments)
            const headers = this.getAllResponseHeaders()
            let xt = headers.split("\n").filter(e=>e.indexOf("x-token")>=0)[0]
            // console.log(headers)
            if(xt){
                xt = xt.replace("x-token:","").trim()
                if(xt.length)xToken = xt
            }
        }
    };
    XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send
    XMLHttpRequest.prototype.send = function () {
        sendProcess(this);
        XMLHttpRequest.prototype._send.apply(this, arguments);
    }
    updateXToken();
}

let servers = {screeps: 'https://screeps.com'}
const $get = (path ,params, headers={}, server = 'screeps') => {
    const url = /http/.test(path) ? path : servers[server] + path
    return JSON.parse($.ajax({ url, params, method: 'get', headers ,async:false}).responseText)
}
const $post = (path, data = {}, headers = {}, server= 'screeps') => {
    data = JSON.stringify(data)
    const url = /http/.test(path) ? path : servers[server] + path
    return JSON.parse($.ajax({ url:url,contentType:"application/json;charset=UTF-8", dataType:'json', data:data, method: 'post', headers: headers ,async:false}).responseText)
}

查看某個(gè)人的全部資源

let player = "likeafox"
let id = $get("/api/user/find?username="+player, {}, { 'x-token': xToken }).user._id
let playerRooms = $get("/api/user/rooms?reservation&id="+id, {}, { 'x-token': xToken })
let addStore = (store,b)=> {for(let v in b) if(b[v]>0)store[v]=(store[v]||0)+b[v];return store}
let all = {}
Object.keys(playerRooms.shards).forEach(shard=>{
    playerRooms.shards[shard].forEach(rn=>{
        let room = $get("/api/game/room-objects?room="+rn+"&shard="+shard, {}, { 'x-token': xToken })
        let storages = room.objects.filter(e=>e.type=="storage"||e.type=="terminal"||e.type=="factory")
        storages.forEach(e=>addStore(all,e.store))
        // console.log(storages.map(e=>e))
    })
})
all

自動(dòng)上背景貼紙(墻壁浙值、地板)

let id = $get("/api/auth/me", {}, { 'x-token': xToken })._id;
let invs = $get("/api/user/decorations/inventory", {}, { 'x-token': xToken }).list;
let playerRooms = $get("/api/user/rooms?reservation&id="+id, {}, { 'x-token': xToken });
["wallLandscape","floorLandscape"].forEach(type=>{
    let vis = invs.filter(e=>e.active&&e.decoration.rarity==3&&e.decoration.type==type).map(e=>e.active.shard+"_"+e.active.room)
    let needs = Object.keys(playerRooms.reservations).map(shard=> playerRooms.reservations[shard].map(rn=>[shard,rn])).flat().filter(e=>vis.indexOf(e[0]+"_"+e[1])==-1)
    let inv = invs.filter(e=>!e.active&&e.decoration.rarity==3&&e.decoration.type==type)
    console.log(inv,needs,_.zip(inv,needs))
    _.zip(inv,_.shuffle(needs)).filter(e=>e[0]&&e[1]).forEach(a=>{
        let active = {}
        if(!a[0].decoration)console.log(a[0])
        Object.keys(a[0].decoration.props).forEach(e=>{
            active[e]=a[0].decoration.props[e].default
        })
        active.shard=a[1][0]
        active.room=a[1][1]
        let data = {_id:a[0]._id,active:active}
        console.log(data)
        console.log($post("/api/user/decorations/activate", data, { 'x-token': xToken}))
    })
})

自動(dòng)上Creep皮膚

let id = $get("/api/auth/me", {}, { 'x-token': xToken })._id;
let invs = $get("/api/user/decorations/inventory", {}, { 'x-token': xToken }).list;
let avoid = new Set(["C-00127:CC:Y","C-00071:CC:X","C-00227:CC:Y","C-00160:CC:X","C-00024:DE:A","C-00096:CC:X","C-00226:CC:X","C-00103:CC:Y","C-00098:CC:X"])
let creepSkins = invs.filter(e=>e.decoration.type=="creep"&&e.active&&!avoid.has(e.decoration.name))
let getNameFilter = (n)=>{
    let base36 = Math.pow(36,2)
    let randomId = ()=>_.padLeft(Math.ceil(Math.random()*base36).toString(36).toLocaleUpperCase(),2,"0")
    let result = ""
    let set = new Set()
    for(let i=0;i<n;i++){
        let p = randomId()
        if(set.has(p)) i-=1
        else{
            if(i>0)result+="!SEP!"
            set.add(p)
            result+=p
        }
    }
    return result
}
creepSkins.forEach(e=>{
    e.active.nameFilter = getNameFilter(18)
    e.active.exclude = false
    let data = {_id:e._id,active:e.active}
    console.log(data)
    console.log($post("/api/user/decorations/deactivate", {decorations:[e._id]}, { 'x-token': xToken}))
    console.log($post("/api/user/decorations/activate", data, { 'x-token': xToken}))
})

對(duì)應(yīng)的creep的名字生成原理

let base36 = Math.pow(36,10)
randomId = ()=>_.padLeft(Math.ceil(Math.random()*base36).toString(36).toLocaleUpperCase(),10,"0")

自動(dòng)上貼紙


/**
 * 全自動(dòng)上1-3級(jí)貼圖
 * 會(huì)檢測(cè)已有的貼圖不會(huì)重疊
 * 默認(rèn)按位置大小從大到小先放置(全局)
 * 控制臺(tái)會(huì)輸出貼圖位置
 * 如果上錯(cuò)了涯保,可以按日期來(lái)取消貼圖
 */

let getRoomTerrain = (shard,room)=>Array(...$get("/api/game/room-terrain?room="+room+"&shard="+shard+"&encoded=1", {}, { 'x-token': xToken }).terrain[0].terrain);
let id = $get("/api/auth/me", {}, { 'x-token': xToken })._id;
let playerRooms = $get("/api/user/rooms?reservation&id="+id, {}, { 'x-token': xToken });
let invs =()=> $get("/api/user/decorations/inventory", {}, { 'x-token': xToken }).list;
let items = ()=> invs().filter(e=>!e.active&&e.decoration.rarity<=3&&e.decoration.type=="wallGraffiti")
let active_item = ()=> invs().filter(e=>e.active&&e.decoration.type=="wallGraffiti")
let roomDpStr=(terr)=>{let str = "";for(let x=0;x<50;x++){for(let y=0;y<50;y++) {let p = terr[x*50+y];str+=(p>0?p:" ")+" "}str+="\n"}return str}
let roomTerrStr=(terr)=>{let str = "";for(let x=0;x<50;x++){for(let y=0;y<50;y++) {let p = terr[x*50+y];if(p==0||p>=4)str+=" █???/".charAt(p);str+=" █???/".charAt(p)}str+="\n"}return str}
let clearTerr=(terr,xx,yy,h,w,n)=>{for(let x=0;x<h;x++){for(let y=0;y<w;y++){terr[parseInt(xx-x)*50+parseInt(yy-y)]=n}}}

let dpRoom = (terr)=>{
    let arr = []
    for(let i=0;i<50;i++){for(let j=0;j<50;j++) {
        let cur = 1;
        let left = i>0?arr[i*50-50+j]:0;
        let top = j>0?arr[i*50+j-1]:0;
        let left_top = (j>0&&i>0)?arr[i*50+j-51]:0;
        cur=Math.min(left+1,top+1,left_top+1)
        if(terr[i*50+j]!="1")cur = 0
        arr.push(cur)
    }}
    return arr
}

let avoidSize = 9;// 超過(guò)多大的空間不給放,用來(lái)放 紫色和金色的
let rooms = Object.keys(playerRooms.shards).flatMap(shard=>playerRooms.shards[shard].map(e=>[shard,e]))
rooms.forEach(roomCur=>{
// let roomCur = ["shard2","E56S29"]
// let roomCur = ['shard2', 'E54S28']
    let roomCurItems = active_item().filter(e=>e.active&&e.active.shard==roomCur[0]&&e.active.room==roomCur[1])
    let terrain = getRoomTerrain (...roomCur)
    roomCurItems.forEach(e=>{for(let x=0;x<e.active.height;x++){for(let y=0;y<e.active.width;y++){terrain[parseInt(e.active.y+x)*50+parseInt(e.active.x+y)]=4}}})
    let dp = dpRoom(terrain)
    if (dp.filter(e => e >= avoidSize).length) {
        dp.forEach((e,i)=>{
            if(e<avoidSize)return;
            clearTerr(terrain,i/50,i%50,e,e,5)
        })
        console.log("https://screeps.com/a/#!/room/"+roomCur.join("/"))
        console.log("%c"+roomTerrStr(terrain),"font-family: Monospace;")
    }
    roomCur.push(terrain)
    roomCur.push(Math.max(...dpRoom(terrain)))
})

let minSize = 5;
Array.prototype.randomGet= function(){return this[Math.floor(this.length*Math.random())]};
let tryCnt = items().length
let activeId = []
while(tryCnt>0){tryCnt--;
    let maxRoom = Math.max(...rooms.map(e=>e[3]))
    let roomCur = rooms.filter(e=>e[3]==maxRoom).randomGet()
    let roomCurItems = active_item().filter(e=>e.active&&e.active.shard==roomCur[0]&&e.active.room==roomCur[1])
    let terrain = roomCur[2]
    roomCurItems.forEach(e=>{for(let x=0;x<e.active.height;x++){for(let y=0;y<e.active.width;y++){terrain[parseInt(e.active.y+x)*50+parseInt(e.active.x+y)]=4}}})
    let dp = dpRoom(terrain)
    let max = Math.max(...dp)
    let pos = dp.map((e,i)=>[e,i]).filter(e=>e[0]>=minSize&&e[0]==max).randomGet()
    if(!pos)break;
    clearTerr(terrain,pos[1]/50,pos[1]%50,pos[0],pos[0],5)
    console.log("%c"+roomTerrStr(terrain),"font-family: Monospace;")
    roomCur[3]=Math.max(...dpRoom(terrain))

    let it = items().randomGet();
    it.active={}
    Object.keys(it.decoration.props).forEach(e=>{
        it.active[e]=it.decoration.props[e].default
    })
    it.active.x = pos[1]%50-pos[0]+1
    it.active.y = Math.floor(pos[1]/50)-pos[0]+1
    it.active.height=pos[0]
    it.active.width=pos[0]
    it.active.shard=roomCur[0]
    it.active.room=roomCur[1]
    activeId.push(it._id)
    let data = {_id:it._id,active:it.active}
    console.log($post("/api/user/decorations/activate", data, { 'x-token': xToken}))
}
image.png

creeps 死亡情況




const CHAR_0 = '0'.charCodeAt(0)
const MAP_DIRECT = {E:1,N:-1,W:-1,S:1} //東西南北坐標(biāo)
const MAP_OFFSET = {E:0,N:-1,W:-1,S:0} //東西南北坐標(biāo)

let getRoomCoordinate = function (roomName) {
    let tmp={x:0,y:0}
    let sh = 0;
    let pow = 1;
    for(let i=roomName.length-1;i>=0;i--){
        let cc = roomName.charCodeAt(i)-CHAR_0;
        if(cc>=0&&cc<=9){
            if(sh==0){
                tmp.y+=cc*pow
            }else{
                tmp.x+=cc*pow
            }
            pow*=10;
        }else{
            let c = roomName[i];
            if(sh==0){
                tmp.y*=MAP_DIRECT[c]
                tmp.y+=MAP_OFFSET[c]
            }else{
                tmp.x*=MAP_DIRECT[c]
                tmp.x+=MAP_OFFSET[c]
            }
            pow = 1
            sh+=1
        }
    }
    return tmp
}

function getRoomNameByXY (x,y) {
    if(x.x){
        y=x.y
        x=x.x
    }
    return `${x >= 0 ? "E" : "W"}${x >= 0 ? x : -1 - x}${y >= 0 ? "S" : "N"}${y >= 0 ? y : -1 - y}`;
}
function isHighWay(roomName){
    let cnt=0
    for(let i=roomName.length-1;i>=0;i--) {
        if (roomName.charCodeAt(i) == CHAR_0) {
            cnt+=1
        }
    }
    return cnt>=1
}

// let id = $get("/api/user/find?username=Tigga", {}, { 'x-token': xToken }).user._id
let id = $get("/api/auth/me", {}, { 'x-token': xToken })._id;
let playerRooms = $get("/api/user/rooms?reservation&id="+id, {}, { 'x-token': xToken });

function isMyRoom(shard,roomName){
    return playerRooms.reservations[shard].concat(playerRooms.shards[shard]).filter(e=>e==roomName).length!=0
}

// let stateName = "creepsLost"+180
let stateName = "creepsLost"+1440
playerRooms
let allDead = Object.keys(playerRooms.shards).map(shard=> {
    let allRooms = playerRooms.reservations[shard].concat(playerRooms.shards[shard])
    let myRemoterRooms =  Array.from(new Set(allRooms.map(getRoomCoordinate).map(pos=>{
        let arr = []
        for(let i=-10;i<=10;i++){
            for(let j=-10;j<=10;j++) {
                arr.push({
                    x:pos.x+i,
                    y:pos.y+j,
                })
            }
        }
        return arr
    }).flat().map(getRoomNameByXY)))
    let data =  $post("/api/game/map-stats", {rooms:myRemoterRooms,shard:shard,statName: stateName}, { 'x-token': xToken });
    return Object.entries(data.stats).map(e=>{e[1].shard = shard;e[1].roomName = e[0];return e[1];})
}).flat().filter(e=>e[stateName]).filter(e=>e[stateName].filter(t=>t.user==id).length).flat().map(e=>{
    return [e.shard,e.roomName,e[stateName].filter(t=>t.user==id)[0].value]
}).sort((a,b)=>b[2]-a[2])
    // .map(e=>e.value).reduce((a,b)=>a+b,0)

console.log("過(guò)道死亡:"+allDead.filter(e=>isHighWay(e[1])).map(e=>e[2]).reduce((a,b)=>a+b,0))
console.log("外礦死亡:"+allDead.filter(e=>isMyRoom(e[0],e[1])).map(e=>e[2]).reduce((a,b)=>a+b,0))
console.log("其他死亡:"+allDead.filter(e=>!isHighWay(e[1])&&!isMyRoom(e[0],e[1])).map(e=>e[2]).reduce((a,b)=>a+b,0))

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末埋酬,一起剝皮案震驚了整個(gè)濱河市摆昧,隨后出現(xiàn)的幾起案子苫拍,更是在濱河造成了極大的恐慌,老刑警劉巖鳍咱,帶你破解...
    沈念sama閱讀 206,482評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異与柑,居然都是意外死亡谤辜,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)价捧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)丑念,“玉大人,你說(shuō)我怎么就攤上這事结蟋「校” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,762評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵嵌屎,是天一觀的道長(zhǎng)推正。 經(jīng)常有香客問(wèn)我,道長(zhǎng)宝惰,這世上最難降的妖魔是什么植榕? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,273評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮尼夺,結(jié)果婚禮上内贮,老公的妹妹穿的比我還像新娘。我一直安慰自己汞斧,他們只是感情好夜郁,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,289評(píng)論 5 373
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著粘勒,像睡著了一般竞端。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上庙睡,一...
    開(kāi)封第一講書(shū)人閱讀 49,046評(píng)論 1 285
  • 那天事富,我揣著相機(jī)與錄音,去河邊找鬼乘陪。 笑死统台,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的啡邑。 我是一名探鬼主播贱勃,決...
    沈念sama閱讀 38,351評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了贵扰?” 一聲冷哼從身側(cè)響起仇穗,我...
    開(kāi)封第一講書(shū)人閱讀 36,988評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎戚绕,沒(méi)想到半個(gè)月后纹坐,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,476評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡舞丛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,948評(píng)論 2 324
  • 正文 我和宋清朗相戀三年耘子,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片球切。...
    茶點(diǎn)故事閱讀 38,064評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡谷誓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出欧聘,到底是詐尸還是另有隱情片林,我是刑警寧澤,帶...
    沈念sama閱讀 33,712評(píng)論 4 323
  • 正文 年R本政府宣布怀骤,位于F島的核電站费封,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蒋伦。R本人自食惡果不足惜弓摘,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,261評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望痕届。 院中可真熱鬧韧献,春花似錦、人聲如沸研叫。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,264評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)嚷炉。三九已至渊啰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間申屹,已是汗流浹背绘证。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,486評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留哗讥,地道東北人嚷那。 一個(gè)月前我還...
    沈念sama閱讀 45,511評(píng)論 2 354
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像杆煞,于是被迫代替她去往敵國(guó)和親魏宽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子腐泻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,802評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容