Build a Hand Cricket Multiplayer Game in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

 

 

 

index.html

 

 

<!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">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.0.3/tailwind.min.css">
  <link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.5.5/css/simple-line-icons.min.css">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=DotGothic16&display=swap" rel="stylesheet">
  <title>White Background Image Remover</title>
  <meta name="description" content="An easy and fast way to remove the white background from an image and delivery a PNG image as result.">
  <meta name="keywords" content="white, background, remover, easy, fast, PNG">
  <style type="text/css">
    html, body{
      font-family: 'DotGothic16', sans-serif;
    }
</style>  
</head>
<body class="w-screen h-screen flex flex-col justify-start items-center bg-blue-300">
  <header class="mt-10 mb-10 text-center">
    <h1 class="text-5xl font-extrabold">White Background Remover</h1>
    <h2 class="leading-8 mt-2 max-w-xl">An easy and fast way to remove the white background from an image and delivery a PNG image as result</h2>
  </header>
  <form action="#" id="image-form" enctype="multipart/form-data" class="border-2">
    <input type="file" name="image-input" id="image-input" class="w-0 h-0">
    <label for="image-input" id="image-label" class="cursor-pointer pl-16 pr-16">Click here to image upload</label>
    <button class="pt-2 pb-2 pl-10 pr-10 bg-gray-400 hover:bg-blue-200 transition-all duration-300" type="submit">Remove Background</button>
  </form>
  <div id="preview-section" class="mt-10">
    <div class="preview-original-image"></div>
    <canvas id="canvas"></canvas>
  </div>
  <a id="download-button" download="image-with-removed-white-bg.png" class="fixed right-10 top-12 bg-yellow-300 hover:bg-yellow-400 cursor-pointer transition-all duration-300 pl-12 pr-12 pt-10 pb-10 shadow">
    <span type="button" class="text-2xl uppercase">Download</span>
    <span class="icon-arrow-down-circle text-2xl"></span>
  </a>
  <script>
    const ORIGINAL_IMAGE_ID = "original-img";
const CANVAS_ID = "canvas";
const FORM_ID = "image-form";
const DOWNLOAD_BUTTON_ID = "download-button";
const IMAGE_INPUT_ID = "image-input";
const IMAGE_LABEL_ID = "image-label";

window.onload = () => {
  Listeners.inputFileChange(IMAGE_INPUT_ID, IMAGE_LABEL_ID);
  Listeners.formSubmit(FORM_ID);
  Listeners.downloadButton(DOWNLOAD_BUTTON_ID, ORIGINAL_IMAGE_ID, CANVAS_ID);
};

const Listeners = {
  formSubmit: (formId) => {
    const form = document.getElementById(formId);
    form.addEventListener("submit", (formEvent) => {
      formEvent.preventDefault();
      ImageProcessor.getImageDataFromInputFile("#image-form input[type=file]")
        .then((imageData) => ImageProcessor.getImageObject(imageData))
        .then((imageObject) =>
          ImageProcessor.createPreviewAndCanvas(
            imageObject,
            ORIGINAL_IMAGE_ID,
            CANVAS_ID,
            ImageProcessor.drawImageOnCanvas
          )
        );
    });
  },
  downloadButton: (downloadButtonId, originalImageId, canvasId) => {
    const downloadButtonElement = document.getElementById(downloadButtonId);
    const canvasElement = document.getElementById(canvasId);
    downloadButtonElement.addEventListener("click", (event) => {
      const originalImage = document.getElementById(originalImageId);
      if (!originalImage) event.preventDefault();
      const imageToDownload = canvasElement
        .toDataURL("image/png")
        .replace("image/png", "image/octet-stream");
      downloadButtonElement.setAttribute("href", imageToDownload);
    });
  },
  inputFileChange: (imageInputId, imageLabelId) => {
    const input = document.getElementById(imageInputId);
    input.addEventListener("change", (event) => {
      const label = document.getElementById(imageLabelId);
      label.innerText = event.target.files[0].name;
    });
  },
};

const ImageProcessor = {
  getImageDataFromInputFile: (query) => {
    const imageData = document.querySelector(query).files[0];
    return new Promise((resolve) => resolve(imageData));
  },
  getImageObject: (imageData) => {
    const fileReader = new FileReader();
    const imageObject = new Image();
    fileReader.readAsDataURL(imageData);
    fileReader.onload = (event) => {
      imageObject.src = event.target.result;
    };
    return new Promise((resolve) => resolve(imageObject));
  },
  createPreviewAndCanvas: (imageObject, imageId, canvasId, canvasCallback) => {
    const imageElement = document.createElement("img");
    imageObject.onload = () => {
      const oldImage = document.getElementById(imageId);
      if (oldImage) {
        oldImage.remove();
      }
      imageElement.src = imageObject.src;
      imageElement.width = imageObject.width;
      imageElement.height = imageObject.height;
      imageElement.id = imageId;
      imageElement.className = "hidden";

      document
        .querySelector(".preview-original-image")
        .appendChild(imageElement);

      canvasCallback(canvasId, imageId);
    };

    return new Promise((resolve) => resolve());
  },
  drawImageOnCanvas: (canvasElementId, originalImageElementId) => {
    const canvas = document.getElementById(canvasElementId),
      originalImage = document.getElementById(originalImageElementId),
      canvasContext = canvas.getContext("2d");

    canvas.height = originalImage.height;
    canvas.width = originalImage.width;
    canvasContext.drawImage(originalImage, 0, 0);

    const imageData = canvasContext.getImageData(
        0,
        0,
        originalImage.width,
        originalImage.height
      ),
      pixels = imageData.data,
      transparency = { r: 0, g: 0, b: 0, a: 0 };

    for (
      let cursor = 0, totalOfPixels = pixels.length;
      cursor < totalOfPixels;
      cursor += 4
    ) {
      let r = pixels[cursor],
        g = pixels[cursor + 1],
        b = pixels[cursor + 2];

      if (r === 255 && g === 255 && b === 255) {
        pixels[cursor] = transparency.r;
        pixels[cursor + 1] = transparency.g;
        pixels[cursor + 2] = transparency.b;
        pixels[cursor + 3] = transparency.a;
      }
    }

    canvasContext.putImageData(imageData, 0, 0);
  },
};
  </script>
</body>
</html>

 

 

style.css

 

 

@import 'https://fonts.googleapis.com/css?family=Noto+Sans+JP';

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
 }

body {
    font-family: "Noto Sans JP", sans-serif; 
/*	font-family: "Times New Roman", Times, serif; */
height: 100vh;
	background: url('../imgs/background.jpg'), radial-gradient(#444, #111);
	background-position: center center;
	background-attachment: fixed;
	background-repeat: no-repeat;
	background-blend-mode: multiply;
	background-size: cover;
	color: #fff;
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	align-items: center;

}


.toss {
	text-align: center;
	}

.headlines {
	display: flex;
	font-size: 48px;
}
.headlines > * {
	padding: 20px;
}
#OddEven{
	background-image: url('imgs/cricket-sports-concept-toss-illustration-coin-projection-stylish-text-game-50406653.jpg');
	background-repeat: no-repeat;
	font-size: 50px;
	
}
.but{
	width:200px;
	height:80px;
	font-size:30px;
	outline: 0;
	border: 0;
	border-radius: 4px;
}
.but-yellow {
	color:blue;
	background-color: yellow;
}
.but-blue {
	color: white;
	background-color: blue;
}
.but1{
	width:200px;
	height:100px;
	font-size:30px;
}
#ask_user_bat{
	font-size:100px;
	text-align:center;
}
#inp {
  padding: 20px;	
text-align: center;
	border-style: groove;
	font-size:100px;

}
.but2{
	width:100px;
	height:50px;
}

 

 

script.js

 

 

var OE = -1;			//0 odd & 1 even
var inp
var callback;
var userBats = -1;	//if user bats(1) or bowls(0) in first innings
var userScore = 0, cpuScore = 0;

function S(id) {
	return document.getElementById(id);
}

function set_OE(i) {
	OE = i;
	console.log("User chose " + ((i) ? "Even" : "Odd"));
	S("OddEven").style.display = "none";
	get_inp("do_toss");
}

function get_OE() {
	S("OddEven").style.display = "block";
}

function set_inp(i) {
	inp = i;
	console.log("User chose " + i);
	S("inp").style.display = "none";
	window[callback](i);
	//eval(callback+"(i)");
}

function get_inp(_callback) {
	S("inp").style.display = "block";
	callback = _callback;
}

function get_cpu_inp() {
	var c = Math.floor(Math.random() * 6 + 1);
	console.log("Cpu chose : " + c);
	return c;
}

function set_userBats(i) {
	userBats = i;
	console.log("User chose to " + ((userBats) ? "Bat" : "Bowl") + " first");
	S("ask_user_bat").style.display = "none";
	if (userBats)
		userBat();
	else
		cpuBat();
	S("score_board").style.display = "block";
	S("choice_board").style.display = "block";
}

function askUserBat() {
	S("ask_user_bat").style.display = "block";
}

function do_toss(i) {
	var userToss = i;
	var cpuToss = get_cpu_inp();
	var toss = userToss + cpuToss;
	if ((toss % 2 == 0 && OE) || (toss % 2 && !OE))
		askUserBat();
	else {
		userBats = 0;	//cpu bats
		console.log("User has to Bowl first");
		S("score_board").style.display = "block";
		S("choice_board").style.display = "block";
		alert("You have lost the toss. You have to bowl first")
		cpuBat();
	}
}

function cpuBat() {
	get_inp("addCpuScore");
}

function userBat() {
	get_inp("addUserScore");
}

function addUserScore(i) {
	cpu_inp = get_cpu_inp();
	S("user_choice").innerHTML = i;
	S("cpu_choice").innerHTML = cpu_inp;
	if (cpu_inp == i) {
		console.log("User has been declared out");
		alert("You have been dismissed for " + userScore + " runs");
		if (userBats == 1) {
			cpuBat();
		} else {
			//match over
			if (userScore >= cpuScore) {
				console.log("User won the match");
				alert("You won!!!");
			} else {
				console.log("User lost the match");
				alert("You lost!!!");
			}
		}
	} else {
		userScore += i;
		console.log("User Score : " + userScore)
		S("user_score").innerHTML = userScore;
		if (userBats == 0 && userScore >= cpuScore) {
			console.log("User won the match");
			alert("You won!!!");
		} else
			get_inp("addUserScore");
	}
}

function addCpuScore(i) {
	cpu_inp = get_cpu_inp();
	S("user_choice").innerHTML = i;
	S("cpu_choice").innerHTML = cpu_inp;
	if (cpu_inp == i) {
		console.log("Cpu has been dismissed for " + cpuScore + " runs");
		alert("CPU has been dismissed for " + cpuScore + " runs")
		if (userBats == 0) {
			userBat();
		} else {
			//match over
			if (userScore >= cpuScore) {
				console.log("User won the match");
				alert("You won the match by " + parseInt(userScore - cpuScore) + " runs");
			} else {
				console.log("User lost the match");
				alert("You lost the match by" + parseInt(cpuScore - userScore) + " runs");
			}
		}
	} else {
		cpuScore += cpu_inp;
		console.log("Cpu Score : " + cpuScore);
		S("cpu_score").innerHTML = cpuScore;
		if (userBats == 1 && userScore < cpuScore) {
			console.log("User lost the match");
			alert("You lost!!!");
		} else
			get_inp("addCpuScore");
	}
}

get_OE();

 

 

DOWNLOAD FULL SOURCE CODE

 

 

Leave a Reply