# MIT License
# Copyright (C) 2022 Shintaro Mukai.
# https://mukai.systems/articles/t6kgmuu7kwwrqq5vq756duk0l8oyijob/

# Golden Cookie Clicker.

import time

import cv2
import pyautogui

pyautogui.FAILSAFE = False

gc = cv2.imread('./gc.png', cv2.IMREAD_GRAYSCALE)
gc_dx, gc_dy = map(lambda x: int(x / 2), gc.shape)
gc_click_interval = 25
cookie_x, cookie_y = 400, 600

def screenshot():
    ss = './ss.png'
    pyautogui.screenshot(ss)
    return cv2.imread(ss, cv2.IMREAD_GRAYSCALE)

def click_cookie():
    pyautogui.click(cookie_x, cookie_y)

def click_golden_cookie():
    img = screenshot()
    result = cv2.matchTemplate(img, gc, cv2.TM_CCOEFF)
    _, _, _, (x, y) = cv2.minMaxLoc(result)
    pyautogui.click(x + gc_dx, y + gc_dy)

if __name__ == '__main__':
    time.sleep(5)
    while pyautogui.position() != (0, 0):
        click_golden_cookie()
        start = time.time()
        while time.time() - start < gc_click_interval:
            click_cookie()
            if pyautogui.position() != (cookie_x, cookie_y):
                time.sleep(10)
                break
