잠이 안 왔어요. 어쩌면 아까 마셨던 커피 세 잔 때문이었을 수도 있고, 아니면 생각이 복잡해서였을 수도 있습니다. 그럼에도 불구하고 나는 안절부절 못하고 표류할 수 없다는 것을 깨달았습니다. 불면증과 싸우는 대신 코딩을 하기로 결정했습니다. 그리고 Chrome 오프라인 게임에서 공룡이 저절로 점프하게 만드는 스크립트를 만드는 것보다 그 에너지를 소비하는 더 좋은 방법이 있을까요?
이것은 작은 아이디어가 어떻게 몇 시간의 조정과 테스트를 거쳐 궁극적으로 T-Rex의 자동 점프 시스템이 완벽하게 작동하게 되었는지에 대한 이야기입니다.
시작: 간단한 아이디어
처음에는 가장 기본적인 개념부터 시작했어요. 나는 장애물이 범위 내에 있을 때마다 공룡이 자동으로 점프하기를 원했습니다. 그 당시에는 도전이 간단해 보였습니다. 약간의 생각 끝에 간단한 스크립트를 작성했습니다.
// 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript 코어 데이터 유형은 브라우저 및 Node.js에서 일관되지만 추가 유형과 다르게 처리됩니다. 1) 글로벌 객체는 브라우저의 창이고 node.js의 글로벌입니다. 2) 이진 데이터를 처리하는 데 사용되는 Node.js의 고유 버퍼 객체. 3) 성능 및 시간 처리에는 차이가 있으며 환경에 따라 코드를 조정해야합니다.

javaScriptUSTWOTYPESOFSOFCOMMENTS : 단일 라인 (//) 및 multi-line (//)

Python과 JavaScript의 주요 차이점은 유형 시스템 및 응용 프로그램 시나리오입니다. 1. Python은 과학 컴퓨팅 및 데이터 분석에 적합한 동적 유형을 사용합니다. 2. JavaScript는 약한 유형을 채택하며 프론트 엔드 및 풀 스택 개발에 널리 사용됩니다. 두 사람은 비동기 프로그래밍 및 성능 최적화에서 고유 한 장점을 가지고 있으며 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

Python 또는 JavaScript를 선택할지 여부는 프로젝트 유형에 따라 다릅니다. 1) 데이터 과학 및 자동화 작업을 위해 Python을 선택하십시오. 2) 프론트 엔드 및 풀 스택 개발을 위해 JavaScript를 선택하십시오. Python은 데이터 처리 및 자동화 분야에서 강력한 라이브러리에 선호되는 반면 JavaScript는 웹 상호 작용 및 전체 스택 개발의 장점에 없어서는 안될 필수입니다.

파이썬과 자바 스크립트는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구와 개인 선호도에 따라 다릅니다. 1. Python은 간결한 구문으로 데이터 과학 및 백엔드 개발에 적합하지만 실행 속도가 느립니다. 2. JavaScript는 프론트 엔드 개발의 모든 곳에 있으며 강력한 비동기 프로그래밍 기능을 가지고 있습니다. node.js는 풀 스택 개발에 적합하지만 구문은 복잡하고 오류가 발생할 수 있습니다.

javaScriptisNotBuiltoncorc; it'SangretedLanguageThatrunsonOngineStenWrittenInc .1) javaScriptWasDesignEdasAlightweight, 해석 hanguageforwebbrowsers.2) Endinesevolvedfromsimpleplemporectreterstoccilpilers, 전기적으로 개선된다.

JavaScript는 프론트 엔드 및 백엔드 개발에 사용할 수 있습니다. 프론트 엔드는 DOM 작업을 통해 사용자 경험을 향상시키고 백엔드는 Node.js를 통해 서버 작업을 처리합니다. 1. 프론트 엔드 예 : 웹 페이지 텍스트의 내용을 변경하십시오. 2. 백엔드 예제 : node.js 서버를 만듭니다.

Python 또는 JavaScript는 경력 개발, 학습 곡선 및 생태계를 기반으로해야합니다. 1) 경력 개발 : Python은 데이터 과학 및 백엔드 개발에 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 적합합니다. 2) 학습 곡선 : Python 구문은 간결하며 초보자에게 적합합니다. JavaScript Syntax는 유연합니다. 3) 생태계 : Python에는 풍부한 과학 컴퓨팅 라이브러리가 있으며 JavaScript는 강력한 프론트 엔드 프레임 워크를 가지고 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.