Advertisement
OS_scripts

Snake auto play V1

Feb 6th, 2025 (edited)
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Snake extension auto play Version 1 (this AI suck and will died on 20 points)
  2. // https://chromewebstore.google.com/detail/snake/oppflpnigmhkldmdmmbnopidlhahanji
  3. // edit the source code from original snake extension in app.js
  4.  
  5. (() => {
  6.   "use strict";
  7.   class t {
  8.     constructor(t, e, s) {
  9.       this.x = t, this.y = e, this.dir = s
  10.     }
  11.     collides(t) {
  12.       return this.xx == t.xx && this.yy == t.yy
  13.     }
  14.     get xx() {
  15.       return Math.round(this.x / scl)
  16.     }
  17.     get yy() {
  18.       return Math.round(this.y / scl)
  19.     }
  20.   }
  21.   class e {
  22.     constructor(e, s, i, r) {
  23.       this.justTurnRight = 0;
  24.       this.justTurnLeft = 0;
  25.       this.justStarted = 0;
  26.       this.justHitBottom = false;
  27.       this.x = e, this.y = s, this.color = r, this.body = [], this.dir = {
  28.         x: 0,
  29.         y: 0
  30.       }, this.newDir = {
  31.         x: 0,
  32.         y: 0
  33.       }, this.greenFace = new Image, this.greenFace.src = "images/head.png", this.redFace = new Image, this.redFace.src = "images/redHead.png", this.face = this.greenFace;
  34.       for (var n = 0; n < i; n++) this.body.push(new t((this.x - n) * scl, this.y * scl, {
  35.         x: 1,
  36.         y: 0
  37.       }))
  38.     }
  39.    
  40.     update() {
  41.       if (!this.isDead) {
  42.         if (this.justStarted < tileCount){
  43.             this.justStarted++;
  44.             this.newDir.x = 0;
  45.             this.newDir.y = -1;
  46.         }
  47.         const headFront = this.headFront()
  48.         const checkTop = this.isHitTop(headFront.yy);
  49.         const checkBottom = this.isHitBottom(headFront.yy);
  50.         const checkRight = this.isHitRight(headFront.xx);
  51.         const checkLeft = this.isHitLeft(headFront.xx);
  52.         if (this.justTurnRight >= 1 && !checkRight){
  53.             this.justTurnRight++;
  54.             if (this.justTurnRight >= 5){
  55.                 this.justTurnRight = 0
  56.                 this.newDir.x = -1;
  57.                 this.newDir.y = 0;
  58.             }
  59.         }
  60.         if (this.justTurnLeft && !checkLeft){
  61.             this.justTurnLeft++;
  62.             if (this.justTurnLeft >= 5){
  63.                 this.justTurnLeft = 0
  64.                 this.newDir.x = 1;
  65.                 this.newDir.y = 0;
  66.             }
  67.         }
  68.         if (checkTop){
  69.             this.newDir.x = 1;
  70.             this.newDir.y = 0;
  71.             this.justHitBottom = false;
  72.         }
  73.         else if (checkBottom){
  74.             this.newDir.x = 1;
  75.             this.newDir.y = 0;
  76.             this.justHitBottom = true;
  77.         }
  78.         else if (checkRight){
  79.             this.newDir.x = 0;
  80.             this.newDir.y = (this.justHitBottom ? -1 : 1);
  81.             this.justTurnRight = 1;
  82.         }
  83.         else if (checkLeft){
  84.             this.newDir.x = 0;
  85.             this.newDir.y = (this.justHitBottom ? -1 : 1);
  86.             this.justTurnLeft = 1;
  87.         }
  88.         //console.log("Going "+ (this.newDir.x == 1 ? "Right" : "Left"));
  89.         if (0 == (this.head.x / scl).toFixed(1).substr(-1) && 0 == (this.head.y / scl).toFixed(1).substr(-1)) {
  90.           if (this.checkDeath() && !this.isDead) return this.die();
  91.  
  92.           // Update the direction of snake
  93.           this.dir.x = this.newDir.x;
  94.           this.dir.y = this.newDir.y;
  95.           this.head.dir.x = this.dir.x;
  96.           this.head.dir.y = this.dir.y;
  97.  
  98.           // Update the snake body/pos
  99.           for (let t = this.length - 1; t > 0; t--) {
  100.             this.body[t].dir.x = (this.body[t - 1].x - this.body[t].x) / scl;
  101.             this.body[t].dir.y = (this.body[t - 1].y - this.body[t].y) / scl;
  102.           }
  103.         }
  104.  
  105.         // Move snake
  106.         this.body.forEach((t) => {
  107.           t.x += t.dir.x * speed;
  108.           t.y += t.dir.y * speed;
  109.         });
  110.       }
  111.     }
  112.     headFront() {
  113.       const predictedX = this.head.xx + this.head.dir.x;
  114.       const predictedY = this.head.yy + this.head.dir.y;
  115.  
  116.       return { xx: predictedX, yy: predictedY };
  117.     }
  118.     isHitTop(yy) {
  119.       if (yy <= -1) {
  120.         return true;
  121.       }
  122.       return false;
  123.     }
  124.     isHitBottom(yy) {
  125.       if (yy >= tileCount) {
  126.         return true;
  127.       }
  128.       return false;
  129.     }
  130.     isHitRight(xx) {
  131.       if (xx >= tileCount) {
  132.         return true;
  133.       }
  134.       return false;
  135.     }
  136.     isHitLeft(xx) {
  137.       if (xx <= -1) {
  138.         return true;
  139.       }
  140.       return false;
  141.     }
  142.     draw(t) {
  143.       this.body.forEach((e => {
  144.         t.fillStyle = this.color, t.fillRect(e.x, e.y, scl, scl), keys.shift && (t.strokeStyle = "red", t.strokeRect(e.xx * scl, e.yy * scl, scl, scl))
  145.       })), t.drawImage(this.face, this.head.x, this.head.y, scl, scl)
  146.     }
  147.     appendNew() {
  148.       let e = this.tail;
  149.       this.body.push(new t(e.x, e.y, {
  150.         x: 0,
  151.         y: 0
  152.       }))
  153.     }
  154.     checkDeath() {
  155.       if (this.head.xx >= tileCount || this.head.yy >= tileCount || this.head.xx < 0 || this.head.yy < 0) return !0;
  156.       for (let t = 1; t < this.length; t++)
  157.         if (this.head.collides(this.body[t])) return !0;
  158.       return !1
  159.     }
  160.     die() {
  161.       this.isDead = !0;
  162.       let t = this.color;
  163.       this.color = "red", this.face = this.redFace, setTimeout((() => {
  164.         this.color = t, this.face = this.greenFace, setTimeout((() => {
  165.           this.color = "red", this.face = this.redFace
  166.         }), 200)
  167.       }), 200)
  168.     }
  169.     get length() {
  170.       return this.body.length
  171.     }
  172.     get head() {
  173.       return this.body[0]
  174.     }
  175.     get tail() {
  176.       return this.body[this.body.length - 1]
  177.     }
  178.     get xx() {
  179.       return this.head.xx
  180.     }
  181.     get yy() {
  182.       return this.head.yy
  183.     }
  184.   }
  185.   class s {
  186.     constructor() {
  187.       return new Proxy(this, this)
  188.     }
  189.     get(t, e) {
  190.       try {
  191.         return JSON.parse(localStorage.getItem(e))
  192.       } catch (t) {
  193.         return console.warn("Unable to load value from localstorage"), null
  194.       }
  195.     }
  196.     set(t, e, s) {
  197.       try {
  198.         return localStorage.setItem(e, JSON.stringify(s)), !0
  199.       } catch (t) {
  200.         return console.warn("Unable to store value to localstorage"), !1
  201.       }
  202.     }
  203.   }
  204.   const i = t => chrome && "storage" in chrome && t in chrome.storage,
  205.     r = t => (e, s) => new Promise((r => {
  206.       i(t) ? chrome.storage[t].set({
  207.         [e]: s
  208.       }, r) : (localStorage.setItem(e, s), r())
  209.     })),
  210.     n = t => e => new Promise(((s, r) => {
  211.       const n = `item with key [${e}] does not exist`;
  212.       if (i(t)) chrome.storage[t].get(e, (t => e in t ? s(t[e]) : r(n)));
  213.       else {
  214.         const t = localStorage.getItem(e);
  215.         null !== t ? s(t) : r(n)
  216.       }
  217.     })),
  218.     o = n("local"),
  219.     a = r("local"),
  220.     h = n("sync"),
  221.     c = r("sync");
  222.   class l {
  223.     constructor(t, e, s) {
  224.       this.xx = t, this.yy = e, this.padding = s, this.p = s, this.color = "red"
  225.     }
  226.     generateNew() {
  227.       this.xx = Math.round(Math.random() * (tileCount - 1)), this.yy = Math.round(Math.random() * (tileCount - 1));
  228.       let t = !1;
  229.       snake.body.forEach((e => {
  230.         e.xx == this.xx && this.yy == e.yy && (t = !0)
  231.       })), t ? this.generateNew() : this.p = scl / 2
  232.     }
  233.     draw(t) {
  234.       t.fillStyle = this.color, t.fillRect(this.x + this.p, this.y + this.p, scl - 2 * this.p, scl - 2 * this.p), this.p > this.padding && this.p--
  235.     }
  236.     get x() {
  237.       return this.xx * scl
  238.     }
  239.     get y() {
  240.       return this.yy * scl
  241.     }
  242.   }
  243.   const d = async (t, e = {}) => {
  244.     const s = "clientId",
  245.       i = "userId",
  246.       r = "sessionData",
  247.       n = await o(s).catch((() => self?.crypto?.randomUUID()));
  248.     a(s, n);
  249.     const l = await h(i).catch((() => self?.crypto?.randomUUID()));
  250.     c(i, l);
  251.     const d = await o(r).catch((() => ({
  252.       timeStamp: Date.now(),
  253.       sessionId: Date.now()
  254.     })));
  255.     5 < (Date.now() - d.timeStamp) / 6e4 && (d.sessionId = Date.now()), d.timeStamp = Date.now(), a(r, d);
  256.     const y = chrome?.runtime?.getManifest()?.version;
  257.     return fetch("https://www.google-analytics.com/mp/collect?measurement_id=G-V3VSP7EQBQ&api_secret=Ociti_pnRfa797JSsfwD3g", {
  258.       method: "POST",
  259.       body: JSON.stringify({
  260.         client_id: n,
  261.         user_id: l,
  262.         events: [{
  263.           name: t,
  264.           params: {
  265.             appVersion: y,
  266.             sessionId: d?.sessionId,
  267.             page_location: globalThis?.location?.href,
  268.             page_host: globalThis?.location?.host,
  269.             page_title: globalThis?.document?.title,
  270.             ...e
  271.           }
  272.         }]
  273.       })
  274.     }).then((t => t.text()))
  275.   }, y = t => fetch("https://k-ext.pages.dev/" + t);
  276.   async function w() {
  277.     const t = y("snake").then((t => t.text())).then((t => {
  278.         d("ad_load");
  279.         const e = document.querySelector("div#ads");
  280.         e.innerHTML = t, e.querySelectorAll("[data-close]").forEach((t => {
  281.           const e = t.getAttribute("data-close"),
  282.             s = document.querySelector(e);
  283.           t.addEventListener("click", (() => {
  284.             s.toggleAttribute("hidden")
  285.           }))
  286.         })), e.querySelectorAll("[data-analytics]").forEach((t => {
  287.           const e = t.getAttribute("data-analytics");
  288.           t.addEventListener("click", (() => {
  289.             d(e)
  290.           }))
  291.         }))
  292.       })),
  293.       e = y("snake-uninstall-urls").then((t => t.text())).then((t => t.split(","))).then((t => t.filter((t => -1 !== t.indexOf("https://"))))).then((t => {
  294.         const [e] = [...t, ""];
  295.         return chrome.runtime.setUninstallURL(e)
  296.       }));
  297.     return Promise.all([t, e])
  298.   }
  299.   const u = t => {
  300.       if (!(t instanceof Error)) return JSON.stringify(t);
  301.       const e = {};
  302.       return Object.getOwnPropertyNames(t).forEach((s => {
  303.         e[s] = t[s]
  304.       }), t), JSON.stringify(e)
  305.     },
  306.     x = async (t, e) => {
  307.       "string" != typeof t && (t = u(t)), (async (t, e, s) => {
  308.         const i = (() => {
  309.             try {
  310.               if (-1 !== window.location.href.indexOf("chrome-extension://")) return chrome.runtime.getManifest().version
  311.             } catch (t) {}
  312.             return "null"
  313.           })(),
  314.           [r] = (new Date).toLocaleString("no-NB").split(",");
  315.         d(t, {
  316.           version: i,
  317.           date: r,
  318.           description: s,
  319.           where: e
  320.         })
  321.       })("error", e, t)
  322.     };
  323.   let g, f, m, p, k = 0;
  324.  
  325.   function b() {
  326.     p.fillStyle = "black", p.fillRect(0, 0, canvas.width, canvas.height), g.draw(p), snake.update(), snake.draw(p), p.font = 1.5 * scl + "px Arial", p.fillStyle = "#fff", p.fillText(k, canvas.width / 2 - p.measureText(k).width / 2, 2.5 * scl), p.font = .5 * scl + "px Arial", p.fillStyle = "#fff", p.fillText("High score: " + m, canvas.width / 2 - p.measureText("High score: " + m).width / 2, 3.5 * scl), snake.head.collides(g) && (g.generateNew(), snake.appendNew(), k++), k > m && (m = k, f._hscore = m)
  327.   }
  328.   window.tileCount = 11, window.speed = 7, window.onload = function () {
  329.     !async function () {
  330.       window.ga && (window.addEventListener("error", (t => {
  331.         const e = u(t.error ? t.error : t);
  332.         x(e, "window.onerror")
  333.       })), window.addEventListener("unhandledrejection", (t => {
  334.         const e = t.reason ? t.reason : "unhandled rejection";
  335.         x(e, "window.onunhandledrejection")
  336.       })))
  337.     }();
  338.     let t = document.querySelector("#canvas");
  339.     p = t.getContext("2d"), f = new s, window.scl = t.width / tileCount, g = new l(6, Math.floor(tileCount / 2), 5), window.snake = new e(4, Math.floor(tileCount / 2), 3, "rgb(50, 255, 50)"), m = f._hscore || 0, d("page_view", {
  340.       highScore: m
  341.     }), setInterval(b, 1e3 / 90), w()
  342.   }, window.keys = {}, document.addEventListener("keydown", (t => {
  343.     snake.isDead && window.location.reload(), keys[t.key.toLowerCase()] = !0
  344.   })), document.addEventListener("keyup", (t => keys[t.key.toLowerCase()] = !1))
  345. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement