From 7d44614efb48993889af1f27c64309dc07034c6a Mon Sep 17 00:00:00 2001 From: Ready Worker One <41317229+sheadelany@users.noreply.github.com> Date: Fri, 13 Oct 2023 20:42:14 -0600 Subject: [PATCH] Create script.js 3 of 3 WB Game --- script.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 script.js diff --git a/script.js b/script.js new file mode 100644 index 0000000..87559de --- /dev/null +++ b/script.js @@ -0,0 +1,42 @@ +document.addEventListener('keydown', movePlayer); +let player = document.getElementById('player'); +let ronin = document.getElementById('ronin'); + +function movePlayer(e) { + let playerStyle = window.getComputedStyle(player); + let playerLeft = parseInt(playerStyle.left); + let playerTop = parseInt(playerStyle.top); + + if (e.key === 'ArrowLeft' && playerLeft > 0) { + player.style.left = (playerLeft - 10) + 'px'; + } + if (e.key === 'ArrowRight' && playerLeft < 550) { + player.style.left = (playerLeft + 10) + 'px'; + } + if (e.key === 'ArrowUp' && playerTop > 0) { + player.style.top = (playerTop - 10) + 'px'; + } + if (e.key === 'ArrowDown' && playerTop < 350) { + player.style.top = (playerTop + 10) + 'px'; + } + + checkCollision(); +} + +function checkCollision() { + let playerRect = player.getBoundingClientRect(); + let roninRect = ronin.getBoundingClientRect(); + + if (playerRect.x < roninRect.x + roninRect.width && + playerRect.x + playerRect.width > roninRect.x && + playerRect.y < roninRect.y + roninRect.height && + playerRect.y + playerRect.height > roninRect.y) { + alert("Battle with Ronin!"); + resetPositions(); + } +} + +function resetPositions() { + player.style.left = '0px'; + player.style.top = '0px'; +}