(function() {
'use strict';
console.log('[农场助手] Content Script 加载中...');
let config = {
autoHarvest: true,
autoPlant: true,
autoBuySeeds: true,
harvestInterval: 5000,
maxBuyAmount: 50,
minGoldReserve: 100,
enabled: true
};
let isRunning = false;
let checkInterval = null;
let isInitialized = false;
let isProcessing = false;
let farmApi = null;
let farmData = null;
let plantData = null;
function injectAndGetApi() {
return new Promise((resolve, reject) => {
console.log('[农场助手] 开始注入外部脚本获取API...');
const script = document.createElement('script');
script.src = chrome.runtime.getURL('inject.js');
script.onload = function() {
console.log('[农场助手] 注入脚本已加载');
setTimeout(() => {
const api = window.__FARM_BOT_API__;
const data = window.__FARM_BOT_DATA__;
const plants = window.__FARM_BOT_PLANTS__;
if (api && data) {
resolve({ success: true, apiRequest: api, jsonData: data, plantData: plants });
} else {
resolve({ success: false, apiRequest: null, jsonData: null, plantData: null });
}
}, 500);
};
script.onerror = function(e) {
console.error('[农场助手] 脚本加载失败:', e);
reject(e);
};
document.head.appendChild(script);
});
}
function listenForInjection() {
return new Promise((resolve) => {
const handleComplete = (event) => {
document.removeEventListener('__farmBotInjectComplete__', handleComplete);
const detail = event.detail || {};
console.log('[农场助手] 注入完成:', detail);
if (detail.success) {
farmApi = window.__FARM_BOT_API__;
farmData = window.__FARM_BOT_DATA__;
plantData = window.__FARM_BOT_PLANTS__;
resolve({ success: true, apiRequest: farmApi, jsonData: farmData, plantData: plantData });
} else {
resolve({ success: false });
}
};
document.addEventListener('__farmBotInjectComplete__', handleComplete);
setTimeout(() => {
document.removeEventListener('__farmBotInjectComplete__', handleComplete);
resolve({ success: false, timeout: true });
}, 5000);
});
}
function waitForPageReady() {
return new Promise((resolve) => {
if (document.readyState === 'complete') {
resolve();
} else {
window.addEventListener('load', resolve, { once: true });
}
});
}
async function init() {
try {
console.log('[农场助手] 开始初始化...');
await waitForPageReady();
console.log('[农场助手] 页面已加载');
await new Promise(r => setTimeout(r, 2000));
console.log('[农场助手] 正在获取API引用...');
const [injectResult] = await Promise.all([
injectAndGetApi(),
listenForInjection()
]);
if (!injectResult.success || !window.__FARM_BOT_API__) {
const retry = await injectAndGetApi();
if (!retry.success) {
throw new Error('无法获取农场API。请刷新页面重试。');
}
}
farmApi = window.__FARM_BOT_API__;
farmData = window.__FARM_BOT_DATA__;
plantData = window.__FARM_BOT_PLANTS__;
if (!farmApi || !farmData) {
throw new Error('API未正确加载');
}
console.log('[农场助手] ✅ API获取成功!', {
methods: Object.keys(farmApi).slice(0, 10),
landCount: farmData.length
});
isInitialized = true;
chrome.runtime.sendMessage({ action: 'getConfig' }, (response) => {
if (response?.config) {
config = { ...config, ...response.config };
}
startAutomation();
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
handleMessage(request);
sendResponse({ received: true });
return true;
});
log('助手已启动 ✓');
addVisualIndicator();
} catch (error) {
console.error('[农场助手] ❌ 初始化失败:', error);
log('初始化失败: ' + error.message);
}
}
function startAutomation() {
if (isRunning) return;
isRunning = true;
mainLoop();
checkInterval = setInterval(() => {
if (config.enabled && !isProcessing) mainLoop();
}, config.harvestInterval);
log('自动化已启动 ✓');
}
function stopAutomation() {
isRunning = false;
if (checkInterval) {
clearInterval(checkInterval);
checkInterval = null;
}
}
function handleMessage(request) {
switch (request.action) {
case 'forceHarvest':
log('执行强制采摘...');
harvestAllMature();
break;
case 'forcePlant':
log('执行强制种植...');
plantAllEmptyLands();
break;
case 'configUpdated':
config = { ...config, ...request.config };
break;
}
}
async function mainLoop() {
if (!config.enabled || isProcessing || !isInitialized) return;
isProcessing = true;
try {
if (config.autoHarvest) await harvestAllMature();
if (config.autoPlant) await plantAllEmptyLands();
if (config.autoBuySeeds) await checkAndBuySeeds();
} catch (error) {
console.error('[农场助手] 主循环错误:', error);
} finally {
isProcessing = false;
}
}
async function harvestAllMature() {
if (!farmApi?.harvest || !farmData) return;
const matureLands = farmData.filter(land => {
if (!land || land.landState !== 1 || !land.seedType) return false;
return isLandMature(land);
});
if (matureLands.length === 0) return;
log(`发现 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$${matureLands.length} 块成熟作物,采摘中...`);
for (const land of matureLands) {
try {
await farmApi.harvest(land.id);
land.landState = 0;
land.seedType = null;
land.plantTime = null;
await delay(500);
} catch (e) {
console.error(`采摘失败:`, e);
}
}
log('采摘完成 ✓');
}
async function plantAllEmptyLands() {
if (!farmApi?.plant || !farmData) return;
const emptyLands = farmData.filter(land => {
return land && land.landState !== 0 && (!land.seedType || land.seedType === null);
});
if (emptyLands.length === 0) return;
let seeds = await getAvailableSeeds();
if (seeds.length === 0) {
await checkAndBuySeeds();
seeds = await getAvailableSeeds();
if (seeds.length === 0) return;
}
log(`发现 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$${emptyLands.length} 块空地,种植中...`);
for (const land of emptyLands) {
const available = await getAvailableSeeds();
if (available.length === 0) break;
const seed = selectBestSeed(available);
if (seed) {
try {
await farmApi.plant(land.id, seed.id);
land.landState = 1;
land.seedType = seed.itemId;
land.plantTime = new Date().toISOString();
await delay(500);
} catch (e) {
console.error(`种植失败:`, e);
}
}
}
log('种植完成 ✓');
}
async function getAvailableSeeds() {
if (!farmApi?.queryUserInventory) return [];
try {
const inventory = await farmApi.queryUserInventory();
return inventory?.seedList?.filter(s => s.quantity > 0) || [];
} catch (e) {
return [];
}
}
function selectBestSeed(seeds) {
if (!seeds?.length) return null;
return seeds[0];
}
async function checkAndBuySeeds() {
if (!farmApi?.getShopItemList || !farmApi?.purchaseItem) return;
const goldEl = document.querySelector('.goldCoins__text-exp');
const currentGold = parseInt(goldEl?.textContent) || 0;
if (currentGold < config.minGoldReserve) return;
const seeds = await getAvailableSeeds();
if (seeds.length > 0) return;
try {
const inventory = await farmApi.queryUserInventory();
if (inventory?.fruitList?.length) {
for (const fruit of inventory.fruitList) {
if (fruit.quantity > 0) {
try {
await farmApi.sellFruits([{ itemId: fruit.itemId, quantity: fruit.quantity }]);
} catch (e) {}
}
}
}
} catch (e) {}
const newGold = parseInt(document.querySelector('.goldCoins__text-exp')?.textContent) || 0;
const available = newGold - config.minGoldReserve;
if (available <= 0) return;
try {
const shop = await farmApi.getShopItemList();
const seedItems = shop?.filter(i => !i.locked) || [];
if (seedItems.length === 0) return;
seedItems.sort((a, b) => a.priceAmount - b.priceAmount);
const toBuy = seedItems[0];
const amount = Math.min(Math.floor(available / toBuy.priceAmount), config.maxBuyAmount);
if (amount > 0) {
await farmApi.purchaseItem(toBuy.shopItemId, amount);
log(`购买 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$${amount} 粒种子成功 ✓`);
}
} catch (e) {}
}
function isLandMature(land) {
if (!land?.plantTime) return false;
const elapsed = Date.now() - new Date(land.plantTime).getTime();
const maturityTime = (land.maturityTime || 60) * 1000;
return elapsed >= maturityTime;
}
function delay(ms) {
return new Promise(r => setTimeout(r, ms));
}
function log(message) {
console.log(`[农场助手] $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$${message}`);
try {
chrome.runtime.sendMessage({ action: 'addLog', log: message });
} catch (e) {}
}
function addVisualIndicator() {
const existing = document.getElementById('farm-bot-indicator');
if (existing) existing.remove();
const indicator = document.createElement('div');
indicator.id = 'farm-bot-indicator';
indicator.innerHTML = `
<div style="color:white;font-size:12px;padding:5px;">
🌾 农场助手
<div id="bot-status">初始化中...</div>
</div>
`;
indicator.style.cssText = `
position:fixed;bottom:100px;right:20px;
background:linear-gradient(135deg,#667eea,#764ba2);
padding:10px 15px;border-radius:10px;
z-index:99999;box-shadow:0 4px 15px rgba(0,0,0,0.3);
`;
document.body.appendChild(indicator);
setInterval(() => {
const statusEl = document.getElementById('bot-status');
if (statusEl) {
if (!isInitialized) {
statusEl.textContent = '初始化中...';
} else if (config.enabled && isRunning) {
statusEl.textContent = '运行中 ✓';
} else {
statusEl.textContent = '已暂停';
}
}
}, 500);
}
console.log('[农场助手] 文档状态:', document.readyState);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => setTimeout(init, 2000));
} else {
setTimeout(init, 2000);
}
})();