Blockchain Game Tutorial

Do you have scanty knowledge about Blockchain? Do you want to develop a game over the power of Blockchain? Do you want to launch a game? Then Cheers you have landed on the right blog! In this blog, I will docent you on how to develop a game using Node JS Express over Blockchain technology. If you follow all the process then, I bet you will be able to launch your own crypto game in a few days & who knows it may hit high in the sky.

So Hold tight & trust your faith.

Flecks:

Prerequisite System Flow Smart Contract Setup Coding Concluding

1.Prerequisites:

i. Apprentices who want to deepen their practical Smart Contract skills in a fun way.

ii. A basic grasp of Smart Contract, NodeJS & Socket.

iii. Patience to handle ups & down in code.

2. System Flow:

System Flow will guide you to understand the flow of the game.

System Flow Diagram

3. Smart Contract:

Smart Contract is a heart of any crypto game. Everything is managed by it & so declare all the function wisely. Open remix IDE online and write below code.

pragma solidity ^0.5.0; contract casino{

address owner = msg.sender; struct player{ address id; uint bet; uint amount; }

mapping (uint => player) players;

player[] player_array; address payable[] player_address_array; modifier onlyOwner() {require(msg.sender == owner); _; } function play(uint _bet) payable public{ for(uint start=0 ; start <player_array.length;start++){

if(_bet == player_array[start].bet){

revert(“You have select different bet no”);

}

} player memory plays = player(msg.sender,_bet,msg.value );

player_array.push(plays);

player_address_array.push(msg.sender);

}



function drawwinner() onlyOwner payable public returns(uint randomnumber){

randomnumber = uint(blockhash(block.number-1)) %10;

for(uint start=0 ; start <player_array.length ; start++){

if(randomnumber==player_array[start].bet){

player_address_array[start].transfer(player_array[start].amount*2);

}

}

}

}

Now unlock MetaMask & set Ropsten Testnet, after that click on Run & then set Environment to Injected Web3 & Deloy the Contract.

4. Setup:

4.1 Install Node Js



curl -sL

sudo apt install nodejs

node -v

npm -v sudo apt install curlcurl -sL https://deb.nodesource.com/setup_8.x | sudo bash -sudo apt install nodejsnode -vnpm -v

4.2 Clone this repo to get node folder skeleton.



npm install

npm start git clone https://github.com/YudizBlockchain/Simple-NodeJS-Server.git npm installnpm start

4.3 Now open folder in an editor.

5. Coding:

5.1 Install the node module for the project.

npm i — save web3

npm i — save socket.io

npm i — save request

5.2 Socket code:

The socket is the most critical part to manage players in the game. So practice & learn it adequately. Write below code in the server.js file.

var io = require(‘socket.io’).listen(app.listen(port));

io.sockets.on(‘connection’, function (socket) {

socket.on(‘adduser’, function(username,data,sessionVar,callback){

socket.join(rooms);

socket.emit(‘updatechat’, ‘SERVER’, username +’ have connected to “‘ +rooms);

socket.broadcast.to(rooms).emit(‘updatechat’, ‘SERVER’, username + ‘ has connected to this room’);

socket.emit(‘updaterooms’, rooms, rooms);

});

socket.on(‘disconnect’, function(){ delete usernames[socket.username]; socket.broadcast.emit(‘updatechat’, ‘SERVER’, socket.username + ‘ has disconnected’);

socket.leave(socket.room);

});

});

5.3 Router code:

The router is used to route the flow of the website from the client side to the server side. It acts as a mediator in node js. Write below code in router.js inside the controller folder.

router.get(‘/home’, flukyClient.homeRedirect);

router.get(‘/main’, flukyClient.mainRedirect);

router.post(‘/SetRoom’, flukyClient.SetRoom);

router.post(‘/logoutUser’, flukyClient.logoutUser);

5.4 Server function:

The server will maintain the server side, how the user requests the server accordingly that the server will response it. Write below code in serverFunctions.js inside the controller folder.

exports.homeRedirect = function (req,res,next){

res.render (“home”,{req:req,res:res});

} exports.logoutUser = function (req,res,next){ let logout = req.body.logout;

if(logout==”true”){

req.session.destroy((error)=>{

if(error){

console.log(error);

}

});

}

else{

console.log(‘logout error’)

}

res.send({

‘msg’:’success’

});

}

5.5 Interact Smart Contract:

Create ABI.txt file inside /html/js folder & paste ABI code in that file.

[

{

“constant”: false,

“inputs”: [

{

“name”: “betNo”,

“type”: “uint256”

} ],

“name”: “play”,

“outputs”: [

{

“name”: “success”,

“type”: “bool”

}

],

“payable”: true, “type”: “function”

}

]

Now Create ABI.js file inside /html/js folder & paste below code.

var mainContractAddress = ‘#Contract_Address’; function showGetResult()

{

var result = null;

$.ajax({

url: “./ABI.txt”,

type: ‘get’,

dataType: ‘json’,

async: false,

success: function(data) {

result = data;

}

});

return result;

} Code to interact with the smart contract in your file. var web3 = new Web3(web3.currentProvider);

var callContract = web3.eth.contract(

showGetResult() //it will call from ABI.js file

); var contractAddress = callContract.at(mainContractAddress);

$(‘#pay’).click(function() {

contractAddress.play($($(‘#betNo’).val(),{from: web3.eth.accounts[0], gas:3000000},function(error,result){

if(! error){

console.log(result);

}

});

});

6. Concluding:

Voila!! You had just done with the backend part & now Design attractive GUI for the same & you are ready to Rock the Crypto World.

Above codes is the basic way to build the crypto game. The development is gigantic like an ocean, dive in deep & apply your creative mind to make an extraordinary game like never created before. All the Best!