搜尋
首頁web前端js教程創建自動跳躍恐龍腳本的旅程

The Journey of Creating an Auto-Jump Dino Script

我睡不著。也許是因為我之前喝了三杯咖啡,也許是因為我的思緒飛快運轉。不管怎樣,我發現自己焦躁不安,無法入睡。我沒有與失眠作鬥爭,而是決定編碼。還有什麼比創建一個讓 Chrome 離線遊戲中的恐龍自行跳躍的腳本更好的方式來花費這些精力呢?

這是一個關於一個想法的小火花如何導致數小時的調整、測試,並最終為霸王龍打造一個功能齊全的自動跳躍系統的故事。

開始:一個簡單的想法

首先,我從最基本的概念開始。我希望只要障礙物在範圍內,恐龍就能自動跳躍。當時的挑戰似乎很簡單。經過一番思考,我寫了一個簡單的腳本:

// Auto jump function
function autoJump() {
  const checkObstacle = setInterval(() => {
    const tRex = Runner.instance_.tRex;

    // Check if an obstacle is near
    const obstacles = Runner.instance_.horizon.obstacles;

    if (obstacles.length > 0) {
      const obstacle = obstacles[0];

      // If the obstacle is close and within jumpable range, make the Dino jump
      if (obstacle.xPos  20 && !tRex.jumping) {
        tRex.startJump();
      }
    }
  }, 10); // Check every 10ms
}

// Start auto jump
autoJump();

第一個版本完成了這項工作。恐龍會偵測障礙物,並在接近障礙物時自動跳躍。然而,仍有許多需要改進的地方。它給人的感覺是機器人和有限的——它可以跳躍,但沒有蹲下或考慮遊戲的速度如何影響恐龍的反應。我想要一些更具適應性和動態性的東西。

進化:自適應自動跳躍和蹲伏

我花了接下來的幾個小時完善程式碼,添加了更多功能,例如根據遊戲速度進行自適應跳躍,以及在翼手龍飛過時整合蹲伏機制。結果是一個感覺更符合實際遊戲的腳本。最終版本讓恐龍不僅可以根據固定距離做出反應,還可以根據遊戲本身的速度進行調整。

這是我的想法:

// Create the button to toggle auto-jump
const toggleButton = createToggleButton();
document.body.appendChild(toggleButton);

let autoJumpActive = false; // Auto-jump initially inactive
let autoJumpInterval = null; // Store interval ID
let jumpCount = 0; // Count the number of jumps
let obstacleCount = 0; // Count the number of obstacles encountered
let isCrouching = false; // Track crouch state

// Function to create the toggle button
function createToggleButton() {
  const button = document.createElement('button');
  button.innerText = 'Activate Auto-Jump';
  styleToggleButton(button);
  button.addEventListener('click', toggleAutoJump);
  return button;
}

// Function to style the toggle button
function styleToggleButton(button) {
  button.style.position = 'fixed';
  button.style.top = '10px';
  button.style.left = '10px';
  button.style.padding = '10px';
  button.style.zIndex = '1000';
  button.style.backgroundColor = '#4CAF50';
  button.style.color = '#fff';
  button.style.border = 'none';
  button.style.cursor = 'pointer';
}

// Function to simulate a key press
function simulateKeyPress(keyCode, key) {
  const event = new KeyboardEvent('keydown', {
    keyCode: keyCode,
    code: key,
    key: key,
    bubbles: true,
    cancelable: true,
  });
  document.dispatchEvent(event);
}

// Function to simulate a key release
function simulateKeyRelease(keyCode, key) {
  const event = new KeyboardEvent('keyup', {
    keyCode: keyCode,
    code: key,
    key: key,
    bubbles: true,
    cancelable: true,
  });
  document.dispatchEvent(event);
}

// Function to calculate adaptive distances for jumping and crouching based on speed
function calculateAdaptiveDistance(baseDistance) {
  const speed = Runner.instance_.currentSpeed;
  return baseDistance + speed * 3; // Adjust the multiplier as needed for more precision
}

// Function to start auto-jumping and crouching
function startAutoJump() {
  autoJumpInterval = setInterval(() => {
    const tRex = Runner.instance_.tRex;
    const obstacles = Runner.instance_.horizon.obstacles;
    const speed = Runner.instance_.currentSpeed; // Get the current speed of the game

    if (obstacles.length > 0) {
      const obstacle = obstacles[0];
      const distanceToObstacle = obstacle.xPos - tRex.xPos; // Distance from Dino to the obstacle

      // Dynamically calculate the adaptive jump and crouch distances based on game speed
      const jumpDistance = calculateAdaptiveDistance(100); // Base distance is 100, adjusted by speed
      const crouchDistance = calculateAdaptiveDistance(50); // Base crouch distance is 50
      const safeDistance = 40; // Minimum safe distance to avoid jumping too early

      // Check if the Dino needs to jump or crouch
      if (distanceToObstacle  safeDistance) {
        if (!tRex.jumping && !isCrouching) { // Ensure Dino is not crouching or jumping
          jumpCount++; // Increment jump count
          simulateKeyPress(32, ' '); // Simulate jump (spacebar)
        }
      } else if (distanceToObstacle  safeDistance && !tRex.jumping) {
        // Only crouch if the Dino is not jumping
        simulateKeyPress(40, 'ArrowDown'); // Simulate crouch (down arrow)
        isCrouching = true; // Set crouch state to true
      } else if (obstacle.typeConfig.type === 'PTERODACTYL' && obstacle.yPos  obstacle.xPos && isCrouching) {
        simulateKeyRelease(40, 'ArrowDown'); // Release crouch (down arrow)
        isCrouching = false; // Reset crouch state
      }
    }

    // Update obstacle count
    obstacleCount = Runner.instance_.horizon.obstacles.length;

  }, 50); // Reduced interval time to 50ms for more frequent checks
}

// Function to stop auto-jumping
function stopAutoJump() {
  clearInterval(autoJumpInterval);
  autoJumpActive = false; // Reset auto-jump state
  toggleButton.innerText = 'Activate Auto-Jump';
  toggleButton.style.backgroundColor = '#4CAF50';
}

// Function to toggle auto-jump
function toggleAutoJump() {
  if (autoJumpActive) {
    stopAutoJump();
  } else {
    startAutoJump();
    toggleButton.innerText = 'Deactivate Auto-Jump';
    toggleButton.style.backgroundColor = '#f44336';
  }
  autoJumpActive = !autoJumpActive; // Toggle the state
}

// Detecting game over
const originalGameOver = Runner.prototype.gameOver;
Runner.prototype.gameOver = function() {
  stopAutoJump(); // Stop auto-jumping on game over
  originalGameOver.apply(this, arguments); // Call the original game over function
}

// Detecting when the game restarts
const originalStartGame = Runner.prototype.startGame;
Runner.prototype.startGame = function() {
  originalStartGame.apply(this, arguments);
  if (autoJumpActive) {
    startAutoJump(); // Restart auto-jump on game restart
  }
}

對編碼之旅的思考

從一個不眠之夜到一個功能齊全的自動跳轉腳本的旅程既有趣又充滿挑戰。最初的簡單想法逐漸演變成更為複雜的想法,需要注重細節、適應力和願意嘗試。每次迭代都讓腳本更像是遊戲的一個組成部分,而不是一個簡單的附加元件。

這就是編碼的美妙之處:你從一個想法開始,透過堅持和創造力,你最終會得到超越你最初願景的東西。有時,這一切都始於喝了太多杯咖啡!

以上是創建自動跳躍恐龍腳本的旅程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中