Cookie Clicker AI Assistant

AI-powered chatbot assistant to control your Cookie Clicker game - set cookies, manage buildings, unlock achievements, and more

Size

23.9 KB

Version

1.1.1

Created

Feb 13, 2026

Updated

about 1 month ago

1// ==UserScript==
2// @name		Cookie Clicker AI Assistant
3// @description		AI-powered chatbot assistant to control your Cookie Clicker game - set cookies, manage buildings, unlock achievements, and more
4// @version		1.1.1
5// @match		https://*.orteil.dashnet.org/*
6// @icon		https://orteil.dashnet.org/cookieclicker/img/favicon.ico
7// @grant		GM.xmlhttpRequest
8// @grant		GM.getValue
9// @grant		GM.setValue
10// ==/UserScript==
11(function() {
12    'use strict';
13
14    console.log('Cookie Clicker AI Assistant loading...');
15
16    // Wait for Game object to be available
17    function waitForGame(callback) {
18        console.log('Checking for Game object...');
19        if (typeof Game !== 'undefined' && Game.ready) {
20            console.log('Game is ready!');
21            callback();
22        } else {
23            console.log('Game not ready, waiting...');
24            setTimeout(() => waitForGame(callback), 500);
25        }
26    }
27
28    // Enhanced Game control functions
29    const GameController = {
30        setCookies(amount) {
31            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
32            Game.cookies = amount;
33            Game.cookiesEarned = Math.max(Game.cookiesEarned, amount);
34            return { success: true, message: `Set cookies to ${amount}` };
35        },
36
37        addCookies(amount) {
38            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
39            Game.cookies += amount;
40            Game.cookiesEarned += amount;
41            return { success: true, message: `Added ${amount} cookies. Total: ${Math.floor(Game.cookies)}` };
42        },
43
44        buyBuilding(buildingName, amount = 1) {
45            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
46            const building = Game.Objects[buildingName];
47            if (!building) {
48                const available = Object.keys(Game.Objects).join(', ');
49                return { success: false, error: `Building not found. Available: ${available}` };
50            }
51            for (let i = 0; i < amount; i++) {
52                building.buy();
53            }
54            return { success: true, message: `Bought ${amount} ${buildingName}(s). Total: ${building.amount}` };
55        },
56
57        setBuilding(buildingName, amount) {
58            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
59            const building = Game.Objects[buildingName];
60            if (!building) {
61                const available = Object.keys(Game.Objects).join(', ');
62                return { success: false, error: `Building not found. Available: ${available}` };
63            }
64            building.amount = amount;
65            return { success: true, message: `Set ${buildingName} to ${amount}` };
66        },
67
68        unlockAchievement(achievementName) {
69            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
70            const achievement = Game.Achievements[achievementName];
71            if (!achievement) {
72                return { success: false, error: `Achievement not found: ${achievementName}` };
73            }
74            Game.Win(achievementName);
75            return { success: true, message: `Unlocked achievement: ${achievementName}` };
76        },
77
78        removeAchievement(achievementName) {
79            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
80            const achievement = Game.Achievements[achievementName];
81            if (!achievement) {
82                return { success: false, error: `Achievement not found: ${achievementName}` };
83            }
84            achievement.won = 0;
85            return { success: true, message: `Removed achievement: ${achievementName}` };
86        },
87
88        openDevMenu() {
89            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
90            Game.OpenSesame();
91            return { success: true, message: 'Dev menu opened! Check the options menu.' };
92        },
93
94        clickCookie(times = 1) {
95            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
96            for (let i = 0; i < times; i++) {
97                Game.ClickCookie();
98            }
99            return { success: true, message: `Clicked cookie ${times} times` };
100        },
101
102        summonGoldenCookie() {
103            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
104            const goldenCookie = new Game.shimmer('golden');
105            return { success: true, message: 'Golden cookie summoned!' };
106        },
107
108        summonReindeer() {
109            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
110            const reindeer = new Game.shimmer('reindeer');
111            return { success: true, message: 'Reindeer summoned!' };
112        },
113
114        popAllGoldenCookies() {
115            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
116            let count = 0;
117            for (let i in Game.shimmers) {
118                Game.shimmers[i].pop();
119                count++;
120            }
121            return { success: true, message: count > 0 ? `Popped ${count} golden cookie(s)!` : 'No golden cookies to pop' };
122        },
123
124        getGameStats() {
125            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
126            return {
127                success: true,
128                stats: {
129                    cookies: Math.floor(Game.cookies),
130                    cookiesPerSecond: Math.floor(Game.cookiesPs),
131                    buildings: Object.keys(Game.Objects).map(name => ({
132                        name,
133                        amount: Game.Objects[name].amount
134                    })).filter(b => b.amount > 0),
135                    achievements: Game.AchievementsOwned,
136                    goldenClicks: Game.goldenClicks,
137                    handmadeCookies: Game.handmadeCookies
138                }
139            };
140        },
141
142        setBakeryName(name) {
143            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
144            Game.bakeryName = name;
145            Game.bakeryNameRefresh();
146            return { success: true, message: `Bakery name set to: ${name}` };
147        },
148
149        unlockAllUpgrades() {
150            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
151            let count = 0;
152            for (let i in Game.Upgrades) {
153                if (!Game.Upgrades[i].bought) {
154                    Game.Upgrades[i].buy(true);
155                    count++;
156                }
157            }
158            return { success: true, message: `Unlocked ${count} upgrades` };
159        },
160
161        unlockAllAchievements() {
162            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
163            let count = 0;
164            for (let i in Game.Achievements) {
165                if (!Game.Achievements[i].won) {
166                    Game.Win(i);
167                    count++;
168                }
169            }
170            return { success: true, message: `Unlocked ${count} achievements!` };
171        },
172
173        setCPS(amount) {
174            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
175            Game.cookiesPs = amount;
176            return { success: true, message: `Set cookies per second to ${amount}` };
177        },
178
179        ascend() {
180            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
181            Game.Ascend(1);
182            return { success: true, message: 'Ascending...' };
183        },
184
185        reincarnate() {
186            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
187            Game.Reincarnate(1);
188            return { success: true, message: 'Reincarnating...' };
189        },
190
191        enableAutoClicker(cps = 10) {
192            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
193            if (window.autoClickerInterval) {
194                clearInterval(window.autoClickerInterval);
195            }
196            window.autoClickerInterval = setInterval(() => {
197                Game.ClickCookie();
198            }, 1000 / cps);
199            return { success: true, message: `Auto-clicker enabled at ${cps} clicks per second` };
200        },
201
202        disableAutoClicker() {
203            if (window.autoClickerInterval) {
204                clearInterval(window.autoClickerInterval);
205                window.autoClickerInterval = null;
206                return { success: true, message: 'Auto-clicker disabled' };
207            }
208            return { success: false, error: 'Auto-clicker not running' };
209        },
210
211        spawnGoldenCookieStorm(count = 10) {
212            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
213            for (let i = 0; i < count; i++) {
214                setTimeout(() => {
215                    new Game.shimmer('golden');
216                }, i * 100);
217            }
218            return { success: true, message: `Spawning ${count} golden cookies!` };
219        },
220
221        setPrestigeLevel(level) {
222            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
223            Game.prestige = level;
224            Game.heavenlyChips = level;
225            return { success: true, message: `Set prestige level to ${level}` };
226        },
227
228        unlockAllSeeds() {
229            if (typeof Game === 'undefined') return { success: false, error: 'Game not loaded' };
230            if (!Game.Objects['Farm']) return { success: false, error: 'Farm not unlocked' };
231            let count = 0;
232            for (let i in Game.Objects['Farm'].minigame.plants) {
233                Game.Objects['Farm'].minigame.plants[i].unlocked = 1;
234                count++;
235            }
236            return { success: true, message: `Unlocked ${count} garden seeds!` };
237        }
238    };
239
240    // AI Command Processor
241    async function processAICommand(userMessage) {
242        try {
243            console.log('Processing command:', userMessage);
244            
245            // Get current game state for context
246            const gameStats = GameController.getGameStats();
247            const context = gameStats.success ? JSON.stringify(gameStats.stats) : 'Game not loaded';
248
249            const prompt = `You are an AI assistant for Cookie Clicker game. The user said: "${userMessage}"
250
251Current game state: ${context}
252
253Available commands you can execute:
254- setCookies(amount): Set cookies to exact amount
255- addCookies(amount): Add cookies to current amount
256- buyBuilding(name, amount): Buy buildings (Cursor, Grandma, Farm, Mine, Factory, Bank, Temple, Wizard tower, Shipment, Alchemy lab, Portal, Time machine, Antimatter condenser, Prism, Chancemaker, Fractal engine, Javascript console, Idleverse, Cortex baker, You)
257- setBuilding(name, amount): Set building count to exact amount
258- unlockAchievement(name): Unlock specific achievement
259- removeAchievement(name): Remove specific achievement
260- unlockAllAchievements(): Unlock all achievements
261- openDevMenu(): Open developer menu
262- clickCookie(times): Auto-click the cookie
263- summonGoldenCookie(): Spawn a golden cookie
264- summonReindeer(): Spawn a reindeer
265- popAllGoldenCookies(): Auto-click all golden cookies on screen
266- spawnGoldenCookieStorm(count): Spawn multiple golden cookies
267- enableAutoClicker(cps): Enable auto-clicker (clicks per second)
268- disableAutoClicker(): Disable auto-clicker
269- setBakeryName(name): Change bakery name
270- unlockAllUpgrades(): Unlock all upgrades
271- setCPS(amount): Set cookies per second
272- ascend(): Ascend to prestige
273- reincarnate(): Reincarnate after ascending
274- setPrestigeLevel(level): Set prestige level
275- unlockAllSeeds(): Unlock all garden seeds
276- getGameStats(): Get current game statistics
277
278Analyze the user's request and determine which command(s) to execute. Return a JSON response with:
279{
280  "commands": [{"function": "functionName", "params": [param1, param2]}],
281  "explanation": "What you're doing"
282}
283
284If the user is asking a question or wants stats, set commands to empty array and provide explanation.`;
285
286            const response = await RM.aiCall(prompt, {
287                type: 'json_schema',
288                json_schema: {
289                    name: 'game_command',
290                    schema: {
291                        type: 'object',
292                        properties: {
293                            commands: {
294                                type: 'array',
295                                items: {
296                                    type: 'object',
297                                    properties: {
298                                        function: { type: 'string' },
299                                        params: { type: 'array' }
300                                    },
301                                    required: ['function', 'params']
302                                }
303                            },
304                            explanation: { type: 'string' }
305                        },
306                        required: ['commands', 'explanation']
307                    }
308                }
309            });
310
311            console.log('AI Response:', response);
312
313            // Execute commands
314            const results = [];
315            for (const cmd of response.commands) {
316                if (GameController[cmd.function]) {
317                    const result = GameController[cmd.function](...cmd.params);
318                    results.push(result);
319                }
320            }
321
322            // Build response message
323            let message = response.explanation;
324            if (results.length > 0) {
325                message += '\n\n' + results.map(r => r.message || r.error).join('\n');
326            }
327
328            return { success: true, message };
329
330        } catch (error) {
331            console.error('AI Command Error:', error);
332            return { success: false, message: 'Error processing command: ' + error.message };
333        }
334    }
335
336    // Create Chat UI
337    function createChatUI() {
338        console.log('Creating chat UI...');
339        
340        const chatContainer = document.createElement('div');
341        chatContainer.id = 'ai-assistant-container';
342        chatContainer.innerHTML = `
343            <div id="ai-assistant-header">
344                <span>🤖 AI Cookie Assistant</span>
345                <button id="ai-assistant-toggle"></button>
346            </div>
347            <div id="ai-assistant-body">
348                <div id="ai-chat-messages"></div>
349                <div id="ai-chat-input-container">
350                    <input type="text" id="ai-chat-input" placeholder="Tell me what to do..." />
351                    <button id="ai-chat-send">Send</button>
352                </div>
353            </div>
354        `;
355
356        // Styles
357        const style = document.createElement('style');
358        style.textContent = `
359            #ai-assistant-container {
360                position: fixed;
361                bottom: 20px;
362                left: 20px;
363                width: 420px;
364                max-height: 650px;
365                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
366                border-radius: 20px;
367                box-shadow: 0 15px 50px rgba(0,0,0,0.4);
368                z-index: 999999;
369                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
370                display: flex;
371                flex-direction: column;
372            }
373
374            #ai-assistant-header {
375                background: rgba(0,0,0,0.3);
376                padding: 18px 20px;
377                border-radius: 20px 20px 0 0;
378                display: flex;
379                justify-content: space-between;
380                align-items: center;
381                color: white;
382                font-weight: bold;
383                font-size: 18px;
384                cursor: move;
385                user-select: none;
386            }
387
388            #ai-assistant-toggle {
389                background: rgba(255,255,255,0.25);
390                border: none;
391                color: white;
392                width: 32px;
393                height: 32px;
394                border-radius: 50%;
395                cursor: pointer;
396                font-size: 22px;
397                line-height: 1;
398                transition: all 0.3s;
399                font-weight: bold;
400            }
401
402            #ai-assistant-toggle:hover {
403                background: rgba(255,255,255,0.4);
404                transform: scale(1.15);
405            }
406
407            #ai-assistant-body {
408                display: flex;
409                flex-direction: column;
410                height: 550px;
411                background: white;
412                border-radius: 0 0 20px 20px;
413            }
414
415            #ai-assistant-body.collapsed {
416                display: none;
417            }
418
419            #ai-chat-messages {
420                flex: 1;
421                overflow-y: auto;
422                padding: 20px;
423                display: flex;
424                flex-direction: column;
425                gap: 12px;
426            }
427
428            .ai-message {
429                padding: 12px 16px;
430                border-radius: 18px;
431                max-width: 85%;
432                word-wrap: break-word;
433                animation: slideIn 0.4s ease;
434                line-height: 1.5;
435                white-space: pre-wrap;
436            }
437
438            @keyframes slideIn {
439                from {
440                    opacity: 0;
441                    transform: translateY(15px);
442                }
443                to {
444                    opacity: 1;
445                    transform: translateY(0);
446                }
447            }
448
449            .ai-message.user {
450                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
451                color: white;
452                align-self: flex-end;
453                margin-left: auto;
454            }
455
456            .ai-message.assistant {
457                background: #f5f5f5;
458                color: #333;
459                align-self: flex-start;
460                border: 1px solid #e0e0e0;
461            }
462
463            .ai-message.system {
464                background: #fff3cd;
465                color: #856404;
466                align-self: center;
467                font-size: 13px;
468                text-align: center;
469                border: 1px solid #ffeaa7;
470            }
471
472            #ai-chat-input-container {
473                display: flex;
474                padding: 18px;
475                gap: 12px;
476                border-top: 2px solid #f0f0f0;
477                background: #fafafa;
478                border-radius: 0 0 20px 20px;
479            }
480
481            #ai-chat-input {
482                flex: 1;
483                padding: 12px 18px;
484                border: 2px solid #e0e0e0;
485                border-radius: 25px;
486                font-size: 15px;
487                outline: none;
488                transition: all 0.3s;
489                background: white;
490            }
491
492            #ai-chat-input:focus {
493                border-color: #667eea;
494                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
495            }
496
497            #ai-chat-send {
498                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
499                color: white;
500                border: none;
501                padding: 12px 28px;
502                border-radius: 25px;
503                cursor: pointer;
504                font-weight: bold;
505                font-size: 15px;
506                transition: all 0.3s;
507            }
508
509            #ai-chat-send:hover {
510                transform: scale(1.08);
511                box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);
512            }
513
514            #ai-chat-send:disabled {
515                opacity: 0.6;
516                cursor: not-allowed;
517                transform: none;
518            }
519
520            #ai-chat-messages::-webkit-scrollbar {
521                width: 10px;
522            }
523
524            #ai-chat-messages::-webkit-scrollbar-track {
525                background: #f1f1f1;
526                border-radius: 10px;
527            }
528
529            #ai-chat-messages::-webkit-scrollbar-thumb {
530                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
531                border-radius: 10px;
532            }
533
534            #ai-chat-messages::-webkit-scrollbar-thumb:hover {
535                background: linear-gradient(135deg, #5568d3 0%, #653a8b 100%);
536            }
537        `;
538
539        document.head.appendChild(style);
540        document.body.appendChild(chatContainer);
541        
542        console.log('Chat UI created and added to page');
543
544        // Make draggable
545        let isDragging = false;
546        let currentX, currentY, initialX, initialY;
547
548        const header = document.getElementById('ai-assistant-header');
549        header.addEventListener('mousedown', (e) => {
550            if (e.target.id === 'ai-assistant-toggle') return;
551            isDragging = true;
552            initialX = e.clientX - chatContainer.offsetLeft;
553            initialY = e.clientY - chatContainer.offsetTop;
554        });
555
556        document.addEventListener('mousemove', (e) => {
557            if (isDragging) {
558                e.preventDefault();
559                currentX = e.clientX - initialX;
560                currentY = e.clientY - initialY;
561                chatContainer.style.left = currentX + 'px';
562                chatContainer.style.top = currentY + 'px';
563                chatContainer.style.right = 'auto';
564                chatContainer.style.bottom = 'auto';
565            }
566        });
567
568        document.addEventListener('mouseup', () => {
569            isDragging = false;
570        });
571
572        // Toggle collapse
573        document.getElementById('ai-assistant-toggle').addEventListener('click', () => {
574            const body = document.getElementById('ai-assistant-body');
575            const toggle = document.getElementById('ai-assistant-toggle');
576            body.classList.toggle('collapsed');
577            toggle.textContent = body.classList.contains('collapsed') ? '+' : '−';
578        });
579
580        // Add welcome message
581        addMessage('assistant', '👋 Hello! I\'m your Cookie Clicker AI assistant!\n\nI can do ANYTHING in your game:\n\n🍪 Set/add cookies\n🏭 Buy/set buildings\n🏆 Unlock achievements\n✨ Summon golden cookies\n🎯 Auto-click cookies\n🌟 Unlock all upgrades\n🎮 Open dev menu\n⚡ And much more!\n\nJust tell me what you want!');
582
583        // Handle send message
584        const input = document.getElementById('ai-chat-input');
585        const sendBtn = document.getElementById('ai-chat-send');
586
587        async function sendMessage() {
588            const message = input.value.trim();
589            if (!message) return;
590
591            addMessage('user', message);
592            input.value = '';
593            sendBtn.disabled = true;
594            sendBtn.textContent = '🤔...';
595
596            const response = await processAICommand(message);
597            addMessage('assistant', response.message);
598
599            sendBtn.disabled = false;
600            sendBtn.textContent = 'Send';
601        }
602
603        sendBtn.addEventListener('click', sendMessage);
604        input.addEventListener('keypress', (e) => {
605            if (e.key === 'Enter') sendMessage();
606        });
607        
608        console.log('Event listeners attached');
609    }
610
611    function addMessage(type, text) {
612        const messagesContainer = document.getElementById('ai-chat-messages');
613        if (!messagesContainer) {
614            console.error('Messages container not found!');
615            return;
616        }
617        const messageDiv = document.createElement('div');
618        messageDiv.className = `ai-message ${type}`;
619        messageDiv.textContent = text;
620        messagesContainer.appendChild(messageDiv);
621        messagesContainer.scrollTop = messagesContainer.scrollHeight;
622    }
623
624    // Initialize - try immediately and also wait for game
625    console.log('Starting initialization...');
626    
627    // Create UI immediately
628    if (document.readyState === 'loading') {
629        document.addEventListener('DOMContentLoaded', () => {
630            console.log('DOM loaded, creating UI...');
631            createChatUI();
632        });
633    } else {
634        console.log('DOM already loaded, creating UI now...');
635        createChatUI();
636    }
637
638    // Wait for game to be ready
639    waitForGame(() => {
640        console.log('Cookie Clicker AI Assistant ready!');
641        addMessage('system', '✅ Game loaded! I\'m ready to help you!');
642    });
643
644})();