How to Create a Simple Crypto Clicker Game

Posted By : Devashish

Jun 19, 2024

Creating a simple crypto clicker game is a fun way to learn the basics of crypto development. In this tutorial, we build a basic crypto clicker game where users can earn cryptocurrency by clicking a button. We will use HTML, CSS, and JavaScript for the front end and a simple Ethereum smart contract to handle the blockchain logic.

 

Project Structure

 

Let's start by setting up the project structure. Create a new folder for your project and inside it, create the following files:

 

  • index.html
  • styles.css
  • script.js
  • contract.sol (for the Ethereum smart contract)

 

Step 1: HTML Structure

 

We'll start by creating a simple HTML structure. Open index.html and add the following code:

 

<!DOCTYPE html>
<html lang='en'>
<head>
   <meta charset='UTF-8'>
   <meta name='viewport' content='width=device-width, initial-scale=1.0'>
   <title>Crypto Clicker Game</title>
   <link rel='stylesheet' href='styles.css'>
</head>
<body>
   <div class='game-container'>
       <h1>Crypto Clicker</h1>
       <div id='crypto-account'>Connect Wallet</div>
       <div id='crypto-count'>0</div>
       <button id='click-button'>Click me!</button>
   </div>
   <script src='script.js'></script>
</body>
</html>

 

Also, Explore |  How to Develop a Crypto Swap Aggregator Platform

 

Step 2: Styling with CSS

 

Next, we'll add some basic styles to make our game look nicer. Open styles.css and add the following code:

 

body {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;
   margin: 0;
   font-family: Arial, sans-serif;
   background-color: #f0f0f0;
}

.game-container {
   text-align: center;
   background: white;
   padding: 20px;
   border-radius: 10px;
   box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
   width:300px;
   max-width: 100%;
}

#crypto-account{
   padding:8px 12px;
   background-color: #f2f2f2;
   border-radius: 2px;
   max-width:100%;
   word-break: break-all;
}

#crypto-count {
   font-size: 2em;
   margin: 20px 0;
}

#click-button {
   padding: 10px 20px;
   font-size: 1em;
   cursor: pointer;
}

 

You may also like | Staking Platform Development: A Step-by-Step Guide

 

Step 3: JavaScript Functionality

 

Now, let's add the game logic. Open script.js and add the following code:

 

document.addEventListener('DOMContentLoaded', (event) => {
 let count = 0;
 const cryptoCountElement = document.getElementById('crypto-count');
 const clickButton = document.getElementById('click-button');

 clickButton.addEventListener('click', () => {
     count++;
     cryptoCountElement.innerText = count;
 });
});

 

Step 4: Ethereum Smart Contract

 

We'll create a simple Ethereum smart contract to handle the blockchain logic. Open contract.sol and add the following code:

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract CryptoClicker {
   mapping(address => uint256) public balances;

   function earnCrypto() public {
       balances[msg.sender] += 1;
   }

   function getBalance() public view returns (uint256) {
       return balances[msg.sender];
   }
}

 

This contract allows users to earn cryptocurrency by calling the earnCrypto function and to check their balance using the getBalance function.

 

Step 5: Interacting with the Smart Contract

 

To interact with the Ethereum smart contract, we will use the Web3.js library. Add the following script tag to the end of your index.html file to include Web3.js:

 

<script src='https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js'></script>

 

Update your script.js to include Web3.js integration:

 

document.addEventListener('DOMContentLoaded', async (event) => {

   let count = 0;
   const cryptoCountElement = document.getElementById('crypto-count');
   const cryptoAccountElement = document.getElementById('crypto-account');
   const clickButton = document.getElementById('click-button');

   if (typeof web3 !== 'undefined') {
       console.log('Web3 Detected! Using provider:', web3.currentProvider.constructor.name);
       window.web3 = new Web3(web3.currentProvider);
   } else {
       console.log('No Web3 Detected... using HTTP Provider');
       window.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); // Replace with your provider URL if needed
   }
   console.log('web3 initiated', window.web3);
    const eth = window?.web3?.eth; // Utilize optional chaining for safety
   let accounts = [];
    if (!eth) {
     console.error('Web3 not available, functionality limited.');
   } else {
     accounts = await eth.getAccounts();
     if (accounts.length) {
       cryptoAccountElement.textContent = accounts[0];
     } else {
       cryptoAccountElement.addEventListener('click', async () => {
         const requestedAccounts = await eth.requestAccounts();
         if (requestedAccounts.length) {
           cryptoAccountElement.textContent = requestedAccounts[0];
         } else {
           console.warn('User denied access to accounts.');
         }
       });
     }
   }
    // Contract initialization (replace placeholders with actual values)
   const contractAddress = 'YOUR_CONTRACT_ADDRESS';
   const abi = [
     // The ABI of your smart contract
   ];
    let contract = null;
   if (contractAddress && abi.length) { 
     contract = new web3.eth.Contract(abi, contractAddress);
   }
    // Button click handler with error handling
   clickButton.addEventListener('click', async () => {
     count++;
     cryptoCountElement.innerText = count;
      if (!eth || !contract) {
       console.error('Web3 or contract not initialized. Functionality limited.');
       return;
     }
      const accounts = await eth.getAccounts();
     if (!accounts.length) {
       console.warn('No accounts found. Please connect a wallet.');
       return;
     }
     const account = accounts[0];
       contract?.methods.earnCrypto().send({ from: account })
           .then(() => {
               console.log('Crypto earned!');
           })
           .catch((error) => {
               console.error('Error earning crypto:', error);
           });
   });
});

 

Replace YOUR_CONTRACT_ADDRESS with the address of your deployed contract and include the ABI of your contract in the abi array.

 

Also, Check | Building a Crypto Launchpad: From Concept to Launch

 

Conclusion

 

Congratulations! You have created a simple crypto clicker game that integrates with the Ethereum blockchain. This project covered the basics of HTML, CSS, JavaScript, and blockchain integration using Web3.js. You can expand this game by adding more features, such as upgrades, leaderboards, or additional game mechanics. Have fun coding! If you are looking for crypto development services to build and launch your crypto project, connect with our skilled crypto developers for a quick discussion.  

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

October 18, 2024 at 04:04 am

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button
Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text