|

Automate a Game: Build a Cookie Clicker Bot with Selenium

3D visualization of robotic fingers rapidly clicking a giant cookie, representing a Selenium game bot.

Let’s use our Selenium automation skills for something fun: building a bot to play the classic “Cookie Clicker” game.

Step 1: Setup and Target Elements

First, we need to open the game and find the IDs of the elements we want to click.

  • The main cookie has an ID of cookie.
  • The upgrades (Cursor, Grandma, etc.) have IDs like buyCursor, buyGrandma.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https.orteil.dashnet.org/cookieclicker/")

# Wait for the language selector
time.sleep(5)
driver.find_element(By.ID, "langSelect-EN").click()
time.sleep(2)

# Find the key elements
cookie = driver.find_element(By.ID, "bigCookie")

Step 2: The Main Loop

We’ll create an infinite loop that clicks the cookie, and then occasionally checks if we can afford an upgrade.

# A simple loop to click 100 times
for _ in range(100):
    cookie.click()

# Check if we can buy a "Cursor"
try:
    cursor = driver.find_element(By.ID, "buyCursor")
    cursor.click()
    print("Bought a cursor!")
except:
    print("Can't afford a cursor yet...")

time.sleep(1) # Wait a second
driver.quit() # Close the bot

Challenge

Can you make this bot smarter?

  1. Put the cookie.click() in a while True loop.
  2. Inside the loop, check the text of the buyCursor element. If it doesn’t have the “disabled” class, click it!

Similar Posts

Leave a Reply