1
\$\begingroup\$

I'm new to JS, so I'm most likely coding badly. Can you please point out the errors and correct the code? the site complains that it needs to write more text, but I don’t know what else to write

HTML

<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>Cookie clicker</title>

    <link rel="stylesheet" href="./css/normalize.css">
    <link rel="stylesheet" href="./css/style.css">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">

    <link rel="icon" href="./favicon.ico" type="image/x-icon">
</head>

<body>

    <div class="info">
        <h1>Cookie clicker v2.0 BETA</h1>
        <h2>Made by <span>Wellmare</span></h2>
    </div>

    <div class="game">

        <div class="cookie-wrapper">
            <h2>Cookies: <strong><span id="cookie-counter">0</span></strong></h2>

            <div class="button" id="button">
                <img src="./img/biscuit-clip-art-43.png" alt="cookie" class="cookie">
            </div>
        </div>

        <div class="info-game">

            <h3>You are getting: <strong><span id="cookie-per-sec">0</span></strong> per second</h3>
            <h3>You are getting: <strong><span id="cookie-per-click">1</span></strong> per click</h3>

        </div>

        <div class="btns-upgrade">
            <div class="buttons-upgrades">
                <div class="button-upgrade" id="per-click">
                    <h4 class="button-name">Cookie Per Click</h4>
                    <h5 class="price-to-user-value">Price to <span class="user-value-upgrade">5</span> Upgrades:
                        <span class="price-user">125</span> Cookies
                    </h5>
                    <div class="buttons-wrapper">
                        <div class="tabs-counts">
                            <div class="tab-count tab-count-per-click active">1</div>
                            <div class="tab-count tab-count-per-click">5</div>
                            <div class="tab-count tab-count-per-click">10</div>
                            <div class="tab-count tab-count-per-click">MAX</div>
                        </div>
                        <div class="button-buy">BUY</div>

                    </div>
                    <h5 class="price-to-1">Price to 1 Upgrade: <span class="price-1">25</span> Cookies</h5>
                </div>

                <div class="button-upgrade" id="per-sec">
                    <h4 class="button-name">Cookie Per Second</h4>
                    <h5 class="price-to-user-value">Price to <span class="user-value-upgrade">5</span> Upgrades:
                        <span class="price-user">250</span> Cookies
                    </h5>
                    <div class="buttons-wrapper">
                        <div class="tabs-counts">
                            <div class="tab-count tab-count-per-sec active">1</div>
                            <div class="tab-count tab-count-per-sec">5</div>
                            <div class="tab-count tab-count-per-sec">10</div>
                            <div class="tab-count tab-count-per-sec">MAX</div>
                        </div>
                        <div class="button-buy">BUY</div>

                    </div>
                    <h5 class="price-to-1">Price to 1 Upgrade: <span class="price-1">50</span> Cookies</h5>
                </div>
            </div>


        </div>

        <div class="reset-data-wrapper">
            <a class="reset-data">Reset data</a>
        </div>

    </div>



    <script src="js/newScript.js"></script>

</body>

</html>

JS

// Home button Cookie
const button = document.querySelector('.cookie')

// Home cookie counter
const cookieCounter = document.querySelector('#cookie-counter')

// Counters with number of cookies per click/sec
const cookiePerClickCounter = document.querySelector('#cookie-per-click')
const cookiePerSecCounter = document.querySelector('#cookie-per-sec')

// Reset button
const btnResetData = document.querySelector('.reset-data')

// Cards with the purchase of cookies per click / sec
const cardsWithBuyUpgrade = document.querySelectorAll('.button-upgrade')

// Number of Upgrades to purchase assigned by the user
const countsUpgradesPerUser = document.querySelectorAll('.user-value-upgrade')

// Upgrade prices for purchase from the user
const pricesUpgradesPerUser = document.querySelectorAll('.price-user')

// Prices for 1 upgrade
const pricesPerOneUpgrade = document.querySelectorAll('.price-1')

// Buttons to buy upgrades
const btnsBuyUpgrade = document.querySelectorAll('.button-buy')

// Tabs on the card with buy per click
const tabsCountPerClick = document.querySelectorAll('.tab-count-per-click')

// Tabs on the card with a purchase in a second
const tabsCountPerSec = document.querySelectorAll('.tab-count-per-sec')

// Local variables

let countCookie = 0
let clickSize = 1
let countCookiePerSec = 0
let priceUpgrades = [25, 50]

// Getting values ​​from Local storage
getValuesLocalStorage()

// Change the number of upgrades at a time
// Per click
changeCountUpgradeAtATime(
    countsUpgradesPerUser[0],
    pricesUpgradesPerUser[0],
    1,
    priceUpgrades[0]
)
// Per sec
changeCountUpgradeAtATime(
    countsUpgradesPerUser[1],
    pricesUpgradesPerUser[1],
    1,
    priceUpgrades[1]
)


// Adding cookies every second
const perSecondInterval = setInterval(() => {
    changeCookieCount(countCookiePerSec)
}, 1000)

// Clicking the cookie button
button.addEventListener('click', () => {
    changeCookieCount(clickSize)
})

// Pressing the reset button
btnResetData.addEventListener('click', resetData)

// Pressing the upgrade buttons
let countUpgradesForClick
cardsWithBuyUpgrade[0].addEventListener('click', (e) => {

        let countUpgrades
        let costOneUpgrade = priceUpgrades[0]

        // If you clicked on the tab, then
        if (e.target.classList.contains('tab-count')) {

            if (e.target.textContent === 'MAX') {
                if (countCookie >= costOneUpgrade) {
                    countUpgradesForClick = 1
                    hideAllTab(tabsCountPerClick)
                    e.target.classList.add('active')
                    maxCountUpgrade(1, priceUpgrades[0], 0)
                } else {
                    alert('Недостаточно печенек для покупки')
                }
            } else {
                hideAllTab(tabsCountPerClick)
                e.target.classList.add('active')

                countUpgrades = +e.target.textContent
                costOneUpgrade = priceUpgrades[0]

                finalPrice = countUpgrades * costOneUpgrade
                console.log(countUpgrades, costOneUpgrade, finalPrice)

                changeCountUpgradeAtATime(
                    countsUpgradesPerUser[0],
                    pricesUpgradesPerUser[0],
                    countUpgrades,
                    costOneUpgrade
                )
            }
        }
        // If you clicked on the button-buy, then
        if (e.target.classList.contains('button-buy')) {
            if (countCookie >= +countsUpgradesPerUser[0].textContent * costOneUpgrade) {
                countUpgrades = +countsUpgradesPerUser[0].textContent
                changeCookieCount(-+countsUpgradesPerUser[0].textContent * costOneUpgrade)
                changeCookiePerClick(countUpgrades)

                costOneUpgrade *= 2
                changeCookiePerOneUpgrade(pricesPerOneUpgrade[0], costOneUpgrade, 0)

                changeCountUpgradeAtATime(
                    countsUpgradesPerUser[0],
                    pricesUpgradesPerUser[0],
                    countUpgrades,
                    costOneUpgrade
                )
                localStorage.setItem('PriceToOneClick', priceUpgrades[0])
            } else {
                alert('Недостаточно печенек для покупки')
            }
        }
    }
)


let countUpgradesForSec
cardsWithBuyUpgrade[1].addEventListener('click', (e) => {

    let countUpgrades
    let costOneUpgrade = priceUpgrades[1]

    // If you clicked on the tab, then
    if (e.target.classList.contains('tab-count')) {

        if (e.target.textContent === 'MAX') {
            if (countCookie >= costOneUpgrade) {
                countUpgradesForSec = 1
                hideAllTab(tabsCountPerSec)
                e.target.classList.add('active')
                maxCountUpgrade(1, priceUpgrades[1], 1)
            } else {
                alert('Недостаточно печенек для покупки')
            }
        } else {
            hideAllTab(tabsCountPerSec)
            e.target.classList.add('active')

            countUpgrades = +e.target.textContent
            costOneUpgrade = priceUpgrades[1]

            finalPrice = countUpgrades * costOneUpgrade
            console.log(countUpgrades, costOneUpgrade, finalPrice)

            changeCountUpgradeAtATime(
                countsUpgradesPerUser[1],
                pricesUpgradesPerUser[1],
                countUpgrades,
                costOneUpgrade
            )
        }
    }
    // If you clicked on the button-buy, then
    if (e.target.classList.contains('button-buy')) {
        if (countCookie >= +countsUpgradesPerUser[1].textContent * costOneUpgrade) {
            countUpgrades = +countsUpgradesPerUser[1].textContent
            changeCookieCount(-+countsUpgradesPerUser[1].textContent * costOneUpgrade)
            changeCookiePerSec(countUpgrades)

            costOneUpgrade *= 2
            changeCookiePerOneUpgrade(pricesPerOneUpgrade[1], costOneUpgrade, 1)

            changeCountUpgradeAtATime(
                countsUpgradesPerUser[1],
                pricesUpgradesPerUser[1],
                countUpgrades,
                costOneUpgrade
            )
            localStorage.setItem('PriceToOneSec', priceUpgrades[1])
        } else {
            alert('Недостаточно печенек для покупки')
        }
    }
})

// * FUNCTION

function getValuesLocalStorage() {
    if (localStorage.getItem('CountCookie')) {
        setCookieCount(+localStorage.getItem('CountCookie'))
    }
    if (localStorage.getItem('CookiePerClick')) {
        clickSize = +localStorage.getItem('CookiePerClick')
        cookiePerClickCounter.textContent = clickSize
    }
    if (localStorage.getItem('CookiePerSec')) {
        countCookiePerSec = +localStorage.getItem('CookiePerSec')
        cookiePerSecCounter.textContent = countCookiePerSec
    }
    if (localStorage.getItem('PriceToOneClick')) {
        priceUpgrades[0] = localStorage.getItem('PriceToOneClick')
        changeCookiePerOneUpgrade(pricesPerOneUpgrade[0], priceUpgrades[0], 0)
    }
    if (localStorage.getItem('PriceToOneSec')) {
        priceUpgrades[1] = localStorage.getItem('PriceToOneSec')
        changeCookiePerOneUpgrade(pricesPerOneUpgrade[1], priceUpgrades[1], 1)
    }
}

function changeCookieCount(count) {
    countCookie = countCookie + count
    cookieCounter.textContent = countCookie
    localStorage.setItem('CountCookie', countCookie)
}

function setCookieCount(count) {
    countCookie = count
    cookieCounter.textContent = countCookie
    localStorage.setItem('CountCookie', countCookie)
}

function changeCookiePerClick(count) {
    clickSize += count
    cookiePerClickCounter.textContent = clickSize
    localStorage.setItem('CookiePerClick', clickSize)
}

function changeCookiePerSec(count) {
    countCookiePerSec += count
    cookiePerSecCounter.textContent = countCookiePerSec
    localStorage.setItem('CookiePerSec', countCookiePerSec)
}

function resetData() {
    clickSize = 1
    countCookie = 0
    countCookiePerSec = 0
    localStorage.clear()
    cookiePerClickCounter.textContent = 1
    cookiePerSecCounter.textContent = 0
}

function hideAllTab(tabs) {
    tabs.forEach((tab) => tab.classList.remove('active'))
}

function changeCountUpgradeAtATime(
    placeCountEl,
    placePriceEl,
    count,
    priceToOne
) {
    placeCountEl.textContent = count
    placePriceEl.textContent = count * priceToOne
}

function changeCookiePerOneUpgrade(place, value, index) {
    place.textContent = value
    priceUpgrades[index] = value
}

function maxCountUpgrade(countUpgrades, costOneUpgrade, index) {
    while (countUpgrades * costOneUpgrade <= countCookie) {
        if ((countUpgrades + 1) * costOneUpgrade > countCookie) {
            changeCountUpgradeAtATime(
                countsUpgradesPerUser[index],
                pricesUpgradesPerUser[index],
                countUpgrades,
                costOneUpgrade
            )
            break
        } else {
            countUpgrades++
        }
    }
}
\$\endgroup\$
1
  • 3
    \$\begingroup\$ I suggest you translate the comments from Russian to English. Otherwise, you prune away like 95% of all the developers reading your code. \$\endgroup\$
    – coderodde
    Commented Apr 27, 2022 at 14:55

1 Answer 1

1
\$\begingroup\$

Your code looks nice at least, it's clearly written! Of course there is always room for improvement. A few things that I noticed:

  1. You can store all your values into localstorage at the same time by using JSON.stringify

      let allmyvalues = [clickSize, countCookie, ...etc]
      localStorage.setItem("cookiedata",JSON.stringify(allmyvalues));
    
  2. The code for the UI and the code for the game logic are a bit mixed. You check if a button has a CSS class to know which button it is, but this can be hard to refactor if you want to reuse your cookieclicker logic. I suggest you separate the game logic from the UI even more.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thank you, this code it was written a long time ago, and I'm already studying react, I don't consider this project "good" for myself \$\endgroup\$
    – Wellmare
    Commented Aug 11, 2022 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.