首页  >  文章  >  web前端  >  创建自动跳跃恐龙脚本的旅程

创建自动跳跃恐龙脚本的旅程

Susan Sarandon
Susan Sarandon原创
2024-11-04 17:42:02675浏览

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 < 70 && 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 < jumpDistance && 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 <= crouchDistance && 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 < 70) {
        // Crouch if the obstacle is a Pterodactyl flying high
        simulateKeyPress(40, 'ArrowDown'); // Simulate crouch (down arrow)
        isCrouching = true; // Set crouch state to true
      }

      // Release crouch when the obstacle is passed (Dino's xPos is greater than obstacle's xPos)
      if (tRex.xPos > 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