자동 점프 공룡 스크립트를 만드는 여정
잠이 안 왔어요. 어쩌면 아까 마셨던 커피 세 잔 때문이었을 수도 있고, 아니면 생각이 복잡해서였을 수도 있습니다. 그럼에도 불구하고 나는 안절부절 못하고 표류할 수 없다는 것을 깨달았습니다. 불면증과 싸우는 대신 코딩을 하기로 결정했습니다. 그리고 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 < 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.
