Coin Man

Today I am sharing a small and interesting project that I have created while learning JavaScript.

This Project is named Coin Man. So let's understand what has been performed in the Project.



As you already know HTML is data, CSS is the presentation and JS is the main brain for any web project. In this whole project, we will work only on these files.


Lets Start


1. Firstly I have created an Index.html file which contains two images one for a coin and another one is of a man who is catching coins.


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Coin Man</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <img id="player" src="character.gif" alt="character">
    <img id="coin" src="coin.gif" alt="coin">
    <script src="script.js"></script>
</body>

</html>


2. Next I have added the Style.css file which contains all the necessary CSS for the project. I also have added comments to tell, which function is performed by specific CSS.


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Coin Man</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <img id="player" src="character.gif" alt="character">
    <img id="coin" src="coin.gif" alt="coin">
    <script src="script.js"></script>
</body>

</html>


3. Now the main brain of the projects comes in i.e. Script.js file. It will handle the functionality of a coin and the man.


// Check whether the avatar is touching the coin
function isConnecting(a, b){
    const aRect = a.getBoundingClientRect();
    const bRect = b.getBoundingClientRect();
    return !(
        aRect.top + aRect.height < bRect.top || 
        aRect.top > bRect.top + bRect.height || 
        aRect.left + aRect.width < bRect.left || 
        aRect.left > bRect.left + bRect.width
    );
}

// Initial Method
const init = () => {
    const avatar = document.querySelector('#player');
    const coin = document.querySelector('#coin');
    // Moved the coin at start at random place
    moveCoin();
    // KeyUp event listener for moving the avatar
    // Down, Up, Right, Left
    window.addEventListener('keyup', function(e){
        if(e.key === 'ArrowDown' || e.key === 'Down'){
            moveVertical(avatar, 50);
        }
        else if(e.key === 'ArrowUp' || e.key === 'Up'){
            moveVertical(avatar, -50);
        }
        else if (e.key === 'ArrowRight' || e.key === 'Right') {
			moveHorizontal(avatar, 50);
            // Change the direction of avatar face
			avatar.style.transform = 'scale(1,1)';
		}
		else if (e.key === 'ArrowLeft' || e.key === 'Left') {
			moveHorizontal(avatar, -50);
			avatar.style.transform = 'scale(-1,1)';
		}
		if (isConnecting(avatar, coin)) moveCoin();
    });
}

// Move the avatar in vertical direction
const moveVertical = (element, amount) => {
	const currTop = extractPos(element.style.top);
	element.style.top = `${currTop + amount}px`;
};

// Move the avatar in horizontal direction
const moveHorizontal = (element, amount) => {
	const currLeft = extractPos(element.style.left);
	element.style.left = `${currLeft + amount}px`;
};

// return the postion by removing px from end
const extractPos = (pos) => {
	if (!pos) return 100;
	return parseInt(pos.slice(0, -2));
};

// move the coin at random position
const moveCoin = () => {
	const x = Math.floor(Math.random() * window.innerWidth);
	const y = Math.floor(Math.random() * window.innerHeight);
	coin.style.top = `${y}px`;
	coin.style.left = `${x}px`;
};

init();


getBoundingClientRect() method returns a DOMRect object which provides information about the size of an element and its position relative to the viewport.


addEventListener() method is used to attach an event handler to a particular element. It even does not override the existing event handlers as normal events do. Events are said to be an essential part of JavaScript as the element will respond according to the event that has been occurred.


addEventListener('keyup', function()) method is used to attach a key event for the element. When a key is pressed and released then this event will happen.


scale() method increases or decreases the size of an element according to the parameters given for the width and height. In this case, it is reverting the element (man catching coin) without changing the height and width of its scale (-1,1).



GitHub Linkhttps://github.com/chirag-goel360/Coin-Game-Js


References


getBoundingClientRect - https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect


addEventListener - https://www.w3schools.com/jsref/met_document_addeventlistener.asp


HTML Scale method - https://www.w3schools.com/tags/canvas_scale.asp



Happy Coding

Coders for Life 😍

Chirag Goel

I am a developer, likes to work on different future technologies.

Post a Comment (0)
Previous Post Next Post