Skip to content

Commit 1bc2512

Browse files
- cleanup pixel code, sell PIXELs
- buyEnergy if we have terminals and storage, mineral creeps should move energy to storage for builders and upgrader sell PR TooAngel#703 - fixed quests.js for incoming transactions
1 parent e964728 commit 1bc2512

File tree

6 files changed

+150
-38
lines changed

6 files changed

+150
-38
lines changed

src/brain_main.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
const {checkPlayers} = require('./diplomacy');
44
const {handleQuests} = require('./quests');
55
const {prepareMemory} = require('./brain_memory');
6+
const {handlePixel} = require('./brain_pixel');
67

78
global.cpuUsed = 0;
89

@@ -86,6 +87,9 @@ module.exports.execute = function() {
8687
try {
8788
prepareMemory();
8889
brain.buyPower();
90+
if (config.pixel.enabled && Game.cpu.generatePixel) {
91+
handlePixel();
92+
}
8993
brain.handleNextroomer();
9094
brain.handleSquadManager();
9195
brain.handleIncomingTransactions();
@@ -104,7 +108,7 @@ module.exports.execute = function() {
104108
});
105109

106110
if (global.config.tickSummary.gcl) {
107-
console.log(`${Game.time} GCL ${Game.gcl.level}: ${global.utils.leftPadRound(Game.gcl.progress/Game.gcl.progressTotal*100, 3, 5)} % ${Math.round(Game.gcl.progress)}/${Math.round(Game.gcl.progressTotal)}`);
111+
console.log(`${Game.time} GCL ${Game.gcl.level}: ${global.utils.leftPadRound(Game.gcl.progress / Game.gcl.progressTotal * 100, 3, 5)} % ${Math.round(Game.gcl.progress)}/${Math.round(Game.gcl.progressTotal)}`);
108112
}
109113
if (global.config.tickSummary.bucket) {
110114
console.log(`${Game.time} Bucket: ${Game.cpu.bucket}`);

src/brain_pixel.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'use strict';
2+
3+
const {debugLog} = require('./logging');
4+
const pixelLog = (message) => {
5+
debugLog('pixel', message);
6+
}
7+
8+
module.exports.handlePixel = function() {
9+
if (typeof PIXEL !== 'undefined') {
10+
// generate PIXEL
11+
if (Game.cpu.bucket >= PIXEL_CPU_COST + config.pixel.minBucketAfter) {
12+
global.load = Math.round(Game.cpu.getUsed());
13+
Game.cpu.generatePixel();
14+
const pixel = Game.resources[PIXEL] || ""
15+
const deltaPixel = Game.time - (global.data.pixel || 0)
16+
pixelLog(`PIXEL generated!\tCurrent ${pixel + 1}\t delta: ${deltaPixel} \t load: ${global.load}`)
17+
global.data.pixel = Game.time;
18+
}
19+
20+
// sell PIXEL, make money to buy energy
21+
if (config.pixel.sell && Game.resources[PIXEL] > config.pixel.minPixelAmount) {
22+
const buyOrder = _.sortBy(Game.market.getAllOrders({type: "buy", resourceType: PIXEL}), (o) => -o.price)[0];
23+
if (buyOrder) {
24+
const history = Game.market.getHistory(PIXEL);
25+
const lastDay = history[history.length - 1];
26+
if (lastDay) {
27+
const minPriceToSell = (lastDay.avgPrice - (config.pixel.allowedSalesHistoryDeviation * lastDay.stddevPrice)).toPrecision(3);
28+
if (buyOrder.price >= minPriceToSell) {
29+
pixelLog(`PIXEL pices: ${buyOrder.price}\tamount: ${buyOrder.amount}\tlastDay.avgPrice: ${lastDay.avgPrice}\tlastDay.stddevPrice: ${lastDay.stddevPrice}\tminPrice: ${minPriceToSell}`)
30+
const amount = Math.min(buyOrder.amount, Game.resources[PIXEL] - config.pixel.minPixelAmount);
31+
Game.market.deal(buyOrder.id, amount);
32+
pixelLog(`PIXEL sold!\t${buyOrder.price} @ ${amount}`)
33+
}
34+
}
35+
} else {
36+
pixelLog(`PIXEL has no bestOrder ${buyOrder}`)
37+
}
38+
}
39+
}
40+
}

src/config.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ global.config = {
152152

153153
pixel: {
154154
enabled: false,
155+
sell: true,
156+
allowedSalesHistoryDeviation: 0.05,
157+
minPixelAmount: 500,
155158
minBucketAfter: 2500,
156159
},
157160

@@ -289,11 +292,15 @@ global.config = {
289292
maxBuyPrice: 0.5,
290293
// buyByOwnOrders: true,
291294
buyOrderPriceMultiplicand: 0.5,
292-
295+
// buy energy, let make use of our credits
296+
buyEnergy: {
297+
enabled: true,
298+
allowedSalesHistoryDeviation: 0.05,
299+
},
293300
// buy power if we have more credits than config.market.minCredits
294301
buyPower: false,
295-
// 300M credits
296-
minCredits: 300000000,
302+
// 300K credits
303+
minCredits: 300000,
297304
// disable to use power only in gathered room
298305
sendPowerOwnRoom: true,
299306
// equalizes the energy between your rooms via terminal

src/main.js

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,7 @@ module.exports.loop = function() {
3939
execute();
4040
}
4141
}
42-
if (global.config.pixel.enabled) {
43-
if (typeof PIXEL !== 'undefined') {
44-
if (Game.cpu.bucket >= PIXEL_CPU_COST + global.config.pixel.minBucketAfter) {
45-
Game.cpu.generatePixel();
46-
}
47-
}
48-
}
42+
4943
brain.stats.updateCpuStats();
5044

5145
if (config.resourceStats) {

src/prototype_room_market.js

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Room.prototype.sellByOwnOrders = function(resource, sellAmount) {
3434

3535
Room.prototype.sellByOthersOrders = function(sellAmount, resource, force) {
3636
const sortByEnergyCostAndPrice = (order) => Game.market.calcTransactionCost(sellAmount, this.name, order.roomName) +
37-
-order.price * sellAmount / config.market.energyCreditEquivalent;
37+
-order.price * sellAmount / config.market.energyCreditEquivalent;
3838
if (Memory.orders[ORDER_BUY][resource]) {
3939
const orders = _.sortBy(Memory.orders[ORDER_BUY][resource].orders, sortByEnergyCostAndPrice);
4040
for (const order of orders) {
@@ -194,7 +194,7 @@ Room.prototype.sendEnergyToMyRooms = function() {
194194
const myRoom = _.shuffle(Memory.needEnergyRooms)[0];
195195
const room = Game.rooms[myRoom];
196196
if (!room) {
197-
Memory.needEnergyRooms.splice( Memory.needEnergyRooms.indexOf(myRoom), 1 );
197+
Memory.needEnergyRooms.splice(Memory.needEnergyRooms.indexOf(myRoom), 1);
198198
return;
199199
}
200200
const amount = this.sendEnergyAmountToMyRoom();
@@ -213,13 +213,66 @@ Room.prototype.sendEnergyToMyRooms = function() {
213213
return false;
214214
};
215215

216+
/**
217+
* make use of the credits we earn from selling PIXEL
218+
*
219+
* @returns {ERR_NOT_FOUND|boolean}
220+
*/
221+
Room.prototype.buyEnergy = function() {
222+
if (!this.isRoomReadyForMineralHandling()) {
223+
this.debugLog('market', 'not ReadyForMineralHandling')
224+
return false;
225+
}
226+
if (!config.market.buyEnergy || Game.market.credits < config.market.minCredits || (this.terminal.cooldown > 0)) {
227+
this.debugLog('market', 'config cooldown or no credits')
228+
return false;
229+
}
230+
// todo maybe use this.getEnergy()
231+
const energyInRoom = (this.terminal.store.getUsedCapacity(RESOURCE_ENERGY) + this.storage.store.getUsedCapacity(RESOURCE_ENERGY))
232+
if (energyInRoom > (config.terminal.maxEnergyAmount + config.terminal.minEnergyAmount)) {
233+
this.debugLog('market', 'room has energy')
234+
return false;
235+
}
236+
try {
237+
this.data.allowedSalesHistoryDeviation = this.data.allowedSalesHistoryDeviation || config.market.buyEnergy.allowedSalesHistoryDeviation;
238+
const filterOrders = {type: ORDER_SELL, resourceType: RESOURCE_ENERGY};
239+
const sellOrder = _.sortBy(Game.market.getAllOrders(filterOrders), (o) => o.price)[0];
240+
if (sellOrder) {
241+
const history = Game.market.getHistory(RESOURCE_ENERGY);
242+
const lastDay = history[history.length - 1];
243+
if (lastDay) {
244+
const maxPrice = parseFloat('' + (lastDay.avgPrice + (this.data.allowedSalesHistoryDeviation * lastDay.stddevPrice))).toPrecision(4);
245+
this.debugLog('market', `maxPrice ${maxPrice}\t${lastDay.avgPrice} + (${allowedSalesHistoryDeviation} * ${lastDay.stddevPrice})`)
246+
if (sellOrder.price <= maxPrice) {
247+
const amount = Math.min(config.terminal.minEnergyAmount, sellOrder.amount, this.terminal.store.getFreeCapacity())
248+
const returnCode = Game.market.deal(sellOrder.id, amount, this.name);
249+
this.debugLog('market', 'market.deal:', sellOrder.id, amount, this.name);
250+
if (returnCode === OK) {
251+
return true;
252+
} else if (![ERR_TIRED, ERR_NOT_ENOUGH_RESOURCES].indexOf(returnCode)) {
253+
this.debugLog('market', `market.deal: ${returnCode}`);
254+
return false;
255+
}
256+
}
257+
}
258+
}
259+
// no orders found, next time check for low price
260+
this.data.allowedSalesHistoryDeviation = ((this.data.allowedSalesHistoryDeviation || 0) + config.market.buyEnergy.allowedSalesHistoryDeviation)
261+
} catch (e) {
262+
this.debugLog('market', this.data.allowedSalesHistoryDeviation, e.message);
263+
}
264+
return ERR_NOT_FOUND;
265+
}
266+
216267
Room.prototype.handleMarket = function() {
217268
if (!this.terminal || this.terminal.cooldown) {
218269
return false;
219270
}
220271
this.sellOwnMineral();
221272
this.buyLowResources();
222273
this.buyLowCostResources();
274+
this.buyEnergy();
275+
223276
if (config.market.sendPowerOwnRoom) {
224277
this.sendPowerOwnRooms();
225278
}

src/quests.js

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
2-
31
const {debugLog} = require('./logging');
42

53
/**
@@ -68,7 +66,7 @@ function getQuest(transaction, data) {
6866
/**
6967
* haveActiveQuest
7068
*
71-
* @return {bool}
69+
* @return {boolean}
7270
*/
7371
function haveActiveQuest() {
7472
if (!global.data.activeQuest) {
@@ -93,7 +91,7 @@ module.exports.haveActiveQuest = haveActiveQuest;
9391
* getQuestFromTransactionDescription
9492
*
9593
* @param {object} description
96-
* @return {bool}
94+
* @return {boolean}
9795
*/
9896
function getQuestFromTransactionDescription(description) {
9997
let data;
@@ -107,7 +105,6 @@ function getQuestFromTransactionDescription(description) {
107105
debugLog('quests', 'Quest transaction: No type');
108106
return false;
109107
}
110-
console.log(JSON.stringify(data));
111108
for (const key of ['type', 'action', 'id']) {
112109
if (!data[key]) {
113110
debugLog('quests', `Incoming transaction no Quest: No ${key}`);
@@ -129,17 +126,22 @@ function getQuestFromTransactionDescription(description) {
129126
* checkQuestForAcceptance
130127
*
131128
* @param {object} transaction
132-
* @return {bool}
129+
* @return {boolean}
133130
*/
134131
function checkQuestForAcceptance(transaction) {
135132
Memory.quests = Memory.quests || {};
133+
transaction.description = transaction.description || JSON.stringify({
134+
type: 'quest',
135+
action: 'apply',
136+
id: _.first(Memory.quests)
137+
});
136138
const data = getQuestFromTransactionDescription(transaction.description);
137139
if (!data) {
138140
return false;
139141
}
140142
if (Memory.quests[data.id]) {
141143
console.log(`Quest already ongoing ${JSON.stringify(data)}`);
142-
return;
144+
return false;
143145
}
144146
const quest = getQuest(transaction, data);
145147
console.log(`Found quest acceptance on transaction ${JSON.stringify(quest)}`);
@@ -158,6 +160,7 @@ function checkQuestForAcceptance(transaction) {
158160
const terminalResponse = room.terminal.send(RESOURCE_ENERGY, 100, transaction.from, JSON.stringify(response));
159161
console.log(`terminalResponse ${JSON.stringify(terminalResponse)}`);
160162
// TODO find reserver in room and remove quest hint
163+
return true;
161164
}
162165

163166
module.exports.checkQuestForAcceptance = checkQuestForAcceptance;
@@ -166,35 +169,46 @@ module.exports.checkQuestForAcceptance = checkQuestForAcceptance;
166169
* checkAppliedQuestForAcceptance
167170
*
168171
* @param {object} transaction
169-
* @return {bool}
172+
* @return {boolean}
170173
*/
171174
function checkAppliedQuestForAcceptance(transaction) {
175+
let response
172176
try {
173-
const response = JSON.parse(transaction.description);
174-
if (!response.type) {
175-
debugLog('quests', `No type: ${JSON.stringify(response)}`);
176-
}
177-
if (response.type !== 'quest') {
178-
debugLog('quests', `Wrong type: ${JSON.stringify(response)}`);
177+
try {
178+
response = JSON.parse(transaction.description);
179+
} catch (e) {
180+
debugLog('quests', e.toString(), JSON.stringify(transaction));
179181
return false;
180182
}
181-
if (response.action) {
182-
debugLog('quests', `Action exist type: ${JSON.stringify(response)}`);
183-
return false;
183+
if (response) {
184+
if (!response.type) {
185+
debugLog('quests', `No type: ${JSON.stringify(response)}`);
186+
return false;
187+
}
188+
if (response.type !== 'quest') {
189+
debugLog('quests', `Wrong type: ${JSON.stringify(response)}`);
190+
return false;
191+
}
192+
if (response.action) {
193+
debugLog('quests', `Action exist type: ${JSON.stringify(response)}`);
194+
return false;
195+
}
196+
debugLog('quests', `Quest accept transaction: ${JSON.stringify(response)}`);
197+
if (!haveActiveQuest()) {
198+
debugLog('quests', 'No active quest');
199+
return false;
200+
}
201+
global.data.activeQuest.state = 'active';
202+
global.data.activeQuest.accept = response;
203+
debugLog('quests', `activeQuest: ${JSON.stringify(global.data.activeQuest)}`);
204+
return true;
184205
}
185-
debugLog('quests', `Quest accept transaction: ${JSON.stringify(response)}`);
186-
if (!haveActiveQuest()) {
187-
debugLog('quests', 'No active quest');
188-
return false;
189-
}
190-
global.data.activeQuest.state = 'active';
191-
global.data.activeQuest.accept = response;
192-
debugLog('quests', `activeQuest: ${JSON.stringify(global.data.activeQuest)}`);
193206
} catch (e) {
194207
console.log('checkAppliedQuestForAcceptance');
195208
console.log(e);
196209
console.log(e.stack);
197210
return false;
198211
}
199212
}
213+
200214
module.exports.checkAppliedQuestForAcceptance = checkAppliedQuestForAcceptance;

0 commit comments

Comments
 (0)