1)for java programmers
import java.util.scanner;
public class main {
public static void main(string[] args) {
scaner scaner = new scanner(system.in);
system.out.println("what is your name?");
string name = scanner.nextline();
System.out.println("how old are you?");
int age = scanner.nextint();
scanner.nextline();
System.out.println("what is your favorite food?");
string food = scanner.nextline ();
System.out.println("hello "=name);
System.out.println("you are "+age+" years old");
System.out.println("you like "+food);
2)While loop
import java.util.Scanner;
public class main {
public static void main(string {[] args) {
//while loop = executes a block of code as long as a it's condition remains true
Scanner scanner = new scanner(system.in);
string name = "";
while(name.isBlank()) {
system.out.print("Enter your name:");
name = scanner.nextLine();
}
System.out.println("hello "+name);
}
}
3)how to link with .com pages HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>my bookmarks</title>
</head>
<body>
<h1>my bookmarks</h1>
<h2>primary bookmarks</h2>
<p><a target="_blank" href="https://www.google.com">open google</a></p>
<p><a target="_blank" href="https://www.facebook.com">open facebook</a></p>
<p><a target="_blank" href="https://www.youtube.com">open youtube</a></p>
<p><a target="_blank" href="https://www.Quara.com">open Quara</a></p>
<h3>secondary bookmarks</h3>
<p><a target="_blank" href="https://www.wekipedia.com">open wekipedia</a></p>
<h4>my bookmarks</h4>
</body>
</html>
4)IMAGE with FOOTER and THEAD
<!DOCTYPE html>
<html lang="en">
<title>image with footer thead</title>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>images with head footer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<img height="230" src="you can choose png heare" alt="train images" srcset="">
<br>
<table>
<caption>employe detales</caption>
<thead>
<th>hi we are website builder</th>
<th>welcome to webpage </th>
<thead>
<!-- header content-->!
header
</thead>
</thead>
<tfoot>
<!-- footer content-->
footer
</tfoot>
<tr>
<td colspan="2">hi ujjwal</td>
<td colspan="2"> hi </td>
<td colspan="2">this is athrva</td>
<td colspan="2"> athrva</td>
</tr>
<tr>
<td colspan="2">javasript</td>
<td rowspan="2">hi java</td>
</tr>
<thead>
<tr>
<th>name</th>
<th>destination</th>
<th>fav language</th>
</tr>
</thead>
<tbody>
<tr>
<td>harrys world</td>
<td>programmer</td>
<td colspan="2">js java</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>name</th>
<th>destination</th>
<th>fav language</th>
</tr>
</tfoot>
</table>
<ul type="square">
<li>krishna</li>
<li>shubham</li>
<li>soham</li>
</ul>
<ol type="square">
<li>manraj</li>
<li>shubham</li>
<li>youraj</li>
</ol>
</body>
</html>
5)how to add video??
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>video</title>
</head>
<body>
<video src="add the video" width="455" controls loop muted poster="add photo to thumbnail"video>>
<audio src="put any audio" controls autoplay loop></audio>
</body>
</html>
6)CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS</title>
<style>
span {
color: red;
}
div {
color: red;
background-color: yellow;
}
p {
color: violet;
background-color: blue;
}
</style>
</head>
<body>
<div>
hey i am Krishna and today i am in css mood
</div>
<div>
i am good
</div>
<span>
i am also good
</span>
<p>Hi this is my Bloger and welcome to my bloger in this bloger i am giving you so much beginner coding tips</p>
</body>
</html>
7)css boxmodel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css boxmodel</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
background-color: aqua;
}
.box1 {
color: yellow;
padding: 10px;
margin:35px;
border:2px solid blue;
height: 150px;
box-sizing: border-box;
}
.box2 {
color: red;
padding:10px;
margin:35px;
border:2px solid blue;
height: 150px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box box1">i am a box</div>
<div class="box box2">i am another box</div>
</body>
</html>
8)shadow desigh.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>display property</title>
<style>
.box {
border: 2px solid black;
padding: 34px;
box-shadow: 5px 15px #70a711;
}
.text-element {
text-shadow: 2px 2px 4px #ed1717
</style>
</head>
<body>
<div class="box">
i am krishna
</div>
<p class="text-element">hi this is a webpage with this wonderful beginner
coder area please comment and share and please support</p>
</body>
</html>
9) CSS flexbox
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS flexbox</title>
<style>
.container {
bprder: 2px solid red display: flex;
}
.item {
height: 52px;
width: 52px;
border: 2px solid black;
background: violet;
}
</style>
</head>
<body>
<main>
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</main>
</body>
</html>
10)Basic.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS basic</title>
</head>
<body>
<div class="box">
hey my blog members 1)inspect then console please in computer
</div>
<button>submit</button>
<script>
alert("hello world");
console.log("code is running")
console.log("code is wonderful")
console.log("code is running like a wow")
var a = prompt("enter your number")
var isTrue = confirm("are you sure you want to blast your computer?")
if (isTrue) {
console.log("computer is blasting")
}
else {
console.log("computer is not blasting")
}
console.log("your number is")
</script>
</body>
</html>
11)If else if.Js
console.log("hello i am blogger")
let age = 1;
//let grace = 2;
//age += grace
//console.log(age)
//console.log(age + grace)
//console.log(age - grace)
//console.log(age * grace)
//console.log(age / grace)
//console.log(age ** grace)
//console.log(age % grace)
/*
i am a
multiline
comment
*/
if(age!=18){
console.log("you can drive")
}
else if(age==0){
console.log("are you kidding?")
}
else if(age==1){
console.log("are you again kidding?")
}
else{
console.log("you cannot drive")
}
a = 6;
b = 8;
let C = a > b ? (a - b) : (b - a);
/*
translate to:
if(a>b){
let c = a - b;
}
else{
let c = a - b;
}
*/
12)loop.Js
console.log("i am in loop help")
let a = 1;
console.log(a)
console.log(a + 1)
console.log(a + 2)
console.log(a + 3)
console.log(a + 4)
for (let i = 0; i < 100; i++) {
console.log(a + i);
}
let obj = {
name: "Krishna",
role: "programmer",
Company: "Blogger"
}
for (const key in obj) {
const element = obj[key];
console.log(key, element)
}
for (const iterator of "krishna") {
console.log(c)
}
let i = 0;
while (i < 60) {
console.log(i)
i++;
}
let i = 10;
do {
console.log(i)
i++;
} while (i < 6);
13)Function.Js
function nice(name){
console.log("hey " + name + "you are nice! good etc")
}
function sum(a, b, c = 3) {
//console.log(a + b)
return a + b +c
}
result1 = sum(3, 5)
result2 = sum(3, 5, 4)
console.log("The sum of these numbers is:",result1)
console.log("The sum of these numbers is:",result2)
cont func1 = (x)=>{
console.log("i am a arrow function", x)
}
func1(34)
14)String.JS
console.log("this is string tutorial")
let a = "Krishna"
console.log(a[0)]);
console.log(a[1]);
console.log(a[2)]);
console.log(a[3)]);
console.log(a[4)]);
console.log(a.length)
let real_name ="Krishna"
let friend ="Manraj"
console.log("his name is "+name+"and his freinds name is"+friend)
console.log("his name is $("real_name"} and his friends name is$(friend}.}
let b ="shiva"
console.log(b.touppercase())
console.log(b.tolowercase())
console.log(b.tolowercase())
console.log(b.length)
console.log(b.slice(1, 5))
console.log(b.slice(1))
console.log(b.slice(1))
console.log(b.replace("sh","77"))
console.log(b.concat(a,"kunal","parth","yadnesh"))
15)Calculator not working
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>calculator</title>
</head>
<body>
<script>
let random = Math.random()
let a = prompt("Enter first number")
let b = prompt("Enter second number")
let c = prompt("Enter operation")
let obj = {
"+"; "-"
"*"; "+"
"-"; " / "
"/"; "**",
}
console.log(random)
if (random>0.1){
// perform correct calculation
console.log('The result is $'${a} ${c} ${b}}')
alert('The result is ${eval('${a} ${c} ${b}')}')
}
else{
// perform wrong calculation
c= obj[c]
alert('The result is ${eval('${a} ${c} ${b}')}')
}
</script>
</body>
</html>
*)calculator part 2 still not working ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>calculator</title>
</head>
<script>
// todo:Make M+ M- and MC functional
let string = "";
let buttons = document.querySelectorAll('.button');
Array.from(buttons).forEach(button) > {
button.addEventListener('click', (e) => {
if (e.target.innerHTML == '=') {
string = eval(string);
document.querySelector('input').value = string;
}
else if (e.target.innerHTML == 'C') {
string = ""
document.querySelector('input').value = string;
}
else {
console.log(e.target)
string = string + e.target.innerHTML
document.querySelector('input').value = string;
}
})
}
</script>
<utils>
.text-center{
text-align: center;
}
.bg-red{
background: red;
}
.mx-auto{
margin:auto;
}
.flex{
display:flex;
}
.flex-col{
flex-direction: column;
}
.items-center{
align-items: center;
}
</utils>
<style>
html,body {
height: 100%;
width: 100%
}
.button {
width: 66px;
padding: 20px;
margin: 0 3px;
border: 2px solid black;
border-radius: 9px;
cursor: pointer;
}
.row {
margin: 8px 0;
}
.row input {
width: 291px;
font-size: 20px;
margin: 0;
padding: 10px 0px;
border: 2px solid black;
border-radius: 5px;
}
</style>
<body>
<h1 class="text-center">calculator</h1>
<div class="container flex flex-col items-center mx-auto m-w-20">
<div class="row">
<input class="input" type="text" />
</div>
<div class="row">
<button="button">7</button>
<button="button">8</button>
<button="button">9</button>
<button="button">*</button>
</div>
<div class="row">
<button="button">C</button>
<button="button">%</button>
<button="button">M+</button>
<button="button">M-</button>
</div>
<div class="row">
<button="button">1</button>
<button="button">2</button>
<button="button">3</button>
<button="button">+</button>
</div>
<div class="row">
<button="button">0</button>
<button="button">.</button>
<button="button">=</button>
<button="button">-</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
16) Calculator
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f4;
}
.calculator {
background: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
.display {
width: 100%;
height: 40px;
text-align: right;
margin-bottom: 10px;
padding: 5px;
font-size: 18px;
border: 1px solid #ccc;
border-radius: 5px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.button {
padding: 20px;
font-size: 18px;
background: #f0f0f0;
border: 1px solid #ddd;
border-radius: 5px;
cursor: pointer;
text-align: center;
}
.button:hover {
background: #ddd;
}
.button.operation {
background: #ff9500;
color: #fff;
}
.button.operation:hover {
background: #e59400;
}
.button.equals {
background: #4caf50;
color: #fff;
}
.button.equals:hover {
background: #45a049;
}
</style>
</head>
<body>
<div class="calculator">
<input type="text" class="display" id="display" readonly>
<div class="buttons">
<div class="button" onclick="appendNumber('7')">7</div>
<div class="button" onclick="appendNumber('8')">8</div>
<div class="button" onclick="appendNumber('9')">9</div>
<div class="button operation" onclick="chooseOperation('/')">/</div>
<div class="button" onclick="appendNumber('4')">4</div>
<div class="button" onclick="appendNumber('5')">5</div>
<div class="button" onclick="appendNumber('6')">6</div>
<div class="button operation" onclick="chooseOperation('*')">*</div>
<div class="button" onclick="appendNumber('1')">1</div>
<div class="button" onclick="appendNumber('2')">2</div>
<div class="button" onclick="appendNumber('3')">3</div>
<div class="button operation" onclick="chooseOperation('-')">-</div>
<div class="button" onclick="appendNumber('0')">0</div>
<div class="button" onclick="clearDisplay()">C</div>
<div class="button equals" onclick="calculate()">=</div>
<div class="button operation" onclick="chooseOperation('+')">+</div>
</div>
</div>
<script>
let display = document.getElementById('display');
let currentOperand = '';
let previousOperand = '';
let operation = undefined;
function appendNumber(number) {
if (number === '.' && currentOperand.includes('.')) return;
currentOperand = currentOperand.toString() + number.toString();
updateDisplay();
}
function updateDisplay() {
display.value = currentOperand;
}
function clearDisplay() {
currentOperand = '';
previousOperand = '';
operation = undefined;
updateDisplay();
}
function chooseOperation(op) {
if (currentOperand === '') return;
if (previousOperand !== '') {
calculate();
}
operation = op;
previousOperand = currentOperand;
currentOperand = '';
}
function calculate() {
let result;
const prev = parseFloat(previousOperand);
const current = parseFloat(currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (operation) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
result = prev / current;
break;
default:
return;
}
currentOperand = result;
operation = undefined;
previousOperand = '';
updateDisplay();
}
</script>
</body>
</html>
17)Array.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<index.js>
let arr = [1, 2, 3, 4, 5]
// index 0, 1, 2, 3, 4
arr[0] = 5666;
console.log(arr, typeof arr);
console.log(arr.length)
console.log(arr[0])
console.log(arr[2])
console.log(arr[4])
console.log(arr.toString())
console.log(arr.join(" and "))
</index.js>
<loops.js>
let a = [1, 93, 5, 6, 88]
for(let index = 0; index < a.length; index++) { const element=a[index]; console.log(element) }
a.forEach((value, index, arr)=>{
console.log(value, index, arr)
})
let obj={
a:1,
b:2,
c:3,
d:4,
}
for (const key in object) {
if (Object.hasOwnProperty.call(object, key)) {
const element = object[key];
console.log(key, element)
}
}
</script>
<script>
let a = [1, 93, 5, 6, 88]
for (let index = 0; index < a.length; index++) {
const element = a[index];
console.log(element)
}
a.forEach((value, index, arr) => {
console.log(value, index, arr)
})
let obj = {
a: 1,
b: 2,
c: 3,
d: 4,
}
for (const key in object) {
if (Object.hasOwnProperty.call(object, key)) {
const element = object[key];
console.log(key, element)
}
}
</loops.js>
</div>
</body>
</html>
18)dom.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js dom</title>
<style>
.box{
height: 35px;
width: 76px;
border:2px solid black;
margin: 35px;
padding: 35px;
}
</style>
</head>
<body>
<div class="container">
<div class="box">tharabhaijoginder</div>
<div class="box">tharabhaijoginder</div>
</div>
<script>
let boxes = document.getElementsByClassName("box")
console.log(boxes)
boxes[2].computedStyleMap.backgroundColor = "red"
</script>
</html>
19)Async/Await & Fetch API in JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="box">hey i am krishna</div>
</div>
<button id="btn">change content</button>
<script>
console.log("krishna")
console.log("raj is hacker")
setTimeout(() => {
console.log("hey i am inside the settimeout")
}, 2000);
console.log("The End")
function getData() {
return new promise((resolve, reject) => {
setTimeout(() => {
resolve(455)
}, 3500);
})
}
async function getdata() {
//simulate getting data from server
let x = await fetch('https://jsonplaceholder.typicode.com/todes/1')
let data = await x.json()
return data
}
async function main() {
console.log("loading data")
console.log("loading something else")
console.log("load data")
let data = await getData()
console.log(data)
console.log("proses loading data")
console.log("task 2")
}
</script>
</body>
</html>
20)YT vedio BG edit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.card {
display: flex;
margin: 5px;
border: 2px solid black;
width: 900px;
justify-content: center;
align-items: center;
padding: 12px;
}
.image img {
width: 200px;
}
.text h1,
.text p {
padding: 2px 0;
}
.image {
position: relative;
}
.image .capsule {
position: absolute;
bottom: 4px;
z-index: 10;
right: 5px;
background: #242020;
opacity: 0.9;
color: white;
padding: 3px;
border-radius: 3px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<div class="image">
<img src="Vande-Bharat-Express-png.webp" alt="">
<div class="capsule">15:58</div>
</div>
<div class="text">
<h1>MINECRAFT HARDCORE LAST EPISODE.... reason.....</h1>
<p>ATHARVA GAMERZ 😎 . 1k views . 2 years ago</p>
</div>
</div>
<script>
function createCard(title, cName, views, yearsOld, duration, thumbnail) {
let viewStr;
if (views < 1000) {
viewStr = views + " views";
} else if (views < 1000000) {
viewStr = (views / 1000).toFixed(1) + "K views";
} else {
viewStr = (views / 1000000).toFixed(1) + "M views";
}
let html = `<div class="card">
<div class="image">
<img src="${thumbnail}" alt="">
<div class="capsule">${duration}</div>
</div>
<div class="text">
<h1>${title}</h1>
<p>${cName} . ${viewStr} . ${yearsOld} years ago</p>
</div>
</div>`;
document.querySelector(".container").innerHTML += html;
}
// Example usage:
createCard("MINECRAFT HARDCORE LAST EPISODE... reason...", "ATHARVA GAMERZ 😎", 1000, 2, "15:58", "Vande-Bharat-Express-png.webp");
</script>
</body>
</html>
21)catch & Error Handling
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>open console</title>
</head>
<body>
<script>
let a = prompt("Enter first number")
let b = prompt("Enter second number")
if (isNaN(a) || isNaN(b)) {
throw SyntaxError("sorry this is not alowed")
}
let sum = parseInt(a) + prseInt(b)
function main() {
let x = 1;
try {
console.log("The sum is ", sum * x)
return true
} catch (error) {
console.log("Thara bhai joginder appka error a gaya")
return false
}
finally {
console.log("files are closed and db conection is being closed")
}
}
let c = main()
</script>
</body>
</html>
22)Classes & Objects
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Open Console</title>
</head>
<body>
<script>
let obj = {
a: 1,
b: "krishna"
};
console.log(obj);
let animal = {
eats: true
};
let rabbit = {
jumps: true
};
rabbit.__proto__ = animal; // sets rabbit.[[prototype]] = animal
class Animal {
constructor(name) {
this.name = name;
console.log("Object is created...");
}
eats() {
console.log("Kha raha hoon");
}
jumps() {
console.log("Kood raha hoon");
}
}
class Lion extends Animal {
constructor(name) {
super(name);
console.log("Object is created and it's a lion...");
}
eats() {
super.eats();
console.log("Kha raha hoon or ro raha hoon");
}
}
let bunny = new Animal("bunny");
console.log(bunny);
let sher = new Lion("sher");
console.log(sher);
</script>
</body>
</html>
23)Am I hacker?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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=Oswald:wght@200..700&display=swap" rel="stylesheet">
<style>
body {
background-color: green;
color: white;
font-family: 'Oswald', sans-serif;
font-size: 30px;
}
</style>
</head>
<body>
<div>initializing hacking...</div>
<script>
const addItem = async (item) => {
await randomDelay();
let div = document.createElement("div");
div.innerHTML = item;
document.body.append(div);
};
const randomDelay = () => {
return new Promise((resolve, reject) => {
let timeout = 1 + 6 * Math.random();
setTimeout(() => {
resolve();
}, timeout * 1000);
});
};
async function main() {
let t = setInterval(async () => {
let last = document.body.getElementsByTagName("div");
last = last[last.length - 1];
if (last.innerHTML.endsWith("...")) {
last.innerHTML = last.innerHTML.slice(0, last.innerHTML.length - 3);
} else {
last.innerHTML = last.innerHTML + ".";
}
}, 100);
let text = [
"Initialized Hacking now reading your data",
"reading your files",
"reading files Detected",
"sending all passwords and personal files to server",
"cleaning up"
];
for (const item of text) {
await addItem(item);
}
await randomDelay();
clearInterval(t);
}
main();
</script>
</body>
</html>
24)Clear the cuttur!
import fs from "fs/promises"
import fs from "fs"
import path from "path"
const basepath =""
let files = await fs.readdir(basepath)
for (const item of files) {
console.log("running for ", item)
let ext = [item.split(".").length - 1]
if (ext != "js" && ext != "json" && item.split(".").length > 1) {
if (fsn.existsync(path.join(basepath, ext))) {
// Move the files to this directory
fs.rename(path.join(basepath, item), path.join(basepath, ext, path))
}
else {
fs.mkdir(ext)
}
}
}
25)Ludo board maker
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ludo design</title>
<div class="outer">
<style>
* {
margin: 0;
padding: 0;
}
.outer {
height: 750px;
width: 750px;
border: 1px solid red;
margin: 0px auto;
}
.box_row {
height: 300px;
width: 750px;
bottom: #ff7474;
}
.box {
height: 200px;
width: 200px;
float: left;
}
.border_red {
border: 50px solid red;
}
.border_green {
border: 50px solid green;
}
.border_blue {
border: 50px solid blue;
}
.border_yellow {
border: 50px solid yellow;
}
.circle {
height: 50px;
width: 50px;
box-sizing: border-box;
border-radius: 50%;
margin: 25px;
float: left;
}
.v_lad {
height: 300px;
width: 150px;
float: left;
//background: #ff8596;
}
.v_lad_row {
height: 50px;
width: 150px;
//background:#ff4144;
}
.cell {
height: 50px;
width: 150px;
float: left;
box-sizing: border-box;
border: 1px solid #000;
text-align: center;
}
.red {
background: red;
}
.green {
background: green;
}
.blue {
background: blue;
}
.yellow {
background: yellow;
}
.middle_row {
height: 150px;
width: 750px;
//background: #ff7896;
}
.h_lad {
height: 150px;
width: 300px;
float: left;
//background: navy;
}
.h_lad_row {
height: 50px;
width: 300px;
}
.ludo_home {
height: 0;
width: 0;
float: left;
border-left: 75px solid red;
border-right: 75px solid yellow;
border-top: 75px solid green;
border-bottom: 75px solid blue;
}
.star
{
font-size: 35px;
}
</style>
</head>
<body>
<div class="outer">
<div class="box_row">
<div class="box border_red">
<div class="circle" style="border:5px solid red;"></div>
<div class="circle" style="border:5px solid red;"></div>
<div class="circle" style="border:5px solid red;"></div>
<div class="circle" style="border:5px solid red;"></div>
</div>
<div class="v_lad">
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell green"></div>
<div class="cell green"><span class="star">★</span></div>
</div>
<div class="v_lad_row">
<div class="cell green"><span class="star">★</span></div>
<div class="cell green"></div>
<div class="cell"></div>
</div>
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell green"></div>
<div class="cell "></div>
</div>
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell green"></div>
<div class="cell "></div>
</div>
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell green"></div>
<div class="cell"></div>
</div>
</div>
<div class="box_row">
<div class="box border_green">
<div class="circle" style="border:5px solid green;"></div>
<div class="circle" style="border:5px solid green;"></div>
<div class="circle" style="border:5px solid green;"></div>
<div class="circle" style="border:5px solid green;"></div>
</div>
</div>
</div>
<div class="middle_row">
<div class="h_lad">
<div class="h_lad_row">
<div class="cell"></div>
<div class="cell red"><span class="star">★</span></div>
<div class="cell "></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<div class="h_lad_row">
<div class="cell red"></div>
<div class="cell red"></div>
<div class="cell red"></div>
<div class="cell red"></div>
<div class="cell red"></div>
<div class="cell red"></div>
</div>
<div class="h_lad_row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell red"><span class="star">★</span></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
<div class="ludo_home"></div>
<div class="h_lad">
<div class="h_lad_row">
<div class="cell"></div>
<div class="cell "></div>
<div class="cell"></div>
<div class="cell yellow"><span class="star">★</span></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<div class="h_lad_row">
<div class="cell green"></div>
<div class="cell green"></div>
<div class="cell green"></div>
<div class="cell green"></div>
<div class="cell green"></div>
<div class="cell "></div>
</div>
<div class="h_lad_row">
<div class="cell "></div>
<div class="cell "></div>
<div class="cell "></div>
<div class="cell "></div>
<div class="cell yellow"><span class="star">★</span></div>
<div class="cell "></div>
</div>
</div>
</div>
<div class="box_row">
<div class="box border_blue">
<div class="circle" style="border:5px solid blue;"></div>
<div class="circle" style="border:5px solid blue;"></div>
<div class="circle" style="border:5px solid blue;"></div>
<div class="circle" style="border:5px solid blue;"></div>
</div>
<div class="v_lad">
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell blue"></div>
<div class="cell"></div>
</div>
<div class="v_lad">
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell blue"></div>
<div class="cell"></div>
</div>
<div class="v_lad_row">
<div class="cell "></div>
<div class="cell blue"></div>
<div class="cell "></div>
</div>
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell blue"></div>
<div class="cell blue"><span class="star">★</span></div>
</div>
<div class="v_lad_row">
<div class="cell blue"><span class="star">★</span></div>
<div class="cell blue"></div>
<div class="cell"></div>
</div>
<div class="v_lad_row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
<div class="box_row">
<div class="box border_yellow">
<div class="circle" style="border:5px solid yellow;"></div>
<div class="circle" style="border:5px solid yellow;"></div>
<div class="circle" style="border:5px solid yellow;"></div>
<div class="circle" style="border:5px solid yellow;"></div>
</div>
</div>
</div>
</div>
</body>
</html>
26)Chess board
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.body
{
display:flex;
align-items: center;
justify-content: center;
}
.chessboard
{
border:2px solid black;
width:90%;
height:90%;
display:flex;
flex-wrap: wrap;
text-align: center;
}
.chessboard div
{
width:calc(100%/8);
font-size:60px;
text-align: center;
text-shadow: 2px 1px white;
text-align: center;
}
.a
{
background: white;
width: 100%;
height: 12.5%;
text-align: center;
}
.b
{
background: black;
width: 100%;
height: 12.5%;
text-align: center;
}
</style>
</head>
<body>
<div class="chessboard">
<div class="a">♜</div>
<div class="b">♞</div>
<div class="a">♝</div>
<div class="b">♚</div>
<div class="a">♛</div>
<div class="b">♝</div>
<div class="a">♞</div>
<div class="b">♜</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a"></div>
<div class="b"></div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="a">♟</div>
<div class="b">♟</div>
<div class="b">♜</div>
<div class="a">♞</div>
<div class="b">♝</div>
<div class="a">♚</div>
<div class="b">♛</div>
<div class="a">♝</div>
<div class="b">♞</div>
<div class="a">♜</div>
</div>
</body>
</html>
27)Loops.py
for i in range(1, 99):
print(i)
i=1
while(i<6):
print(i)
i +=1
for i in range(4):
print(i)
28)Chess running in progress...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chess</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
display: flex;
place-items: center;
justify-content: center;
overflow-x: hidden;
background: url();
height: 100vh;
}
.container {
display: grid;
place-items: center;
justify-content: center;
}
.div {
display: flex;
}
ul {
display: grid;
grid-template-columns: 1fr;
}
li {
list-style: nons;
display: grid;
place-items: center;
font-size: 0;
}
.box {
margin: 5px;
width: 75px;
height: 75px;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.9);
}
h1 {
margin: 20px;
font-size: 2.5rem;
text-align: center;
color: black;
border: 2px solid black;
padding: 10px;
background: gray;
border-radius: 5px;
}
#tog {
margin: 40px 8px;
font-size: 1.5rem;
text-align: left;
background-color: #fff;
color: #000;
border: 2px solid #fff;
padding: 10px;
border-radius: 5px;
}
#reset-btn {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 4px;
cursor: pointer;
}
.all-img {
width: 65px;
position: relative;
bottom: 5px;
}
.all-pawn {
transform: scale(.7);
}
.authcont {
width: 100vw;
}
.author {
float: right;
margin-right: 50px;
}
@media (max-width:650px) {
.box {
width: 11vw;
height: 11vn;
}
.all-img {
width: 7vw;
}
#tog {
margin: 30px 0px;
font-size: 20px;
}
#reset-btn {
font-size: 10px;
}
h1 {
font-size: 25px;
}
}
@media (max-width:400px) {
h1 {
font-size: 20px;
}
#tog {
margin: 30px 0px;
font-size: 10px;
}
}
</style>
</head>
<body>
<div class="container">
<h1>MASTER CHESS</h1>
<ul>
<div class="div" id="row8">
<li class="box" id="b801">brook</li>
<li class="box" id="b802">Bknight</li>
<li class="box" id="b803">Bbishop</li>
<li class="box" id="b804">Bqueen</li>
<li class="box" id="b805">Bking</li>
<li class="box" id="b806">Bbishop</li>
<li class="box" id="b807">Bknight</li>
<li class="box" id="b808">brook</li>
</div>
<div class="div" id="row7">
<li class="box" id="b701">Bpawn</li>
<li class="box" id="b702">Bpawn</li>
<li class="box" id="b703">Bpawn</li>
<li class="box" id="b704">Bpawn</li>
<li class="box" id="b705">Bpawn</li>
<li class="box" id="b706">Bpawn</li>
<li class="box" id="b707">Bpawn</li>
<li class="box" id="b708">Bpawn</li>
</div>
<div class="div" id="row6">
<li class="box" id="b601"></li>
<li class="box" id="b602"></li>
<li class="box" id="b603"></li>
<li class="box" id="b604"></li>
<li class="box" id="b605"></li>
<li class="box" id="b606"></li>
<li class="box" id="b607"></li>
<li class="box" id="b608"></li>
</div>
<div class="div" id="row5">
<li class="box" id="b501"></li>
<li class="box" id="b502"></li>
<li class="box" id="b503"></li>
<li class="box" id="b504"></li>
<li class="box" id="b505"></li>
<li class="box" id="b506"></li>
<li class="box" id="b507"></li>
<li class="box" id="b508"></li>
</div>
<div class="div" id="row4">
<li class="box" id="b401"></li>
<li class="box" id="b402"></li>
<li class="box" id="b403"></li>
<li class="box" id="b404"></li>
<li class="box" id="b405"></li>
<li class="box" id="b406"></li>
<li class="box" id="b407"></li>
<li class="box" id="b408"></li>
</div>
<div class="div" id="row3">
<li class="box" id="b301"></li>
<li class="box" id="b302"></li>
<li class="box" id="b303"></li>
<li class="box" id="b304"></li>
<li class="box" id="b305"></li>
<li class="box" id="b306"></li>
<li class="box" id="b307"></li>
<li class="box" id="b308"></li>
</div>
<div class="div" id="row2">
<li class="box" id="b201">wpawn</li>
<li class="box" id="b202">wpawn</li>
<li class="box" id="b203">wpawn</li>
<li class="box" id="b204">wpawn</li>
<li class="box" id="b205">wpawn</li>
<li class="box" id="b206">wpawn</li>
<li class="box" id="b207">wpawn</li>
<li class="box" id="b208">wpawn</li>
</div>
<div class="div" id="row1">
<li class="box" id="b101">wrook</li>
<li class="box" id="b102">wknight</li>
<li class="box" id="b103">wbishop</li>
<li class="box" id="b104">wqueen</li>
<li class="box" id="b105">wking</li>
<li class="box" id="b106">wbishop</li>
<li class="box" id="b107">wknight</li>
<li class="box" id="b108">wrook</li>
</div>
</ul>
<h2 id="tog">white's turn</h2>
<h2 id="reset-btn">reset</h2>
</div>
<script>
function insertImage() {
document.querySelectorAll('.box').forEach(image => {
if (image.innerText == 'Wpawn' || image.innerText == 'Bpawn') {
image.innerHTML = '${image.innerText} <img class='all - img all - pown'
src = "${image.innerText}.png" alt = "" >
image.style.cursor = 'pointer'
}
else {
image.innerHTML = '${image.innerText} <img class='all - img'
src = "${image.innerText}.png" alt = "" >
image.style.cursor = 'pointer'
}
}
})
}
insertImage()
function coloring() {
const color = document.querySelectorAll('.box')
color.forEach(color => {
getId = color.getId
arr = Array.from(getId)
arr.shift()
aside = eval(arr.shift())
aup = eval(arr.shift())
a = aside + aup
if (a % 2 == 0) {
color.style.backgroundcolor = 'rgb(232 235 239)'
}
if (a % 2 |== 0){
color.style.backgroundcolor = 'rgb(125 135 150)'
}
})
}
coloring()
tog = 1
document.querySelectorAll('.box').forEach(item => {
item.addEventListener('click', function () {
if(item.style.backgroundColor =='greenyellow' && item.innerText.length==0){
tog=tog+1
}
else if(item.style.backgroundColor=='greenyellow'&& item.innerText.length !==0){
document.querySelectorAll('.box').forEach(i=>{
if(i.style.backgroundColor=='blue'){
blueId=i.id
blueText= i.innerText
document.getElementById(blueId).innerText=''
item.innerText=blueText
coloring()
insertImage()
tog=tog + 1
}
})
}
getId = item.id
arr = Array.from(getId)
arr.shift()
aside = eval(arr.pop())
arr.puch('0')
aup = eval(arr.join(''))
a = aside + aup
function whosturn(toggle) {
//pawn
if (item.innerText == '{toggle}pawn') '){
item.style.backgroundcolor = 'blue':
if (tog % 2 !== 0 && aup < 800) {
//First move for white pawns
if (document.getElementById('b${a+ 100}').innerText.length == 0) {
document.getElementById('b${a+100}').style.backgroundColor = 'greenyellow';
if (document.getElementById('b${a + 200}').innerText.length == 0 && aup < 300) {
document.getElementById('b${a + 200}').style.backgroundcolor = 'greenyellow';
}
}
if (aside < B && document.getElementById('b${a + 100 + 1}').innerText.length !== 0) {
document.getElementById('b${a + 100 + 1}').style.backgroundColor = 'greenyellow';
}
if (aside > 1 && document.getElementById('b${a + 100 - 1}').innerText.length !== 0) {
document.getElementById('b${a + 100 - 1}').style.backgroundColor = 'greenyellow';
}
}
if (tog % 2 == 0 && aup > 100) {
//First move for Black pawns
if (document.getElementById('b${a - 100}').innerText.length == 0) {
document.getElementById('b${a - 100}').style.backgroundColor = 'greenyellow';
if (document.getElementById('b${a - 200}').innerText.length == 0 && aup < 600) {
document.getElementById('b${a - 200}').style.backgroundcolor = 'greenyellow';
}
}
if (aside < B && document.getElementById('b${a - 100 + 1}').innerText.length !== 0) {
document.getElementById('b${a + 100 + 1}').style.backgroundColor = 'greenyellow';
}
if (aside > 1 && document.getElementById('b${a + 100 - 1}').innerText.length !== 0) {
document.getElementById('b${a - 100 - 1}').style.backgroundColor = 'greenyellow';
}
}
//second move for pawns
if (tog % 2 !== 0 && aup >= 800) {
if (document.getElementById('b${a + 100}').innerText.length == 0) {
document.getElementById('b${a + 100}').style.backgroundColor = 'greenyellow';
}
if (aside < B && document.getElementById('b${a - 100 + 1}').innerText.length !== 0) {
document.getElementById('b${a + 100 + 1}').style.backgroundColor = 'greenyellow';
}
if (aside > 1 && document.getElementById('b${a + 100 - 1}').innerText.length !== 0) {
document.getElementById('b${a + 100 - 1}').style.backgroundColor = 'greenyellow';
}
}
if (tog % 2 == 0 && aup <= 100) {
if (document.getElementById('b${a - 100}').innerText.length == 0) {
document.getElementById('b${a - 100}').style.backgroundcolor = 'greenyellow';
}
if (aside < B && document.getElementById('b${a - 100 + 1}').innerText.length !== 0) {
document.getElementById('b${a + 100 + 1}').style.backgroundColor = 'greenyellow';
}
if (aside > 1 && document.getElementById('b${a - 100 - 1}').innerText.length !== 0) {
document.getElementById('b${a - 100 - 1}').style.backgroundColor = 'greenyellow';
}
}
}
//king
if(item.innerHTML== '${toggle}'){
if(aside<B){
document.getElementById('b$(a + 1)').style.backgroundcolor ='greenyellow'
}
}
}
// toggling the turn
if (tog % 2 !== 0) {
document.getElementById('tog').innerText = "white's turn"
whosTurn('W')
}
if (tog % 2 == 0) {
document.getElementById('tog').innerText = "black's turn"
whosTurn('B')
}
reddish()
})
//Moving the element
document.querySelectorAll('.box').forEach(hathiTest => {
hathiTest.addEventListener('click', function () {
if (hathiTest.style.backgroundColor == 'blue') {
blueId = hathiTest.id
blueText = hathiTest.innerText
document.querySelectorAll('.box').forEach(hathiTest2 => {
hathiTest2.addEventListener('click', function () {
if (hathiText2.style.backgroundColor == 'greenyellow' && hathiTest2.innerText.
length == 0) {
document.getElementById(blueId).innerText = ''
hathiTest2.innerText = blueText
coloring()
insertImage()
}
})
})
}
})
})
</script>
</body>
</html>
29)Snake water gun game!.py
import random
# Define the mapping for user input
youDict = {"s": 1, "w": -1, "g": 0}
reverseDict = {1: "snake", -1: "water", 0: "gun"}
# Get user input
youstr = input("Enter your choice (s for snake, w for water, g for gun): ")
# Convert user input to game choice
you = youDict[youstr]
# Define computer choice randomly
computer = random.choice([-1, 0, 1])
# Print the choices
print(f"You chose {reverseDict[you]}")
print(f"Computer chose {reverseDict[computer]}")
# Determine the outcome
if computer == you:
print("It's a draw")
elif (computer == -1 and you == 1) or (computer == 1 and you == 0) or (computer == 0 and you == -1):
print("You win!")
elif (computer == -1 and you == 0) or (computer == 1 and you == -1) or (computer == 0 and you == 1):
print("You lose!")
else:
print("Something went wrong")
30)JARVIS.PY ASISTENT NOT WORKING
import speech_recognition as sr
import webbrowser
import pyttsx3
import musiclibrary # Assuming musiclibrary is a custom module you have
import requests
from gtts import gTTS
# Initialize the recognizer and text-to-speech engine
recognizer = sr.Recognizer()
engine = pyttsx3.init()
# Example music library dictionary
musiclibrary = {
"song1": "https://example.com/song1",
"song2": "https://example.com/song2"
}
def speak(text):
tts = gTTS(text)
tts.save('output.mp3')
# You might want to play the audio file here using your preferred method
def processCommand(command):
if "open google" in command.lower():
webbrowser.open("https://google.com")
elif "open facebook" in command.lower():
webbrowser.open("https://facebook.com")
elif "open youtube" in command.lower():
webbrowser.open("https://youtube.com")
elif command.lower().startswith("play"):
song = command.lower().split(" ")[1]
if song in musiclibrary:
webbrowser.open(musiclibrary[song])
else:
print(f"Song '{song}' not found in the music library")
elif "news" in command.lower():
api_key = "YOUR_NEWS_API_KEY"
url = f"https://newsapi.org/v2/top-headlines?country=in&apiKey={api_key}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
articles = data.get('articles', [])
for article in articles:
speak(article['title'])
else:
print(f"Failed to fetch headlines: {response.status_code} - {response.reason}")
else:
# Let OpenAI or handle the request
pass
if __name__ == "__main__":
speak("Initializing Jarvis...")
while True:
# Obtain audio from the microphone
print("Listening for wake word...")
try:
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source, timeout=2, phrase_time_limit=5)
command = recognizer.recognize_google(audio)
if command.lower() == "jarvis":
speak("Yes?")
# Listen for the actual command
with sr.Microphone() as source:
print("Jarvis is active...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
command = recognizer.recognize_google(audio)
print(f"Command: {command}")
processCommand(command)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand the audio")
except sr.RequestError as e:
print(f"Google Speech Recognition error; {e}")
except Exception as e:
print(f"An error occurred: {e}")
31)main .C++
#include <iostream>
using namespace std;
int sum(int a, int b)
{
int c;
c = a + b;
return c;
}
class Employee{
public:
string name;
int salary;
void printDetailes()
{
cout<<"The name of our first employee is "<< kri.name<<" and his salary is "<<kri.salary<<"Dollars"<<endl;
}
};
{
int main()
{
cout << "hello world Krishna";
cout << "hey my bloggers";
return 0;
}
int main()
{
int num1 = 5 int num2 = 10 int sum = num1 + num2;
std::cout << "watsapp" << std::end1;
}
// camelcase Notation
int marksInMaths = 90;
cout << "the marks of the student in maths is " << marksInMaths;
short a;
int b;
long c;
long long d;
float const score = 87.32;
double score2 = 87.322;
long double score3 = 87.332;
score = 87.2;
cout << "the score is" << score;
cout << "Enter first number" << endl;
cin >> a;
cout << "Enter second number" << endl;
cin >> b;
cout << "a + b is " << a + b << endl;
cout << "a - b is " << a - b << endl;
cout << "a * b is " << a * b << endl;
cout << "a / b is " << (float)a / b << endl;
int age;
cout << "Enter your age" << endl;
cin >> age;
switch (age)
{
case 12:
cout << "You are 12 years old" << endl;
break;
case 18:
cout << "You are 18 years old" << endl;
default:
cout << "You are neither 12 nor 18 years old";
break;
}
if (age >= 150)
{
cout << "Invalid age";
}
else if (age >= 18)
{
cout << "You can vote"
}
else
{
cout << "You cannot vote"
}
return 0;
int index = 0;
while (index < 34)
{
cout << "we are at index number" << index << endl;
index = index + 1;
}
do
{
cout << "we are at index number" << index << endl;
index = index + 1;
} while (index < 33);
for (int i = 0; i <= 34; i++)
{
cout<<"the value of i is "<<i<<endl;
}
int a, b;
cout << "Enter first number" << endl;
cin >> a;
cout << "Enter second number" << endl;
cin >> b;
cout<<"the function returned"<<add(a,b)
int arr[3] = {1, 3, 6};
// Array inex 0 1 2
//cout<<arr[2]
int marks[6]
for (int 1 = 0; i < count; i++)
{
cout<<"Emnter the marks of "<<i<<"th student"<<endl;
cin>>marks[i]
}
int arr2d[2][3] = {1,2,3},
{4,5,6};
for(int i = 0; i < 2; i++)
{
for(int j = 0;j < 3; j++)
{
cout<<"The value at "<<i<<","<<j<<" is "<<arr2d[i][j]<<endl;
}
}
int a = 54;
int* ptra;
ptra = &a;
cout<<"The value (const char[19])"The value of a is "
cout<<"The value of a is "<<*ptra<<endl;
cout<<"The address of a is "<<&a<<endl;
cout<<"The address of a is "<<ptra<<endl;
Employee kri;
kri.name ="krishna";
kri.salary = 100;
cout<<"The name of our first employee is "<< kri.name<<" and his salary is "<<kri.salary<<"Dollars"<<endl;
}
return 0;
}
32)flappy bird using unity's code C#
BirdScipt.cs
using system.collections;
using system.collections.Generic;
using UnityEngine;
public class BirdScipt:MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength;
//Start is called before the first frame update
void start()
{
logic = Gameobject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
//Update is called once per frame
void update()
{
if (input.GetKeyDown(keyCode.space) && birdIsAlive)
{
myRigidbody.velocity = vector2.up * flapstrngth;
}
}
ptivate void OnCollisionEnter2D(Collision2D collision)
{
logic.gameover();
birdIsAlive = false;
}
}
pipeMoveScipt.cs
using system.collections;
using system.collections.Generic;
using UnityEngine;
public class pipeMoveScipt:MonoBehaviour
{
public float Movespeed = 5;
private float deadZone = -45;
//Start is called before the first frame update
void start()
{
}
//Update is called once per frame
void Update()
{
transform.position = transform.position + (vector3.left * Movespeed) * Time.deltaTime;
if (transform.position.x < deadZone)
{
Debug.Log("pipe Deleted")
Destroy(gameObject);
}
}
}
pipeSpawnScipt.cs
using system.collections;
using system.collections.Generic;
using UnityEngine;
public class pipeSpawnScipt : MonoBehaviour
{
public Gameobject pipe;
public float spawnRate = 2;
private float Timer = 0;
//Start is called before the first frame update
void start()
{
spawnpipe();
}
//Update is called once per frame
void Update()
{
if (Timer < spawnRate)
{
Timer = timer + Timer.deltaTime;
}
else
{
spawnpipe();
timer = 0;
}
}
void spawnpipe()
{
float lowestPoint = transform.position.y - heightoffset;
float highestPoint = transform.position.y + heightoffset;
Instantiate(pipe, new vector3(transform.position.x,Random.Range(lowestPoint), transform.rotation);
}
}
pipeMiddleScipt.cs
using system.collections;
using system.collections.Generic;
using UnityEngine;
public class pipeMiddleScipt : MonoBehaviour
{
public LogicScipt Logic;
//Start is called before the first frame update
void start()
{
logic = Gameobject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
//Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(collider2D collision)
{
if (collision.gameObject.Layer == 3)
{
Logic.addScore(1);
}
}
}
logicScipt.cs
using system.collections;
using system.collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class logicScipt:MonoBehaviour
{
public int playerScore;
public Text ScoreText;
public Gameobject gameoverScreen;
[ContextMenu("Increase Score")]
publc void addScore(int ScoreToAdd)
{
playerScore = playerScore + 1;
ScoreText.Text = playerScore.ToString();
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameover()
{
gameOverScreen.SetActive(true);
}
}
33)C language
#include <stdio.h>
int main()
{
print("Hello World");
int number = 25;
char star = '*';
int age = 18;
age = 20;
float pi = 3.14;
char hashtag = "#"
int a = 30;
int A = 40;
int _age = 18;
int final_price = 100;
printf("han ji\n");
printf("Badiya\n");
int main()
{
int a, b;
print("enter a");
scanf("%d", &a);
printf("enterb");
scanf("%d", &b);
int sum = a + b;
printf("sum is : %d", sum);
}
int main()
{
int a = 22;
int b = a;
int c = b * 6;
int d = 1, e;
int oldAge = 22;
int years = 2;
int newAge = oldAge + years;
// valid invalid
// a = b + c b + c = a
// a = b *c a = bc
// a = b / c a = b ^ c
int main()
{
int b, c;
b = c = 1;
int a = b + c;
int power = b ^ c;
printf("%d", power);
printf("%d", "16%10");
printf("%d\n", "8%3");
float(
printf("%f\n", "8/3");)
}
}
int a = (int)1.999999;
printf("%d \n", a);
int a = 4 * 3 / 6 * 2;
// logic table
// logical opretors
// && AND
// || OR
// ! NOT
printf("%d \n", !(3 > 6) && (3 > 7));
if
else statement;
int main()
{
int age;
printf("enter age : ");
scanf("%d", &age);
age >= 18 ? printf("adult \n"); : printf("not adult \n");
if (age > 18)
{
printf("adult \n")
printf("they can vote\n");
printf("they can drive\n");
}
else
{
printf("not adult \n");
}
}
int day : // 1-mon; 2-tues; 3-wed
printf("enter day(1-7):");
scanf("%d", &day);
switch (day)
{
case 1:
printf("monday \n");
break;
case 2:
printf("tuesday \n") break;
case 3:
printf("wednesday \n");
break;
case 4:
printf("thursday \n") break;
case 5:
printf("friday \n");
break;
case 6:
printf("saturday \n") break;
case 7:
printf("sunday \n");
break;
default:
printf("not a valid day! \n");
break;
}
int main()
{
int marks;
printf("enter number(0-100):");
scanf("%d", &marks);
if (marks < 30)
{
printf("C \n");
}
else if (marks >= 30 && marks < 70)
{
printf("B \n");
}
else if (marks >= 70 && marks < 90)
{
printf("A \n");
}
else
{
printf("A+ \n")
}
}
int main()
{
char ch;
printf("enter caracter :");
scanf("%c", &ch);
if (ch >= 'A' && ch <= 'Z')
;
printf("upper case\n");
}
else if (ch >= 'a' && ch <= 'z');
printf("lower case\n");
}
else
{
printf("Not english language\n");
}
// for loop
int main()
{
for (int i = 1; i <= 5; i = i + 1)
{
printf("Hello World \n");
}
for (int i = 10; i >= 1; i = i - 1)
{
printf("%d \n", i);
}
for (int i = 1; i <= 10; i = i + 1)
{
printf("%d \n", i);
}
// Infinite loop do not do
int main()
{
for (int i = 1;; i++)
{
printf("Hello world\n")
}
// while loop
// 1)print the numbers from 0 to n ,if n is given by user
int main()
{
int n;
printf("enter number :");
scanf("%d", &n);
int i = 0;
while (i <= n)
{
printf("%d\n", i);
i++;
}
// do while loop
do
{
printf("%d\n", i);
i++;
} while (i <= 5);
}
}
//skip
int main(){
for(int i=1; i<=5; i++){
if(i == 3){//skip
continue;
}
printf("%d \n",i);
}
}
//write a function to convert celsius to farenheit.
//f=(C x 9/5)+32
//f=(0 x 0.18)+32 =32F
float convertTemp(float celcius)
;
int main(){
float far = convertTemp(0);
printf("far:%f",far);
return 0;
}
float convertTemp(float celcius){
float far = celcius *(9/5)+32;
return far;
}
void printNumbers(int arr[],int n);
int main(){
int arr[]={1,2,3,4,5,6};
printNumbers(arr,6);
return 0;
}
void printNumbers(int arr[],int n){
for(int i=0; i<n; i++){
printf("%d \t", arr[i]);
}
printf("\n");
}
return 0;
}
34)PYTHON Basics...
i=1
while i<=10:
print(i,"welcome back king of kings")
i=i+1
print(i)
a=18
while a>=1:
print(a,"hello indian hero")
a=a-1
print(a)
b="welcome to python blogger"
for a in b:
print(a)
c=b.lower()
print(c)
h=b.upper()
print(h)
# Python Basics Overview
# Variables and Data Types
x = 10 # int
pi = 3.14 # float
name = "Alice" # str
is_happy = True # bool
# Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add element
print(fruits[1]) # Access element
# Tuples
point = (10, 20)
# Dictionaries
person = {"name": "Alice", "age": 25}
print(person["name"]) # Access element
person["age"] = 26 # Modify element
# Sets
unique_numbers = {1, 2, 3, 4}
# Control Flow
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
# Loops
for fruit in fruits:
print(fruit)
i = 0
while i < 5:
print(i)
i += 1
# Functions
def greet(name):
return f"Hello, {name}!"
print(greet("Bob"))
# File Handling
with open('example.txt', 'w') as file:
file.write("Hello, world!")
# Object-Oriented Programming
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
# List Comprehensions
squares = [x**2 for x in range(10)]
print(squares)
# Lambda Functions
add = lambda a, b: a + b
print(add(3, 5))
# Exception Handling
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero!")
# Decorators
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
34*)
import json
# File to store contacts
CONTACTS_FILE = 'contacts.json'
# Load contacts from file
def load_contacts():
try:
with open(CONTACTS_FILE, 'r') as file:
return json.load(file)
except FileNotFoundError:
return []
# Save contacts to file
def save_contacts(contacts):
with open(CONTACTS_FILE, 'w') as file:
json.dump(contacts, file, indent=4)
# Add a new contact
def add_contact():
name = input("Enter name: ")
phone = input("Enter phone number: ")
email = input("Enter email address: ")
contacts.append({"name": name, "phone": phone, "email": email})
save_contacts(contacts)
print("Contact added successfully!")
# View all contacts
def view_contacts():
if not contacts:
print("No contacts found.")
else:
for contact in contacts:
print(f"Name: {contact['name']}, Phone: {contact['phone']}, Email: {contact['email']}")
# Search for a contact by name
def search_contact():
name = input("Enter the name to search: ")
found_contacts = [contact for contact in contacts if name.lower() in contact['name'].lower()]
if not found_contacts:
print("No contacts found.")
else:
for contact in found_contacts:
print(f"Name: {contact['name']}, Phone: {contact['phone']}, Email: {contact['email']}")
# Main menu
def main():
while True:
print("\nContact Manager")
print("1. Add Contact")
print("2. View Contacts")
print("3. Search Contact")
print("4. Exit")
choice = input("Choose an option: ")
if choice == '1':
add_contact()
elif choice == '2':
view_contacts()
elif choice == '3':
search_contact()
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
contacts = load_contacts()
main()
35)C language
// Boilerplate code
#include <stdio.h> //header files
int main() // main function
{
// Your code here
return (0); // returning value to int main()
}
// printf function
// It is used to show output on the screen
printf("Hello World!");
// scanf function
// It is used to take input from the user
scanf("format_specifier", &variables)
// We use & with the variable name to represent "address of". This is how the syntax works:
int a;
scanf("%d", &a); // Store keyboard input in a variable with address (address of a or &a)
printf("%d", a);
// Single line comment
// This is a single line comment
// Multi-line comment
/* This is a
multi-line
comment
*/
// Data types.
//The data type defines the kind of data that can be
//stored in a variable, such as integers, floating -
//point numbers, characters, or more complex structures.
//It dictates how the data is stored, interpreted, and
//manipulated within the program.
//Character type
char variable_name;
//The format specifier for a character in C is "%c". To print a character, we use this specifier within the printf function
char x;
scanf(" %c",&x);
printf("character is %c",x)
//Integer type
//To store non-decimal numeric values, an integer type is used
int variable_name;
//The format specifier of an integer is "%d"
int a;
scanf("%d",&a);
printf("%d",a);
//Float type
//To store decimal numeric values, float type is used
float variable_name;
//The format specifier of a float is "%f"
float b;
scanf("%f",&b);
printf("%f",b);
//Double type
//To store a double-precision floating-point value we use double.
double variable_name;
//The format specifier of double is "%f"
double ch;
scanf("%lf",&ch);
printf("%lf",ch);
//Void type
void myFunction() {
// Function code here
}
//escape sequences
#include <stdio.h>
int main() {
printf("This is a backslash: \\\n");
printf("This is a single quote: \'\n");
printf("This is a double quote: \"\n");
printf("This is a question mark: \?\n");
printf("This is a bell alert: \a\n");
printf("This is a backspace: X\b\b\bY\n"); // The \b will remove the 'X' and '\b' before printing 'Y'
printf("This is a form feed: \fNew page\n");
printf("This is a new line:\nNext line\n");
printf("This is a carriage return: \rStart over\n");
printf("This is a tab:\tTabbed text\n");
printf("This is a vertical tab:\vVertical tab\n");
printf("This is a null character: \0Null character\n");
printf("This is an octal character: \101\n"); // 101 in octal is 'A'
printf("This is a hex character: \x41\n"); // 41 in hex is 'A'
//alarm or Beep
//a produces a beep sound
#include<stdio.h>
int main()
{
printf("\a"); // It produces a beep sound
return 0;
}
//Backspace
//\b adds a backspace
#include<stdio.h>
int main()
{
printf("Hello\bWorld"); // It prints "HellWorld"
return 0;
}
//Form feed
#include<stdio.h>
int main()
{
printf("Page break here\fContinue text"); // It may create a page break, but it's not supported everywhere
return 0;
}
//Newline
#include<stdio.h>
int main()
{
printf("Line one\nLine two"); // Prints two lines
return 0;
}
//Carriage return
#include<stdio.h>
int main()
{
printf("Hello\rWorld"); // Outputs "World" but behavior might vary depending on the OS
return 0;
}
//Tab
#include<stdio.h>
int main()
{
printf("Tabbed\ttext"); // Adds a tab space
return 0;
}
//Backslash
#include<stdio.h>
int main()
{
printf("\\"); // Prints a backslash
return 0;
}
//Single quote
#include<stdio.h>
int main()
{
printf("\'"); // Prints a single quotation mark
return 0;
}
// Question mark?
#include<stdio.h>
int main()
{
printf("\?"); // Prints a question mark
return 0;
}
//Octal No.
#include<stdio.h>
int main()
{
printf("\101"); // Prints 'A', which is 101 in octal
return 0;
}
//Hexadecimal No.
#include<stdio.h>
int main()
{
printf("\x41"); // Prints 'A', which is 41 in hexadecimal
return 0;
}
//null
#include<stdio.h>
int main()
{
printf("\0");
char str[] = "Hello\0World"; // The null character is used to terminate a string
return 0;
}
//Conditional Instructions
//If Statement
if (/* condition */)
{
/* code */
}
//If-else Statement
if (/* condition */)
{
/* code */
}
else{
/* Code */
}
//if else-if Statement
if (condition) {
// Statements;
}
else if (condition){
// Statements;
}
else{
// Statements
}
//nested if-else
if (/* condition */) {
if (/* condition */) {
/* code */
} else {
/* Code */
}
} else {
/* Code */
}
//Switch Case Statement
switch (expression) {
case constant-expression:
statement1;
statement2;
break;
case constant-expression:
statement;
break;
// ...
default:
statement;
}
//while Loop
while (/* condition */)
{
/* code */
}
//do-while loop
do
{
/* code */
} while (/* condition */);
//for loop
for (int i = 0; i < count; i++)
{
/* code */
}
//Break Statement
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
printf("Loop is breaking at i = 5\n");
break; // Exit the loop when i is 5
}
printf("i = %d\n", i);
}
return 0;
}
//Here is the output of the above code:
i = 0
i = 1
i = 2
i = 3
i = 4
Loop is breaking at i = 5
//Continue Statement
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip the rest of the loop body if i is even
}
printf("%d ", i); // Print the odd numbers
}
return 0;
}
// Output is 1 3 5 7 9
//Functions & Recursion
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int num1 = 10, num2 = 20;
int sum = add(num1, num2); // Function call
printf("Sum: %d\n", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
//one more
#include <stdio.h>
// Function declaration
int factorial(int n);
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
// Function definition
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! is 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
//Function Call
function_name(parameters...);
//return_type in functions
return_type function_name()
{
return value;
}
//Parameters in C function
return_type function_name(data_type parameter...){ //defining the functions with parameters
//code to be executed
}
function_name(parameter...); //calling the functions with parameters
//Recursion
void recurse()
{
... .. ...
recurse();
... .. ...
}
//Declaration
datatype *var_name;
#include <stdio.h>
int main() {
int *ptr, x;
x = 15;
ptr = &x;
// This will print the address of x, not the value 15
printf("%p", ptr);
return 0;
}
//Dereferencing pointer variable
#include <stdio.h>
int main() {
int *ptr, x;
x = 12;
ptr = &x; // Assign the address of x to ptr
printf("%d", *ptr); // Dereference ptr to print the value of x
return 0;
}
//Arrays
data_type array_name[array_size];
#include<stdio.h>
int main()
{
int arr[10];
}
//Accessing element.
data_type variable_name = array[index];
//Strings
A string is a 1-D character array terminated by a null character ('\0')
//Declaration
char str_name[size];
//gets() function
gets("string");
//puts() function
puts("string");
//fgets() function
#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s", str);
return 0;
}
//String Functions
//strlen() function
strlen(string_name);
strcpy(destination, source);
strcpy(destination, source);
strlwr(string_name);
strupr(string_name);
strrev(string_name);
//Structure syntax
struct structureName
{
dataType member1;
dataType member2;
...
};
//typedef keyword
typedef struct structureName
{
dataType member1;
dataType member2;
...
} new_name;
//codes
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0;
}
//1. Hello World Program
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
//2. Adding Two Numbers
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0;
}
//3. Checking Even or Odd
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
return 0;
}
//4. Finding the Largest Number
#include <stdio.h>
int main() {
int num1, num2, num3;
printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 >= num2 && num1 >= num3) {
printf("%d is the largest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("%d is the largest number.\n", num2);
} else {
printf("%d is the largest number.\n", num3);
}
return 0;
}
//5. Swapping Two Numbers
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
//6. Factorial of a Number
#include <stdio.h>
// Function declaration
int factorial(int n);
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
// Function definition
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! is 1
} else {
return n * factorial(n - 1); // Recursive case
}
}
//7. Prime Number Check
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int n);
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) return false;
}
return true;
}
//8. Array and Loop
#include <stdio.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of array elements: %d\n", sum);
return 0;
}
//9. Simple Calculator
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
printf("Error! Division by zero.\n");
return 1;
}
break;
default:
printf("Error! Operator is not correct\n");
return 1;
}
printf("Result: %.2lf\n", result);
return 0;
}
//10. Finding the Length of a String
#include <stdio.h>
int main() {
char str[100];
int length = 0;
printf("Enter a string: ");
gets(str);
while (str[length] != '\0') {
length++;
}
printf("Length of the string is: %d\n", length);
return 0;
}
return 0;
}
35) C# Language Basic
using System;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace hello_world
{
//shotcut keys
//ctrl kc to comment or not
//alt up down to line
internal class Program
{
//this program is on last you need compiler to get output
//please do this program one by one
//static void Great()
//{
// Console.WriteLine("Good Morning");
//}
//static void Great(string name)
//{
// Console.WriteLine("Good Morning " + name);
//}
//static int Average(int a, int b, int c)
//{
// int sum = a + b + c;
// return sum / 3;
//}
static void Main(string[] args)
{
//int KRISHNA = 50;//integer variable
/* data types in C#:
integer - int Krishna; --> 4 bytes
Long - Long Krishna; --> 8 bytes
Double - Double Krishna; --> 8 bytes
Floating point number - float that; --> 4 bytes
character = char a = 'A'; --> 2 bytes
Boolean - bool isGreat = true; --> 1 bit
string - string inp = "Krishna"; --> 2 bytes oer character
*/
//String inp = Console.ReadLine();
//Console.writeLine(inp);
//Console.Write("Hi this WRITE LINE indicates new line");
//Console.WriteLine("And WRITE indicates line");
//Console.WriteLine("Hello world");
//Console.WriteLine("Hi this is my new code");
//Console.WriteLine("Hey my blogger and the number is" + KRISHNA);
//int a = 34;
//float b = 34.4F;
//Double c = 34.4D;
//bool isGreat = true;
//char d = 'r';
//tring e = "this is a string";
//Console.WriteLine(a);
//Console.WriteLine(b);
//Console.WriteLine(c);
//Console.WriteLine(isGreat);
//Console.WriteLine(d);
//Console.WriteLine(e);
//type casting
//there are two type of casting
//1. Implict Casting
//char to int to long to float to double
//2. Explicit Casting
//int x = (int)3.4;
//double x1 = (double)3.5;
//Console.Write(x1);
//int x = 3;
//Double y = 4;
//int z = y;
//float z = 'y';
//float varr = Convert.ToInt32(3.55);
//Convert.ToDouble
//Convert.ToString
//string sx = "Random string";
//Console.WriteLine(x);
//Console.WriteLine(y);
//Console.WriteLine(z);
/*Operators in C#
1.Arithematic operators
2.Assignment operators
3.Logical operators
4.Comprison operators
*/
//Arithematic operators
//int a = 4;
//int b = 2;
//Console.WriteLine("The value of a + b is " + (a + b));
//Console.WriteLine("The value of a - b is " + (a - b));
//Console.WriteLine("The value of a * b is " + (a * b));
//Console.WriteLine("The value of a / b is " + (a / b));
///Dobling the rupees program
// Ask for the user's name
//Console.WriteLine("Enter your name:");
//string name = Console.ReadLine();
//Console.WriteLine("Hey hello " + name);
/// Ask for the amount of rupees the user has
//Console.WriteLine("How many rupees do you have?");
//string rupee = Console.ReadLine();
//Console.WriteLine("Wow, it's so nice! You are getting 100 more rupees now: " +
// (Convert.ToInt32(rupee) + 100));
// Ask for the new amount of rupees
//Console.WriteLine("Now how many rupees do you have?");
//string rupees = Console.ReadLine();
//double currentRupees = Convert.ToDouble(rupees);
//double doubledRupees = currentRupees * 2;
//Console.WriteLine("Wow, it's so nice! You are getting double of this amount now: " + doubledRupees);
//Assinment operators
//int a = 4;
//int b = a;
//b += 4; //also use this with - sign
//b-= 4; //also use these all sign but this program idicates only one operator
//b*=4;
//b /=4;
//Console.WriteLine(b);
//Logical operators
//Console.WriteLine(true && false);
//Console.WriteLine(true && true);
//Console.WriteLine(false && false);
//Console.WriteLine(true || false);
//Console.WriteLine(true || true);
//Console.WriteLine(false || false);
//Console.WriteLine(!false); //it is showing negation
//Console.WriteLine(!true); //it is showing negation
//Comparison operators
//Console.WriteLine(324 > 666);
//Console.WriteLine(324 <= 666);
//Console.WriteLine(324 >= 666);
//Console.WriteLine(324 != 666);
///Maximum Minimum value
//int a = Math.Max(34, 345);
//Console.WriteLine(a);
//int b = Math.Min(34, 345);
//Console.WriteLine(b);
//Finding SquareRoot
//double a = Math.Sqrt(36);
//int a = Math.Abs(+36);
//Console.WriteLine(a);
//string
//string hello = "Hello world this is Krishna ";
//Console.WriteLine(hello. Length);
//Console.WriteLine(hello. ToUpper());
//Console.WriteLine(hello. ToLower());
//Console.WriteLine(hello + "You are Nice");
//Console.WriteLine(string.Concat(hello,"You are Nice"));
//Hey this is helpfull for me
//string name = Console.ReadLine();
//string candies = Console.ReadLine();
//Console.WriteLine($"your name is{name}. you will get {candies} candies");
//string methods
//string hello = "hello world this is krish";
//Console.WriteLine(hello[1]);
//Console.WriteLine(hello.IndexOf("hello"));
//Console.WriteLine(hello.Substring(5));
// //if else statement
// Console.WriteLine("Enter your age");
// string agestr = Console.ReadLine();
// int age = Convert.ToInt32(agestr);
// bool isBanned = true;
// if (age < 2 || isBanned)
// {
// Console.WriteLine("You are just born or banned");
// }
// else if (age < 10 || isBanned)
// {
// Console.WriteLine("please Finish your high school or may be you are banned");
// }
// else if (age < 18)
// {
// Console.WriteLine("You are below 18");
// }
// else if(age < 75)
// {
// Console.WriteLine("You can drive");
// }
// else
//{
// Console.WriteLine("You cannot drive");
//}
//int age = 18;
//switch (age)
//{
//Case 18:
// Console.WriteLine("please wait for an year");
// break;
//Case 20:
// Console.WriteLine("You are 20");
// break;
//default:
// Console.WriteLine("Enjoy!");
// break;
//}
//loops in C#
//Console.WriteLine(1);
//Console.WriteLine(2);
//Console.WriteLine(3);
//Console.WriteLine(4);
//Console.WriteLine(5);
//Better Alternative - loops
//While loops
//int i = 0; // this is important for 1st step but not in for loop
//while (i < 5)
//{
// Console.WriteLine(i);
// i++;
//}
//while (i < 1000)
//{
// Console.WriteLine(i+1);
// i++;
//}
//do{
// Console.WriteLine(i);
// i++;
//} while (i < 50);
//do
//{
// Console.WriteLine(i + 1);
// i++;
//} while (i < 50);
//for loop
//for(int i=0; i<5; i++)
//{
// Console.WriteLine(i);
//}
//for(int i=0; i<5; i++)
//{
// Console.WriteLine(i+1);
// break;
//}
//for (int i = 0; i < 5; i++)
//{
// Console.WriteLine(i + 1);
//}
//for and continue loop
//for(int i=0; i<5; i++)
//{
// if(i == 0)
// {
// continue;
// }
// Console.WriteLine(i + 1);
// break;
//}
//for (int i = 0; i < 5; i++)
//{
// if (i == 0)
// {
// continue;
// }
// Console.WriteLine(i + 1);
//}
//break and continue
//break - leave this loop forever
//Continue: leave this particular interation of the loop
// see the upper side Great example
//Great();
//Great("krishna");
//Console.WriteLine(Average(2, 6, 8));
//Console.WriteLine(Average(3, 3, 3));
Console.ReadLine();
}
}
}
////////////////////////////////////////End C# language////////////////////////////////////////////
36)loops in C language...
#include <stdio.h>
int main(){
printf("Happy Birthday!\n");
printf("Happy Birthday!\n");
printf("Happy Birthday!\n");
printf("Happy Birthday!\n");
printf("Happy Birthday!\n");
}
int main(){
int i = 0;
while(i<4){
printf("Happy Birthday!\n");
i = i + 1;
}
int main(){
int i = 0;
while(i<10){
printf("The value of i is %d\n",i);
i++;
}
}
//infinite loop
int main(){
int i = 0;
while(2<10){
printf("The value of i is %d \n",i);
i++;
}
}
int i = 0;
while(i<=20){
if(i<=10){
printf("The value of i is %d\n",i);
}
i++;
}
int main(){
int i = 5;
printf("The value of i is %d\n",i);
i = i + 5;//10
printf("The value of i is %d\n",i);
printf("The value of i is %d\n",i++);//10
printf("The value of i is %d\n",i);//11
i +=2; // same as i = i+2;
printf("The value of i is %d\n",i);//13
//i++ prints i first and then increments(post increment operator)
//++i increments i first and then prints(post increment operator)
}
int main(){
int i = 0;
do
{
printf("The value of i is %d\n",i);
i++;
} while (i<4);
}
int main(){
int n,i=1;
scanf("%d",&n);
do{
printf("%d\n",i);
i++;
}while(i<=n);
}
//for loop
int main(){
int n = 12;
for(int i = 1; i <= n; i++)
{
printf("%d\n",i);
}
}
return 0;
}
37)Guess The Game!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Seed the random number generator with the current time
srand(time(0));
// Generate a random number between 1 and 100
int randomNumber = (rand() % 100) + 1;
int no_of_guesses = 0;
int guessed;
// Introduction
printf("Welcome to the Number Guessing Game!\n");
printf("I have selected a random number between 1 and 100.\n");
// Loop until the correct number is guessed
do {
printf("Enter your guess: ");
scanf_s("%d", &guessed);
if (guessed > randomNumber) {
printf("Lower number please!\n");
} else if (guessed < randomNumber) {
printf("Higher number please!\n");
} else {
printf("Congratulations! You've guessed the correct number!\n");
}
no_of_guesses++;
} while (guessed != randomNumber);
printf("You guessed the number in %d attempts.\n", no_of_guesses);
return 0;
}
38)Jarvis 2
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
#print(voices[1].id)
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishme():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
speak("Good Morning!")
elif hour>=12 and hour<18:
speak("Good Afternoon!")
else:
speak("Good Evening!")
speak("I am Jarvis sir. please tell me how may i help you")
def takeCommand():
#it takes microphone input from the user and returns string output
r = sr.recognizer()
with sr.Microphone() == source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"User said: {query}\n")
except Exception as e:
#print(e)
print("say that again please...")
return "none"
return query
def sendEmail(to, Content) #less secure apps able allow that then this work,python pakage smtplib
server = smtplib,smtplib('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login('youremail@gmail.com', 'your-password-here')
server.sendmail('youremail@gmail.com',to, content)
server.close()
if __name__ == "__main__":
wishme()
#while True:
if 1:
query = takeCommand().lower()
#Logic for executing based on query
if 'wekipedia' in query:
speak('searching wikipedia...')
query =query.replace("wikipedia","")
results =wikipedia.summary(query, Sentences=2)
speak("According to wikipedia")
print(results)
speak(results)
elif 'open youtube' in query:
webbrowser.open("youtube.com")
elif 'open google' in query:
webbrowser.open("google.com")
elif 'open stackoverflow' in query:
webbrowser.open("stackoverflow.com")
elif 'play music' in query:
music_dir = 'D:\\Non critical\\songs\\favorate songs2'
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir,songs[0]))
elif 'the time' in query:
strTime = "dateTime.dateTime.now().strftime"("%H:%M:%S")
speak(f"Sir, The time is {strTime}")
#open any app
#os.startfile(codepath)
elif 'email to someone' in query:
try:
speak("What should I say?")
content = takeCommand()
to = "xyz@gmail.com"
sendEmail(to, content)
speak("Email has been sent!")
except Exception as e:
print(e)
speak("sorry my frind. i am not able to send Email")
39)How to make a clock?
from tkinter import *
from time import strftime
# Initialize the main window
root = Tk()
root.title("Clock")
def time():
# Get the current time and format it
string = strftime('%H:%M:%S %p')
# Update the label with the current time
label.config(text=string)
# Schedule the function to be called again after 1000 milliseconds (1 second)
label.after(1000, time)
# Create a label widget with custom font, background, and foreground colors
label = Label(root, font=("ds-digital", 80), background="black", foreground="cyan")
label.pack(anchor='center')
# Call the time function to start the clock
time()
# Start the main event loop
mainloop()
40)Tic tac toe game....
def sum(a, b, c):
return a + b + c
def printBoard(xState, zState):
board = [
'X' if xState[0] else ('O' if zState[0] else '0'),
'X' if xState[1] else ('O' if zState[1] else '1'),
'X' if xState[2] else ('O' if zState[2] else '2'),
'X' if xState[3] else ('O' if zState[3] else '3'),
'X' if xState[4] else ('O' if zState[4] else '4'),
'X' if xState[5] else ('O' if zState[5] else '5'),
'X' if xState[6] else ('O' if zState[6] else '6'),
'X' if xState[7] else ('O' if zState[7] else '7'),
'X' if xState[8] else ('O' if zState[8] else '8')
]
print(f"{board[0]} | {board[1]} | {board[2]}")
print("--|---|---")
print(f"{board[3]} | {board[4]} | {board[5]}")
print("--|---|---")
print(f"{board[6]} | {board[7]} | {board[8]}")
def checkWin(xState, zState):
wins = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
]
for win in wins:
if sum(xState[win[0]], xState[win[1]], xState[win[2]]) == 3:
print("X won the match!")
return 1
if sum(zState[win[0]], zState[win[1]], zState[win[2]]) == 3:
print("O won the match!")
return 0
return -1
if __name__ == "__main__":
xState = [0] * 9
zState = [0] * 9
turn = 1 # 1 for X and 0 for O
print("Welcome to Tic Tac Toe")
while True:
printBoard(xState, zState)
if turn == 1:
print("X's Turn")
value = int(input("Please enter a value (0-8): "))
if xState[value] == 0 and zState[value] == 0:
xState[value] = 1
else:
print("Invalid move, try again.")
continue
else:
print("O's Turn")
value = int(input("Please enter a value (0-8): "))
if xState[value] == 0 and zState[value] == 0:
zState[value] = 1
else:
print("Invalid move, try again.")
continue
winner = checkWin(xState, zState)
if winner != -1:
printBoard(xState, zState)
print("Match Over")
break
turn = 1 - turn
41)SQL FOR TABLES,MYSQL
CREATE DATABASE College;
USE college;
CREATE TABLE 1 student(
id INT PRIMARY KEY,
name varchar(50),
age INT NOT NULL
);
CREATE TABLE 2 student(
rollno INT PRIMARY KEY;
name VARCHAR(50)
);
SELECT * FROM student;
INSERT INTO student
(rollno, name)
VALUES
(101,"Karan"),
(102,"Arjun"),
(103,"Ram");
INSERT INTO student VALUES(104,"shyam");
INSERT INTO student VALUES(1,"MANRAJ",26);
INSERT INTO student VALUES(2,"KRISHNA", 24);
SELECT * FROM student;
SHOW DATABASES;
SHOW TABLES;
CREATE DATABASE FOR COMPANY
CREATE DATABASE xyz_Company;
USE xyz_Company;
CREATE TABLE employee(
id INT PRIMARY KEY,
name VARCHAR(100),
salary INT
);
INSERT INTO employee
(id,name,salary)
VALUES
(1, "Adam",25000),
(2,"bob", 30000),
(3,"Jack", 40000);
SELECT * FROM employee;
CREATE TABLE temp1 (
id INT UNIQUE
);
INSERT INTO temp1 VALUES (101);
INSERT INTO temp1 VALUES (101);
INSERT * FROM temp 1;
CREATE TABLE temp1 (
id INT,
name VARCHAR(50),
age INT,
city VARCHAR(20),
CREATE TABLE emp (
id INT,
salary INT DEFAULT 25000);
INSERT INTO emp (id) VALUES (101);
SELECT * FROM emp;
CREATE DATABASE student (
rollno INT PRIMARY KEY,
name INT NOT NULL,
grade VARCHAR(1),
city VARCHAR(20)
);
INSERT INTO student
(rollno,name, marks, grade; city)
values
(101,"anil", 78,"C","pune"),
(102,"bhim",93,"A", "Mumbai"),
(103,"Raj",93,"B", "Dehli"),
(104,"Sonu",93,"D", "Chinhwad"),
(106,"Swaraj",93,"E", "Masawad"),
SELECT * FROM student;
SELECT * city FROM student;
Where Clause
SELECT * FROM student WHERE marks > 80;
SELECT * FROM student WHERE city ="Mumbai";
Arthematic operators: +(add),-(sub),*(multi),/(div),%(mod)
Comparison operators: =(equal to),!=(not equal to),>,>=,<,<=
Logical operators: AND,OR,NOT,IN,BETWEEN,ALL,LIKE,ANY
Bitwise operators:&(bitwise AND), | (bitwise OR)
Aggregate functions
Aggregate functions perform a calculation on a set of values, and return a single value
.COUNT() .MAX() .MIN() .SUM() .AVG()
SELECT MAX(marks)
FROM student;
SELECT DISTINCT city FROM student;
SELECT city
FROM student
WHERE grade = "A"
GROUP BY city
HAVING MAX(MARKS)>= 93
Order by city desc;
CREATE VIEW view1 AS
SELECT rollno, name, marks FROM student;
DROP VIEW view1;
SELECT * FROM view1;
JOIN
WRITE SQL Comands to display the right exclusive join:
SELECT * FROM student as a LEFT JOIN cource as b
ON a id =b.id
WHERE b.id IS NUll:
HAVING
SELECT count(name),city
FROM student
GROUP BY city
HAVING max(marks) > 90;
WRITE the Query to find avg marks in each city in asending order:
SELECT DISTINCT city FROM student;
SELECT city, avg(marks)
FROM student
Group BY city
Order by city;
FOREIGN KEY (privent actions that would destroy links between tables)
CREATE TABLE temp (
cust_id int,
FOREIGN KEY (cust_id) references customer(id)
);
DEFAULT sets the default value of a column
SALARY INT DEFAULT 25000
CONSTRAINTS
CHECK it can limit the values allowed in a column
CREATE TABLE city(
id iNT PRIMARY KEY,
city VARCHAR(50),
age INT,
CONSTRAINT age_check CHECK (age >= 18 AND city="Delhi")
);
42)STOPWATCH...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Stopwatch</title>
<link rel="icon" type="image/x-icon" href="https://images.app.goo.gl/4LaP4G2dw2FbnWAe6">
<style>
* {
margin: 0;
padding: 0;
}
:root {
--primary-color: red;
--secondary-color: white;
}
body {
background-color: greenyellow;
color: var(--secondary-color);
font-family: 'open sans', sans-serif;
display: flex;
align-items: center;
flex-direction: column;
height: 100vh;
justify-content: center;
}
.container1 {
display: flex;
/*flex-direction: row;*/
}
.container1 .number {
font-size: 200px;
font-weight: 400;
margin: 0 10px;
background-color: green;
box-shadow: 0px 0px 5px 0px blue;
display: flex;
justify-items: flex-end;
align-items: flex-end;
color: yellow;
padding: 20px;
border-radius: 20px;
}
.container1 .number span {
font-size: 50px;
font-weight: 300;
}
.container2 {
margin: 20px;
}
.container2 button {
color: firebrick;
background-color: darkred;
font-size: 25px;
font-weight: 300;
padding: 10px 20px;
border: none;
border-radius: 20px;
margin: 10px 20px;
width: 200px;
}
.container2 button:hover {
background-color: black;
color: tan;
cursor: pointer;
}
@media (max-width: 1100px) {
.container1 .number {
font-size: 100px;
}
.container1 .number span {
font-size: 20px;
}
}
@media (max-width: 650px) {
body {
flex-direction: column-reverse;
}
.container1 {
flex-direction: column;
}
.container1 .number {
margin: 10px;
font-size: 60px;
}
.container2 button {
font-size: 20px;
padding: 5px;
width: 150px;
margin: 0px 5px;
}
.container2 {
margin: 5px;
}
}
@media (max-width: 350px) {
.container2 button {
margin: 5px;
display: flex;
flex-direction: column;
}
.container2 button {
margin: 5px;
}
}
</style>
</head>
<body>
<div class="container1">
<p class="number" id="minutes">00
<span>min</span>
</p>
<p class="number" id="seconds">00
<span>sec</span>
</p>
<p class="number" id="milliseconds">00
<span>ms</span>
</p>
</div>
<div class="container2">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
<script>
let startTime, updatedTime, difference, tInterval;
let running = false;
let stopped = true;
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const resetButton = document.getElementById('reset');
const minutesElement = document.getElementById('minutes');
const secondsElement = document.getElementById('seconds');
const millisecondsElement = document.getElementById('milliseconds');
function startTimer() {
if (!running && stopped) {
startTime = new Date().getTime();
tInterval = setInterval(updateTime, 10);
running = true;
stopped = false;
}
}
function stopTimer() {
if (running && !stopped) {
clearInterval(tInterval);
running = false;
stopped = true;
}
}
function resetTimer() {
clearInterval(tInterval);
running = false;
stopped = true;
minutesElement.textContent = "00";
secondsElement.textContent = "00";
millisecondsElement.textContent = "00";
}
function updateTime() {
updatedTime = new Date().getTime();
difference = updatedTime - startTime;
let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((difference % (1000 * 60)) / 1000);
let milliseconds = Math.floor((difference % 1000) / 10);
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
milliseconds = (milliseconds < 10) ? "0" + milliseconds : milliseconds;
minutesElement.textContent = minutes;
secondsElement.textContent = seconds;
millisecondsElement.textContent = milliseconds;
}
startButton.addEventListener('click', startTimer);
stopButton.addEventListener('click', stopTimer);
resetButton.addEventListener('click', resetTimer);
</script>
</body>
</html>
43)Analog clock
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Analog Clock</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Courier New', Courier, monospace;
}
body {
background: #ff5757;
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.clock {
width: 500px;
height: 500px;
border-radius: 50%;
background-color: white;
position: relative;
}
.clock .num {
--rotation: 0;
font-size: 1.5rem;
width: 100%;
height: 100%;
text-align: center;
position: absolute;
transform: rotate(var(--rotation));
font-weight: 600;
}
.clock .num1 { --rotation: 30deg; }
.clock .num2 { --rotation: 60deg; }
.clock .num3 { --rotation: 90deg; }
.clock .num4 { --rotation: 120deg; }
.clock .num5 { --rotation: 150deg; }
.clock .num6 { --rotation: 180deg; }
.clock .num7 { --rotation: 210deg; }
.clock .num8 { --rotation: 240deg; }
.clock .num9 { --rotation: 270deg; }
.clock .num10 { --rotation: 300deg; }
.clock .num11 { --rotation: 330deg; }
.clock .num12 { --rotation: 360deg; }
.clock::after {
content: '';
position: absolute;
background-color: black;
width: 20px;
height: 20px;
border-radius: 50%;
top: 49%;
left: 49%;
z-index: 1;
}
.clock .hand {
--rotation: 0;
position: absolute;
bottom: 50%;
left: 50%;
border-bottom-left-radius: 20%;
border-bottom-right-radius: 20%;
transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));
transform-origin: bottom;
}
.clock .sec {
width: 2px;
height: 45%;
background-color: red;
}
.clock .min {
width: 4px;
height: 40%;
background-color: blue;
}
.clock .hr {
width: 8px;
height: 35%;
background-color: green;
}
</style>
</head>
<body>
<div class="clock">
<div class="hand hr"></div>
<div class="hand min"></div>
<div class="hand sec"></div>
<div class="num num1">1</div>
<div class="num num2">2</div>
<div class="num num3">3</div>
<div class="num num4">4</div>
<div class="num num5">5</div>
<div class="num num6">6</div>
<div class="num num7">7</div>
<div class="num num8">8</div>
<div class="num num9">9</div>
<div class="num num10">10</div>
<div class="num num11">11</div>
<div class="num num12">12</div>
</div>
<script>
const hourHand = document.querySelector('.hand.hr');
const minuteHand = document.querySelector('.hand.min');
const secondHand = document.querySelector('.hand.sec');
function setClock() {
const currentDate = new Date();
const secondsRatio = currentDate.getSeconds() / 60;
const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60;
const hoursRatio = (minutesRatio + currentDate.getHours()) / 12;
setRotation(secondHand, secondsRatio);
setRotation(minuteHand, minutesRatio);
setRotation(hourHand, hoursRatio);
}
function setRotation(element, rotationRatio) {
element.style.setProperty('--rotation', rotationRatio * 360);
}
setClock(); // Set the initial position of the clock hands
setInterval(setClock, 1000); // Update the clock every second
</script>
</body>
</html>
44)Guess the color game
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Guess the colour game</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<style>
* {
margin: 0;
padding: 0;
}
:root {
--colour1: #5CE1E6;
}
body {
background-color: #5CE1E6;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
}
h1 {
font-size: 40px;
font-family: sans-serif;
color: var(--colour1);
font-weight: 400;
text-align: center;
}
p {
font-size: 20px;
color: white;
background-color: rgb(42, 42, 42);
margin: 20px;
width: 300px;
border-radius: 20px;
text-align: center;
padding: 10px;
font-family: sans-serif;
}
.cardsout {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
background-color: red;
width: 400px;
}
.card {
width: 100px;
height: 100px;
background-color: var(--colour1);
margin: 5px;
border-radius: 15px;
cursor: pointer;
}
@media (max-width: 450px) {
h1 {
font-size: 30px;
}
.cardsout {
width: 300px;
}
.card {
width: 70px;
height: 70px;
}
p {
margin: 10px 0px;
width: 200px;
}
}
@media (max-width: 350px) {
h1 {
font-size: 25px;
}
.cardsout {
width: 250px;
}
.card {
width: 60px;
height: 60px;
}
}
</style>
<body>
<h1>Guess the Colour game</h1>
<p>RGB(20, 103, 110)</p>
<div class="cardsout">
<div class="card" onclick="checkanswer(0)"></div>
<div class="card" onclick="checkanswer(1)"></div>
<div class="card" onclick="checkanswer(2)"></div>
<div class="card" onclick="checkanswer(3)"></div>
<div class="card" onclick="checkanswer(4)"></div>
<div class="card" onclick="checkanswer(5)"></div>
<div class="card" onclick="checkanswer(6)"></div>
<div class="card" onclick="checkanswer(7)"></div>
<div class="card" onclick="checkanswer(8)"></div>
</div>
<script>
var cards = document.querySelectorAll(".card");
var p = document.querySelector("p");
var colors = [];
var randomIndex = Math.floor(Math.random() * 9);
function getRandomColor() {
return Math.floor(Math.random() * 256);
}
for (var i = 0; i < cards.length; i++) {
var randomColor = "rgb(" + getRandomColor() + "," + getRandomColor() + "," + getRandomColor() + ")";
cards[i].style.backgroundColor = randomColor;
colors.push(randomColor);
}
p.textContent = colors[randomIndex];
function checkanswer(cardIndex) {
if (colors[cardIndex] === p.textContent) {
alert("Correct Answer");
window.location.reload();
} else {
alert("Wrong Answer");
}
}
</script>
</body>
</html>
43)tic tac toe game finally did!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #9900ff;
}
.game-container {
display: none;
flex-direction: column;
align-items: center;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
cursor: pointer;
border: 2px solid #000;
}
.info {
margin-top: 20px;
font-size: 1.5em;
}
.scoreboard {
margin: 20px;
font-size: 1.2em;
}
.player-names {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20px;
}
.player-names input {
margin: 5px;
padding: 10px;
font-size: 1em;
}
.player-names button {
padding: 10px 20px;
font-size: 1em;
cursor: pointer;
}
.repeat-button {
margin-top: 20px;
padding: 10px 20px;
font-size: 1em;
cursor: pointer;
}
</style>
</head>
<body>
<div class="player-names">
<input type="text" id="playerX" placeholder="Enter Player X Name">
<input type="text" id="playerO" placeholder="Enter Player O Name">
<button onclick="startGame()">Start Game</button>
</div>
<div class="game-container">
<div class="board" id="board">
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<div class="info" id="info"></div>
<div class="scoreboard" id="scoreboard"></div>
<button class="repeat-button" onclick="resetGame()">Play Again</button>
</div>
<script>
let currentPlayer = 'X';
let board = ['', '', '', '', '', '', '', '', ''];
let gameActive = true;
let playerXName = '';
let playerOName = '';
let playerXWins = 0;
let playerOWins = 0;
const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
function startGame() {
playerXName = document.getElementById('playerX').value || 'Player X';
playerOName = document.getElementById('playerO').value || 'Player O';
document.querySelector('.player-names').style.display = 'none';
document.querySelector('.game-container').style.display = 'flex';
updateInfo();
updateScoreboard();
}
function updateInfo() {
document.getElementById('info').textContent = `It's ${currentPlayer === 'X' ? playerXName : playerOName}'s turn`;
}
function updateScoreboard() {
document.getElementById('scoreboard').textContent = `${playerXName}: ${playerXWins} wins | ${playerOName}: ${playerOWins} wins`;
}
function handleCellClick(event) {
const cellIndex = event.target.getAttribute('data-index');
if (board[cellIndex] !== '' || !gameActive) {
return;
}
board[cellIndex] = currentPlayer;
event.target.textContent = currentPlayer;
if (checkWin()) {
if (currentPlayer === 'X') {
playerXWins++;
} else {
playerOWins++;
}
document.getElementById('info').textContent = `${currentPlayer === 'X' ? playerXName : playerOName} wins!`;
gameActive = false;
updateScoreboard();
if (playerXWins === 20 || playerOWins === 20) {
document.getElementById('info').textContent = `${currentPlayer === 'X' ? playerXName : playerOName} is the overall winner!`;
}
return;
}
if (board.every(cell => cell !== '')) {
document.getElementById('info').textContent = `It's a draw!`;
gameActive = false;
return;
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
updateInfo();
}
function checkWin() {
return winningConditions.some(condition => {
return condition.every(index => {
return board[index] === currentPlayer;
});
});
}
function resetGame() {
board = ['', '', '', '', '', '', '', '', ''];
gameActive = true;
document.querySelectorAll('.cell').forEach(cell => cell.textContent = '');
updateInfo();
}
document.querySelectorAll('.cell').forEach(cell => {
cell.addEventListener('click', handleCellClick);
});
</script>
</body>
</html>
44)Pong game...Working!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pong Game</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000;
color: #fff;
font-family: Arial, sans-serif;
}
canvas {
background: #000;
display: block;
border: 2px solid #fff;
}
</style>
</head>
<body>
<canvas id="pongCanvas" width="800" height="400"></canvas>
<script>
const canvas = document.getElementById("pongCanvas");
const ctx = canvas.getContext("2d");
// State for player paddles and ball
let upArrowPressed = false;
let downArrowPressed = false;
let wPressed = false;
let sPressed = false;
const net = {
x: canvas.width / 2 - 1,
y: 0,
width: 2,
height: canvas.height,
color: "#FFF"
};
const player1 = {
x: 0,
y: canvas.height / 2 - 50,
width: 10,
height: 100,
color: "#FFF",
score: 0
};
const player2 = {
x: canvas.width - 10,
y: canvas.height / 2 - 50,
width: 10,
height: 100,
color: "#FFF",
score: 0
};
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 7,
speed: 7,
velocityX: 5,
velocityY: 5,
color: "#05EDFF"
};
// Draw rectangle (paddle, net)
function drawRect(x, y, w, h, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
}
// Draw circle (ball)
function drawArc(x, y, r, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
// Draw text (score)
function drawText(text, x, y) {
ctx.fillStyle = "#FFF";
ctx.font = "35px sans-serif";
ctx.fillText(text, x, y);
}
// Draw net
function drawNet() {
drawRect(net.x, net.y, net.width, net.height, net.color);
}
// Reset ball position
function resetBall() {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.speed = 7;
ball.velocityX = -ball.velocityX;
}
// Draw everything on the canvas
function draw() {
drawRect(0, 0, canvas.width, canvas.height, "#000");
drawNet();
drawText(player1.score, canvas.width / 4, canvas.height / 5);
drawText(player2.score, 3 * canvas.width / 4, canvas.height / 5);
drawRect(player1.x, player1.y, player1.width, player1.height, player1.color);
drawRect(player2.x, player2.y, player2.width, player2.height, player2.color);
drawArc(ball.x, ball.y, ball.radius, ball.color);
}
// Move paddles based on key press
function movePaddles() {
// Player 1 (W/S keys)
if (wPressed && player1.y > 0) {
player1.y -= 8;
} else if (sPressed && (player1.y < canvas.height - player1.height)) {
player1.y += 8;
}
// Player 2 (Arrow keys)
if (upArrowPressed && player2.y > 0) {
player2.y -= 8;
} else if (downArrowPressed && (player2.y < canvas.height - player2.height)) {
player2.y += 8;
}
}
// Update the game state
function update() {
ball.x += ball.velocityX;
ball.y += ball.velocityY;
// Ball collision with top and bottom walls
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.velocityY = -ball.velocityY;
}
// Ball collision with paddles
let player = (ball.x < canvas.width / 2) ? player1 : player2;
if (collisionDetect(player, ball)) {
let collidePoint = (ball.y - (player.y + player.height / 2));
collidePoint = collidePoint / (player.height / 2);
let angleRad = (Math.PI / 4) * collidePoint;
let direction = (ball.x < canvas.width / 2) ? 1 : -1;
ball.velocityX = direction * ball.speed * Math.cos(angleRad);
ball.velocityY = ball.speed * Math.sin(angleRad);
ball.speed += 0.1;
}
// Ball out of bounds
if (ball.x - ball.radius < 0) {
player2.score++;
resetBall();
} else if (ball.x + ball.radius > canvas.width) {
player1.score++;
resetBall();
}
movePaddles();
}
// Check collision between ball and paddle
function collisionDetect(player, ball) {
player.top = player.y;
player.bottom = player.y + player.height;
player.left = player.x;
player.right = player.x + player.width;
ball.top = ball.y - ball.radius;
ball.bottom = ball.y + ball.radius;
ball.left = ball.x - ball.radius;
ball.right = ball.x + ball.radius;
return player.left < ball.right && player.top < ball.bottom && player.right > ball.left && player.bottom > ball.top;
}
// Main game loop
function gameLoop() {
update();
draw();
}
// Handle keyboard input
document.addEventListener("keydown", function(event) {
switch(event.keyCode) {
case 87: // W key
wPressed = true;
break;
case 83: // S key
sPressed = true;
break;
case 38: // Up arrow
upArrowPressed = true;
break;
case 40: // Down arrow
downArrowPressed = true;
break;
}
});
document.addEventListener("keyup", function(event) {
switch(event.keyCode) {
case 87: // W key
wPressed = false;
break;
case 83: // S key
sPressed = false;
break;
case 38: // Up arrow
upArrowPressed = false;
break;
case 40: // Down arrow
downArrowPressed = false;
break;
}
});
// Start game loop
setInterval(gameLoop, 1000 / 60);
</script>
</body>
</html>
45)TYPING SPEED...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typing Speed Game</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Ubuntu&display=swap');
* {
margin: 0;
padding: 0;
font-family: 'Ubuntu', sans-serif;
}
body {
background: linear-gradient(to bottom right, #33ccff 0%, #ff99cc 100%);
background-repeat: no-repeat;
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
h1 {
color: white;
}
.container {
width: 100%;
max-width: 600px;
background-color: white;
border-radius: 10px;
padding: 20px;
position: relative;
}
.container input {
z-index: -10;
position: absolute;
opacity: 0;
}
#pg {
background-color: white;
color: rgb(148, 148, 148);
}
#pg::selection {
background-color: #ff99cc;
color: black;
}
.containerin {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 20px;
background-color: #242424;
padding: 10px;
border-radius: 5px;
}
.result {
display: flex;
color: white;
justify-content: space-between;
width: 90%;
}
.result .txt1 {
font-size: 14px;
}
.result .txt2 {
font-size: 20px;
font-weight: bold;
background-color: #33ccff;
border-radius: 15px;
padding: 5px;
text-align: center;
min-width: 50px;
margin-left: 5px;
}
.result div {
display: flex;
align-items: center;
flex-direction: column;
margin: 0px 10px;
}
.containerin button {
background-color: #ff99cc;
color: white;
border: none;
padding: 5px 20px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Typing Speed Game</h1>
<div class="container">
<input type="text" class="textinput" />
<p id="pg">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi doloribus labore nam exercitationem sunt.
Minima at similique molestiae quo. Assumenda, modi! Doloribus facilis facere explicabo inventore cupiditate
consequuntur. Dolorum quidem, odit deserunt ipsa beatae porro ipsum maxime reprehenderit cum tempore
perspiciatis nesciunt aliquid et id iste inventore soluta quam, repellat saepe consectetur. Quos vero
facilis impedit ad? Quis, sit fugit?
</p>
<div class="containerin">
<div class="result">
<div class="time">
<p class="txt1">Time</p>
<p class="txt2">60s</p>
</div>
<div class="wpm">
<p class="txt1">WPM</p>
<p class="txt2">0</p>
</div>
<div class="mistake">
<p class="txt1">Mistakes</p>
<p class="txt2">0</p>
</div>
<div class="cpm">
<p class="txt1">CPM</p>
<p class="txt2">0</p>
</div>
</div>
<button id="start-button">Start</button>
</div>
</div>
<script>
const quoteElement = document.getElementById('pg');
const inputElement = document.querySelector('.textinput');
const startButton = document.getElementById('start-button');
const timeElement = document.querySelector('.time .txt2');
const wpmElement = document.querySelector('.wpm .txt2');
const mistakesElement = document.querySelector('.mistake .txt2');
const cpmElement = document.querySelector('.cpm .txt2');
const quotes = [
"The quick brown fox jumps over the lazy dog.",
"A journey of a thousand miles begins with a single step.",
"To be or not to be, that is the question.",
"All that glitters is not gold.",
"The only thing we have to fear is fear itself."
];
let startTime;
let timerInterval;
let mistakes = 0;
function getRandomQuote() {
const randomIndex = Math.floor(Math.random() * quotes.length);
return quotes[randomIndex];
}
function startGame() {
const quoteText = getRandomQuote();
quoteElement.textContent = quoteText;
inputElement.value = '';
inputElement.focus();
startTime = new Date().getTime();
mistakes = 0;
mistakesElement.textContent = mistakes;
timerInterval = setInterval(updateTimer, 1000);
}
function endGame() {
clearInterval(timerInterval);
const endTime = new Date().getTime();
const timeTaken = (endTime - startTime) / 1000;
const wordsPerMinute = (quoteElement.textContent.split(' ').length / timeTaken) * 60;
const charactersPerMinute = (quoteElement.textContent.length / timeTaken) * 60;
wpmElement.textContent = wordsPerMinute.toFixed(2);
cpmElement.textContent = charactersPerMinute.toFixed(2);
}
function updateTimer() {
const currentTime = new Date().getTime();
const timeElapsed = (currentTime - startTime) / 1000;
timeElement.textContent = `${(60 - timeElapsed).toFixed(2)}s`;
if (timeElapsed >= 60) {
endGame();
}
}
inputElement.addEventListener('input', function() {
const inputText = inputElement.value;
const quoteText = quoteElement.textContent;
if (inputText === quoteText) {
endGame();
}
let mistakeCount = 0;
for (let i = 0; i < inputText.length; i++) {
if (inputText[i] !== quoteText[i]) {
mistakeCount++;
}
}
mistakes = mistakeCount;
mistakesElement.textContent = mistakes;
});
startButton.addEventListener('click', function() {
startGame();
timeElement.textContent = '60s';
wpmElement.textContent = '0';
cpmElement.textContent = '0';
mistakesElement.textContent = '0';
});
</script>
</body>
</html>
46)KBC...Don't try
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
:root {
--col1: #391D6F;
}
* {
margin: 0;
padding: 0;
}
.gamecontainer {
width: 100%;
height: 100vh;
background-color: var(--col1);
display: flex;
justify-content: space-between;
}
.left {
width: 70%;
height: 100%;
background-color: antiquewhite;
display: flex;
flex-direction: column;
border-right: 2px solid white;
justify-content: center;
}
.question .container {
width: 100%;
background-color: aliceblue;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
.hr {
width: 50%;
height: 3px;
background-color: white;
}
.question-container p {
color: white;
font-size: 25px;
width: 100%;
text-align: center;
border: 4px solid white;
padding: 10px 20 px;
}
.answer-container {
width: 100%;
display: flex;
flex-direction: column;
}
.answer-container.answerin {
display: flex;
justify-content: space-between;
align-items: center;
margin: 20px 0px;
}
.answer-container .answerin p {
color: white;
font-size: 25px;
width: 100%;
text-align: center;
border: 4px solid white;
padding: 10px 20px;
}
.answer-container .answerin p span {
color: gold;
}
.answer-container .answerin p:hover {
background-color: white;
cursor: pointer;
color: var(--col1);
}
/*Right selection starts here*/
.right {
width: 30%;
height: 100%;
display: flex;
flex-direction: column;
}
.progress {
width: 70%;
background-color: white;
align-self: center;
height: 50%;
display: flex;
flex-direction: column;
justify-content: center;
}
.progressin {
width: 100%;
display: flex;
justify-content: flex-start;
align-items: center;
padding: 5px 20px;
background-color: aquamarine;
margin: 5px 0px;
font-size: 20px;
color: white;
}
.progressin1 {
width: 100%;
display: flex;
justify-content: flex-start;
align-items: center;
padding: 5px 20px;
background-color: aquamarine;
margin: 5px 0px;
font-size: 30px;
color: gold;
}
.progressin:hover,
.progress .active {
background-color: gold;
color: black;
cursor: pointer;
}
.hr1 {
width: 100%;
height: 3px;
background-color: white;
}
.lifelines {
display: flex;
width: 100%;
height: 40%;
align-items: center;
justify-content: space-around;
flex-wrap: wrap;
}
.lifelinesin {
width: 25%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid white;
border-radius: 20px;
}
.lifelinein img {
width: 50%;
margin: 0px 20px;
object-fit: contain;
}
.lifelinein:hover {
box-shadow: 0px 0px 10px 5px white;
transform: scale(1.1);
cursor: pointer;
transition: all 0.5s ease-in-out;
}
</style>
<body>
<div class="gamecontainer">
<div class="left">
<!--question and answer-->
<div class="--question-container">
<div class="hr"></div>
<p>-----------</p>
<div class="hr"></div>
</div>
<div class="answer-container">
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
<div class="gamecontainer">
<div class="left">
</div>
<div class="right">
<div class="lifelines"></div>
<div class="lifelinesin">
<img src="Vande-Bharat-Express-png.webp" alt="">
</div>
<div class="lifelinesin">
<img src="Vande-Bharat-Express-png.webp" alt="">
</div>
<div class="lifelinesin">
<img src="Vande-Bharat-Express-png.webp" alt="">
</div>
</div>
<div class="hr1"></div>
<div class="progress">
<div class="progressin1">Rs. 1 Million</div>
<div class="progressin">Rs. 500,000</div>
<div class="progressin">Rs. 250,000</div>
<div class="progressin1">Rs. 100,000</div>
<div class="progressin">Rs. 50,000</div>
<div class="progressin">Rs. 25,000</div>
<div class="progressin1">Rs. 16,000</div>
<div class="progressin">Rs. 8,000</div>
<div class="progressin">Rs. 4,000</div>
<div class="progressin">Rs. 2,000</div>
<div class="progressin1">Rs. 1,000</div>
<div class="progressin active">Rs. 0</div>
</div>
</div>
</div>
<div class="right">
</div>
</div>
</body>
<script>
const q1set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q2set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q3set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q4set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q5set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q6set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q7set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q8set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q9set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q10set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q11set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const q12set = [
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
{
question: "what is the name of the ancient incan city in paru that is considerd one of the new seven wonders of the world?",
a: "Anger wat",
b: "petra",
c: "Machu picchu",
d: "The Colosseum",
correct: "Machu picchu"
},
]
const progresset = [
{
id: 1,
price: 0,
},
{
id: 2,
price: 1000,
},
{
id: 3,
price: 2000,
},
{
id: 4,
price: 4000,
},
{
id: 5,
price: 8000,
},
{
id: 6,
price: 16000,
},
{
id: 7,
price: 32000,
},
{
id: 8,
price: 64000,
},
{
id: 9,
price: 125000,
},
{
id: 10,
price: 250000,
},
{
id: 11,
price: 500000,
},
{
id: 12,
price: 1000000,
},
]
const showProgressSet = (progresset) => {
let progressDiv = document.querySelector(".progress");
let progresssetdivdata = '';
//console.log(progressdiv)
progressset = progressset.sort((a, b) => b.price = a.price);
progresset.forEach((item, index) => {
if (item.price == 1000 || item.price == 16000
|| item.price == 125000 || item.price == 1000000
) {
item.price = item.price.tolocalestring();
//console.log(item.price)
progresssetdivdata +=
<div class="progressin1">Rs. ${item.price}</div>
}
else {
item.price = item.price.tolocalestring();
//console.log(item.price)
progresssetdivdata +=
<div class="progressin">Rs. ${item.price}</div>
}
})
}
progressDiv.innerHTML = progressHTML;
showProgressSet(progresset)
const question = document.querySelector(".question-container p")
const allanswerscont = document.querySelector("answer-comtainer")
const setquestionandanswer = (currentQuestion) => {
if (currentQuestion == 1) {
else if (currentQuestion == 2) {
let random = Math.floor(Math.random() * q2set.length)
let randomquestion = q2set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 3) {
let random = Math.floor(Math.random() * q3set.length)
let randomquestion = q3set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 4) {
let random = Math.floor(Math.random() * q4set.length)
let randomquestion = q4set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 5) {
let random = Math.floor(Math.random() * q5set.length)
let randomquestion = q5set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 6) {
let random = Math.floor(Math.random() * q6set.length)
let randomquestion = q6set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 7) {
let random = Math.floor(Math.random() * q7set.length)
let randomquestion = q7set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 8) {
let random = Math.floor(Math.random() * q8set.length)
let randomquestion = q8set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 9) {
let random = Math.floor(Math.random() * q9set.length)
let randomquestion = q9set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 10) {
let random = Math.floor(Math.random() * q10set.length)
let randomquestion = q2set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 11) {
let random = Math.floor(Math.random() * q11set.length)
let randomquestion = q11set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
else if (currentQuestion == 12) {
let random = Math.floor(Math.random() * q12set.length)
let randomquestion = q12set[random]
question.innerHTML = randomquestion.question;
allanswerscont.innerHTML =
<div class="answerin">
<div class="hr"></div>
<p>
<span>A</span> ${randomquestion.a}
</p>
<div class="hr"></div>
<p>
<span>B</span> ${randomquestion.b}
</p>
<div class="hr"></div>
</div>
<div class="answerin">
<div class="hr"></div>
<p>
<span>C</span> ${randomquestion.c}
</p>
<div class="hr"></div>
<p>
<span>D</span> ${randomquestion.d}
</p>
<div class="hr"></div>
</div>
}
setquestionandanswer(currentQuestion)
const setactivetoprogressitem = (currentQuestion)=>{
let progresssetdiv = document.querySelector(".progress")
let progresssetdata = progresssetdiv.querySelectorAll("div")
let progresssetdivdatalength = progresssetdivdata.length
progresssetdivdata[currentQuestion - 1].
classList.add("active")
}
setactivetoprogressitem(currentQuestion)
</script>
</html>
*)KBC try this...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Game</title>
<style>
:root {
--col1: #391D6F;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
}
.gamecontainer {
width: 100%;
height: 100vh;
background-color: var(--col1);
display: flex;
justify-content: space-between;
}
.left {
width: 70%;
height: 100%;
background-color: antiquewhite;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border-right: 2px solid white;
}
.question-container {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20px;
}
.question-container p {
color: white;
font-size: 25px;
width: 80%;
text-align: center;
border: 4px solid white;
padding: 10px 20px;
}
.answer-container {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.answer-container .answerin {
display: flex;
justify-content: space-between;
align-items: center;
margin: 20px 0px;
}
.answer-container .answerin p {
color: white;
font-size: 25px;
width: 45%;
text-align: center;
border: 4px solid white;
padding: 10px 20px;
cursor: pointer;
}
.answer-container .answerin p:hover {
background-color: white;
color: var(--col1);
}
.right {
width: 30%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
.progress {
width: 70%;
background-color: white;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
}
.progressin {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
padding: 5px 20px;
background-color: aquamarine;
margin: 5px 0px;
font-size: 20px;
color: white;
cursor: pointer;
}
.progressin.active {
background-color: gold;
color: black;
}
.hr1 {
width: 100%;
height: 3px;
background-color: white;
}
.lifelines {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.lifelinesin {
width: 25%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid white;
border-radius: 20px;
margin: 10px;
cursor: pointer;
transition: transform 0.3s ease;
}
.lifelinesin:hover {
transform: scale(1.1);
}
.lifelinein img {
width: 50%;
margin: 0px 20px;
object-fit: contain;
}
</style>
</head>
<body>
<div class="gamecontainer">
<div class="left">
<div class="question-container">
<div class="hr"></div>
<p id="question">Question will be displayed here</p>
<div class="hr"></div>
</div>
<div class="answer-container" id="answers">
<!-- Answers will be dynamically inserted here -->
</div>
</div>
<div class="right">
<div class="progress" id="progress">
<!-- Progress will be dynamically inserted here -->
</div>
<div class="gamecontainer">
<div class="left">
<div class="question">Question 1</div>
<div class="answer">Answer 1</div>
<div class="answer">Answer 2</div>
<div class="answer">Answer 3</div>
<div class="answer">Answer 4</div>
</div>
<div class="right">
<div class="progress">
<div class="progress-bar">
<div class="progress-bar-inner"></div>
</div>
</div>
<div class="lifelines">
<img src="https://via.placeholder.com/150" alt="Lifeline Image">
</div>
</div>
</div>
<div class="hr1"></div>
<div class="lifelines">
<div class="lifelinesin">
<img src="Vande-Bharat-Express-png.webp" alt="Lifeline 1">
</div>
<div class="lifelinesin">
<img src="Vande-Bharat-Express-png.webp" alt="Lifeline 2">
</div>
<div class="lifelinesin">
<img src="Vande-Bharat-Express-png.webp" alt="Lifeline 3">
</div>
</div>
</div>
</div>
<script>
const questions = [
{
question: "What is the capital of France?",
a: "Paris",
b: "London",
c: "Berlin",
d: "Rome",
correct: "a"
},
// Add more questions here
];
const progress = [
{ id: 1, price: 0 },
{ id: 2, price: 1000 },
{ id: 3, price: 2000 },
{ id: 4, price: 4000 },
{ id: 5, price: 8000 },
{ id: 6, price: 16000 },
{ id: 7, price: 32000 },
{ id: 8, price: 64000 },
{ id: 9, price: 125000 },
{ id: 10, price: 250000 },
{ id: 11, price: 500000 },
{ id: 12, price: 1000000 },
];
const questionElement = document.getElementById('question');
const answersElement = document.getElementById('answers');
const progressElement = document.getElementById('progress');
let currentQuestionIndex = 0;
function showProgressSet() {
progressElement.innerHTML = '';
progress.sort((a, b) => b.price - a.price).forEach(item => {
const progressItem = document.createElement('div');
progressItem.classList.add('progressin');
if (item.price % 100000 === 0) {
progressItem.classList.add('active');
}
progressItem.textContent = `Rs. ${item.price.toLocaleString()}`;
progressElement.appendChild(progressItem);
});
}
function setQuestionAndAnswer() {
const currentQuestion = questions[currentQuestionIndex];
questionElement.textContent = currentQuestion.question;
answersElement.innerHTML = `
<div class="answerin">
<p><span>A</span> ${currentQuestion.a}</p>
<p><span>B</span> ${currentQuestion.b}</p>
</div>
<div class="answerin">
<p><span>C</span> ${currentQuestion.c}</p>
<p><span>D</span> ${currentQuestion.d}</p>
</div>
`;
}
function setActiveProgressItem() {
const progressItems = progressElement.querySelectorAll('.progressin');
progressItems.forEach((item, index) => {
if (index === currentQuestionIndex) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
function nextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex >= questions.length) {
alert('Quiz completed!');
return;
}
setQuestionAndAnswer();
setActiveProgressItem();
}
showProgressSet();
setQuestionAndAnswer();
setActiveProgressItem();
// Add event listeners for answer selection
answersElement.addEventListener('click', (event) => {
if (event.target.tagName === 'P') {
const selectedAnswer = event.target.textContent.trim().charAt(0);
const correctAnswer = questions[currentQuestionIndex].correct;
if (selectedAnswer === correctAnswer) {
alert('Correct answer!');
} else {
alert('Wrong answer!');
}
nextQuestion();
}
});
</script>
</body>
</html>
47)Quiz game using C
#include<stdio.h>
int main()
{
int i;
int ans1, ans2, ans3, ans4, ans5;
int point1, point2, point3, point4, point5;
int total;
printf("Welcome to the CET Quiz Game\n\n");
printf("> Press 7 to start the game\n");
printf("> Press 0 to quit the game\n");
scanf("%d", &i);
if(i == 7)
{
printf("The game has started\n\n");
}
else if(i == 0)
{
printf("The game has ended\n\n");
return 0;
}
else
{
printf("Invalid choice\n\n");
return 0;
}
if(i == 7)
{
printf("1) What is the chemical symbol for Gold?\n");
printf("a) Au\n");
printf("b) Ag\n");
printf("c) Pb\n");
printf("d) Fe\n\n");
printf("Enter your Answer (1-4): ");
scanf("%d", &ans1);
if(ans1 == 1) // Correct answer is "a) Au"
{
printf("Correct Answer\n");
point1 = 5;
}
else
{
printf("Wrong Answer\n");
point1 = 0;
}
printf("You have scored %d points\n\n", point1);
printf("2) What is the square root of 144?\n");
printf("a) 10\n");
printf("b) 12\n");
printf("c) 14\n");
printf("d) 16\n\n");
printf("Enter your Answer (1-4): ");
scanf("%d", &ans2);
if(ans2 == 2) // Correct answer is "b) 12"
{
printf("Correct Answer\n");
point2 = 5;
}
else
{
printf("Wrong Answer\n");
point2 = 0;
}
printf("You have scored %d points\n\n", point2);
printf("3) Who wrote the play 'Hamlet'?\n");
printf("a) Charles Dickens\n");
printf("b) George Orwell\n");
printf("c) William Shakespeare\n");
printf("d) Jane Austen\n\n");
printf("Enter your Answer (1-4): ");
scanf("%d", &ans3);
if(ans3 == 3) // Correct answer is "c) William Shakespeare"
{
printf("Correct Answer\n");
point3 = 5;
}
else
{
printf("Wrong Answer\n");
point3 = 0;
}
printf("You have scored %d points\n\n", point3);
printf("4) What is the capital of France?\n");
printf("a) Berlin\n");
printf("b) Madrid\n");
printf("c) Rome\n");
printf("d) Paris\n\n");
printf("Enter your Answer (1-4): ");
scanf("%d", &ans4);
if(ans4 == 4) // Correct answer is "d) Paris"
{
printf("Correct Answer\n");
point4 = 5;
}
else
{
printf("Wrong Answer\n");
point4 = 0;
}
printf("You have scored %d points\n\n", point4);
printf("5) What is the value of Pi (Ï€) up to two decimal places?\n");
printf("a) 3.12\n");
printf("b) 3.14\n");
printf("c) 3.16\n");
printf("d) 3.18\n\n");
printf("Enter your Answer (1-4): ");
scanf("%d", &ans5);
if(ans5 == 2) // Correct answer is "b) 3.14"
{
printf("Correct Answer\n");
point5 = 5;
}
else
{
printf("Wrong Answer\n");
point5 = 0;
}
printf("You have scored %d points\n\n", point5);
total = point1 + point2 + point3 + point4 + point5;
printf("Your total score is: %d points\n", total);
}
return 0;
}
48)Can you please search the atomic number?
#include <stdio.h>
// Function to print element details
void printElementDetails(int atomicNumber)
{
switch (atomicNumber)
{
case 1:
printf("Name: Hydrogen\n");
printf("Symbol: H\n");
printf("Atomic number: 1\n");
printf("Atomic mass: 1.008\n");
printf("Electron configuration: 1s^1\n");
printf("Discovered by: Henry Cavendish\n");
printf("Charge: +1\n");
break;
case 2:
printf("Name: Helium\n");
printf("Symbol: He\n");
printf("Atomic number: 2\n");
printf("Atomic mass: 4.0026\n");
printf("Electron configuration: 1s^2\n");
printf("Discovered by: Pierre Janssen and Sir William Ramsay\n");
printf("Charge: 0\n");
break;
case 3:
printf("Name: Lithium\n");
printf("Symbol: Li\n");
printf("Atomic number: 3\n");
printf("Atomic mass: 6.94\n");
printf("Electron configuration: 1s^2 2s^1\n");
printf("Discovered by: Johan August Arfwedson\n");
printf("Charge: +1\n");
break;
case 4:
printf("Name: Beryllium\n");
printf("Symbol: Be\n");
printf("Atomic number: 4\n");
printf("Atomic mass: 9.0122\n");
printf("Electron configuration: 1s^2 2s^2\n");
printf("Discovered by: Louis Nicolas Vauquelin\n");
printf("Charge: +2\n");
break;
case 5:
printf("Name: Boron\n");
printf("Symbol: B\n");
printf("Atomic number: 5\n");
printf("Atomic mass: 10.81\n");
printf("Electron configuration: 1s^2 2s^2 2p^1\n");
printf("Discovered by: Joseph Louis Gay-Lussac\n");
printf("Charge: +3\n");
break;
case 6:
printf("Name: Carbon\n");
printf("Symbol: C\n");
printf("Atomic number: 6\n");
printf("Atomic mass: 12.011\n");
printf("Electron configuration: 1s^2 2s^2 2p^2\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +4/-4\n");
break;
case 7:
printf("Name: Nitrogen\n");
printf("Symbol: N\n");
printf("Atomic number: 7\n");
printf("Atomic mass: 14.007\n");
printf("Electron configuration: 1s^2 2s^2 2p^3\n");
printf("Discovered by: Daniel Rutherford\n");
printf("Charge: -3\n");
break;
case 8:
printf("Name: Oxygen\n");
printf("Symbol: O\n");
printf("Atomic number: 8\n");
printf("Atomic mass: 15.999\n");
printf("Electron configuration: 1s^2 2s^2 2p^4\n");
printf("Discovered by: Carl Wilhelm Scheele\n");
printf("Charge: -2\n");
break;
case 9:
printf("Name: Fluorine\n");
printf("Symbol: F\n");
printf("Atomic number: 9\n");
printf("Atomic mass: 18.998\n");
printf("Electron configuration: 1s^2 2s^2 2p^5\n");
printf("Discovered by: Henri Moissan\n");
printf("Charge: -1\n");
break;
case 10:
printf("Name: Neon\n");
printf("Symbol: Ne\n");
printf("Atomic number: 10\n");
printf("Atomic mass: 20.180\n");
printf("Electron configuration: 1s^2 2s^2 2p^6\n");
printf("Discovered by: Sir William Ramsay and Morris Travers\n");
printf("Charge: 0\n");
break;
// Continue adding elements for atomic numbers 11 to 118
// The following is an example for some more elements
case 11:
printf("Name: Sodium\n");
printf("Symbol: Na\n");
printf("Atomic number: 11\n");
printf("Atomic mass: 22.990\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^1\n");
printf("Discovered by: Humphry Davy\n");
printf("Charge: +1\n");
break;
case 12:
printf("Name: Magnesium\n");
printf("Symbol: Mg\n");
printf("Atomic number: 12\n");
printf("Atomic mass: 24.305\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2\n");
printf("Discovered by: Joseph Black\n");
printf("Charge: +2\n");
break;
case 13:
printf("Name: Aluminum\n");
printf("Symbol: Al\n");
printf("Atomic number: 13\n");
printf("Atomic mass: 26.9815\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^1\n");
printf("Discovered by: Hans Christian Ørsted\n");
printf("Charge: +3\n");
break;
case 14:
printf("Name: Silicon\n");
printf("Symbol: Si\n");
printf("Atomic number: 14\n");
printf("Atomic mass: 28.085\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^2\n");
printf("Discovered by: Jöns Jakob Berzelius\n");
printf("Charge: +4/-4\n");
break;
case 15:
printf("Name: Phosphorus\n");
printf("Symbol: P\n");
printf("Atomic number: 15\n");
printf("Atomic mass: 30.9738\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^3\n");
printf("Discovered by: Hennig Brand\n");
printf("Charge: -3\n");
break;
case 16:
printf("Name: Sulfur\n");
printf("Symbol: S\n");
printf("Atomic number: 16\n");
printf("Atomic mass: 32.06\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^4\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: -2\n");
break;
case 17:
printf("Name: Chlorine\n");
printf("Symbol: Cl\n");
printf("Atomic number: 17\n");
printf("Atomic mass: 35.45\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^5\n");
printf("Discovered by: Carl Wilhelm Scheele\n");
printf("Charge: -1\n");
break;
case 18:
printf("Name: Argon\n");
printf("Symbol: Ar\n");
printf("Atomic number: 18\n");
printf("Atomic mass: 39.948\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6\n");
printf("Discovered by: Lord Rayleigh and Sir William Ramsay\n");
printf("Charge: 0\n");
break;
case 19:
printf("Name: Potassium\n");
printf("Symbol: K\n");
printf("Atomic number: 19\n");
printf("Atomic mass: 39.0983\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^1\n");
printf("Discovered by: Humphry Davy\n");
printf("Charge: +1\n");
break;
case 20:
printf("Name: Calcium\n");
printf("Symbol: Ca\n");
printf("Atomic number: 20\n");
printf("Atomic mass: 40.078\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2\n");
printf("Discovered by: Humphry Davy\n");
printf("Charge: +2\n");
break;
case 21:
printf("Name: Scandium\n");
printf("Symbol: Sc\n");
printf("Atomic number: 21\n");
printf("Atomic mass: 44.9559\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^1\n");
printf("Discovered by: Lars Frederik Nilson\n");
printf("Charge: +3\n");
break;
case 22:
printf("Name: Titanium\n");
printf("Symbol: Ti\n");
printf("Atomic number: 22\n");
printf("Atomic mass: 47.867\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^2\n");
printf("Discovered by: William Gregor\n");
printf("Charge: +4\n");
break;
case 23:
printf("Name: Vanadium\n");
printf("Symbol: V\n");
printf("Atomic number: 23\n");
printf("Atomic mass: 50.9415\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^3\n");
printf("Discovered by: Andrés Manuel del RÃo\n");
printf("Charge: +5\n");
break;
case 24:
printf("Name: Chromium\n");
printf("Symbol: Cr\n");
printf("Atomic number: 24\n");
printf("Atomic mass: 51.996\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^1 3d^5\n");
printf("Discovered by: Louis Nicolas Vauquelin\n");
printf("Charge: +6\n");
break;
case 25:
printf("Name: Manganese\n");
printf("Symbol: Mn\n");
printf("Atomic number: 25\n");
printf("Atomic mass: 54.938\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^5\n");
printf("Discovered by: Johann Gottlieb Gahn\n");
printf("Charge: +7\n");
break;
case 26:
printf("Name: Iron\n");
printf("Symbol: Fe\n");
printf("Atomic number: 26\n");
printf("Atomic mass: 55.845\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^6\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +2/+3\n");
break;
case 27:
printf("Name: Cobalt\n");
printf("Symbol: Co\n");
printf("Atomic number: 27\n");
printf("Atomic mass: 58.933\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^7\n");
printf("Discovered by: Georg Brandt\n");
printf("Charge: +2/+3\n");
break;
case 28:
printf("Name: Nickel\n");
printf("Symbol: Ni\n");
printf("Atomic number: 28\n");
printf("Atomic mass: 58.933\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^8\n");
printf("Discovered by: Axel Fredrik Cronstedt\n");
printf("Charge: +2/+3\n");
break;
case 29:
printf("Name: Copper\n");
printf("Symbol: Cu\n");
printf("Atomic number: 29\n");
printf("Atomic mass: 63.546\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^1 3d^10\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +1/+2\n");
break;
case 30:
printf("Name: Zinc\n");
printf("Symbol: Zn\n");
printf("Atomic number: 30\n");
printf("Atomic mass: 65.38\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +2\n");
break;
case 31:
printf("Name: Gallium\n");
printf("Symbol: Ga\n");
printf("Atomic number: 31\n");
printf("Atomic mass: 69.723\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4p^1\n");
printf("Discovered by: Paul-Émile Lecoq de Boisbaudran\n");
printf("Charge: +3\n");
break;
case 32:
printf("Name: Germanium\n");
printf("Symbol: Ge\n");
printf("Atomic number: 32\n");
printf("Atomic mass: 72.63\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4p^2\n");
printf("Discovered by: Clemens Winkler\n");
printf("Charge: +4\n");
break;
case 33:
printf("Name: Arsenic\n");
printf("Symbol: As\n");
printf("Atomic number: 33\n");
printf("Atomic mass: 74.9216\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4p^3\n");
printf("Discovered by: Albertus Magnus\n");
printf("Charge: -3/+3/+5\n");
break;
case 34:
printf("Name: Selenium\n");
printf("Symbol: Se\n");
printf("Atomic number: 34\n");
printf("Atomic mass: 78.971\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4p^4\n");
printf("Discovered by: Jakob Berzelius\n");
printf("Charge: -2/-4/-6\n");
break;
case 35:
printf("Name: Bromine\n");
printf("Symbol: Br\n");
printf("Atomic number: 35\n");
printf("Atomic mass: 79.904\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4p^5\n");
printf("Discovered by: Antoine Jérôme Balard\n");
printf("Charge: -1\n");
break;
case 36:
printf("Name: Krypton\n");
printf("Symbol: Kr\n");
printf("Atomic number: 36\n");
printf("Atomic mass: 83.798\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4p^6\n");
printf("Discovered by: Sir William Ramsay and Morris Travers\n");
printf("Charge: 0\n");
break;
case 37:
printf("Name: Rubidium\n");
printf("Symbol: Rb\n");
printf("Atomic number: 37\n");
printf("Atomic mass: 84.468\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^1 5s^1\n");
printf("Discovered by: Robert Bunsen and Gustav Kirchhoff\n");
printf("Charge: +1\n");
break;
case 38:
printf("Name: Strontium\n");
printf("Symbol: Sr\n");
printf("Atomic number: 38\n");
printf("Atomic mass: 87.62\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 5s^2\n");
printf("Discovered by: William Cruickshank\n");
printf("Charge: +2\n");
break;
case 39:
printf("Name: Yttrium\n");
printf("Symbol: Y\n");
printf("Atomic number: 39\n");
printf("Atomic mass: 88.905\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^1 4d^1\n");
printf("Discovered by: Johan Gadolin\n");
printf("Charge: +3\n");
break;
case 40:
printf("Name: Zirconium\n");
printf("Symbol: Zr\n");
printf("Atomic number: 40\n");
printf("Atomic mass: 91.224\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^2\n");
printf("Discovered by: Martin Heinrich Klaproth\n");
printf("Charge: +4\n");
break;
case 41:
printf("Name: Niobium\n");
printf("Symbol: Nb\n");
printf("Atomic number: 41\n");
printf("Atomic mass: 92.906\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^4\n");
printf("Discovered by: Charles Hatchett\n");
printf("Charge: +5\n");
break;
case 42:
printf("Name: Molybdenum\n");
printf("Symbol: Mo\n");
printf("Atomic number: 42\n");
printf("Atomic mass: 95.95\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^5\n");
printf("Discovered by: Carl Wilhelm Scheele\n");
printf("Charge: +6\n");
break;
case 43:
printf("Name: Technetium\n");
printf("Symbol: Tc\n");
printf("Atomic number: 43\n");
printf("Atomic mass: 98\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^5\n");
printf("Discovered by: Carlo Perrier and Emilio Segrè\n");
printf("Charge: +7\n");
break;
case 44:
printf("Name: Ruthenium\n");
printf("Symbol: Ru\n");
printf("Atomic number: 44\n");
printf("Atomic mass: 101.07\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^7\n");
printf("Discovered by: Karl Ernst Claus\n");
printf("Charge: +8\n");
break;
case 45:
printf("Name: Rhodium\n");
printf("Symbol: Rh\n");
printf("Atomic number: 45\n");
printf("Atomic mass: 102.905\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^8\n");
printf("Discovered by: William Hyde Wollaston\n");
printf("Charge: +3\n");
break;
case 46:
printf("Name: Palladium\n");
printf("Symbol: Pd\n");
printf("Atomic number: 46\n");
printf("Atomic mass: 106.42\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10\n");
printf("Discovered by: William Hyde Wollaston\n");
printf("Charge: +2/+4\n");
break;
case 47:
printf("Name: Silver\n");
printf("Symbol: Ag\n");
printf("Atomic number: 47\n");
printf("Atomic mass: 107.868\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^1 3d^10 4d^10\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +1/+2\n");
break;
case 48:
printf("Name: Cadmium\n");
printf("Symbol: Cd\n");
printf("Atomic number: 48\n");
printf("Atomic mass: 112.414\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10\n");
printf("Discovered by: Friedrich Stromeyer\n");
printf("Charge: +2\n");
break;
case 49:
printf("Name: Indium\n");
printf("Symbol: In\n");
printf("Atomic number: 49\n");
printf("Atomic mass: 114.818\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2 4d^1\n");
printf("Discovered by: Ferdinand Reich and Hieronymous Theodor Richter\n");
printf("Charge: +3\n");
break;
case 50:
printf("Name: Tin\n");
printf("Symbol: Sn\n");
printf("Atomic number: 50\n");
printf("Atomic mass: 118.710\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2 4d^10 5p^2\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +2/+4\n");
break;
case 51:
printf("Name: Antimony\n");
printf("Symbol: Sb\n");
printf("Atomic number: 51\n");
printf("Atomic mass: 121.760\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2 4d^10 5p^3\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: -3/+3/+5\n");
break;
case 52:
printf("Name: Tellurium\n");
printf("Symbol: Te\n");
printf("Atomic number: 52\n");
printf("Atomic mass: 127.60\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2 4d^10 5p^4\n");
printf("Discovered by: Franz-Joseph Müller von Reichenstein\n");
printf("Charge: -2/-4/-6\n");
break;
case 53:
printf("Name: Iodine\n");
printf("Symbol: I\n");
printf("Atomic number: 53\n");
printf("Atomic mass: 126.904\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2 4d^10 5p^5\n");
printf("Discovered by: Bernard Courtois\n");
printf("Charge: -1\n");
break;
case 54:
printf("Name: Xenon\n");
printf("Symbol: Xe\n");
printf("Atomic number: 54\n");
printf("Atomic mass: 131.293\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2 4d^10 5p^6\n");
printf("Discovered by: Sir William Ramsay and Morris Travers\n");
printf("Charge: 0\n");
break;
case 55:
printf("Name: Cesium\n");
printf("Symbol: Cs\n");
printf("Atomic number: 55\n");
printf("Atomic mass: 132.905\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^1\n");
printf("Discovered by: Robert Bunsen and Gustav Kirchhoff\n");
printf("Charge: +1\n");
break;
case 56:
printf("Name: Barium\n");
printf("Symbol: Ba\n");
printf("Atomic number: 56\n");
printf("Atomic mass: 137.327\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^2\n");
printf("Discovered by: Sir Humphry Davy\n");
printf("Charge: +2\n");
break;
case 57:
printf("Name: Lanthanum\n");
printf("Symbol: La\n");
printf("Atomic number: 57\n");
printf("Atomic mass: 138.905\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2\n");
printf("Discovered by: Carl Gustaf Mosander\n");
printf("Charge: +3\n");
break;
case 58:
printf("Name: Cerium\n");
printf("Symbol: Ce\n");
printf("Atomic number: 58\n");
printf("Atomic mass: 140.116\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^1\n");
printf("Discovered by: Martin Heinrich Klaproth\n");
printf("Charge: +4\n");
break;
case 59:
printf("Name: Praseodymium\n");
printf("Symbol: Pr\n");
printf("Atomic number: 59\n");
printf("Atomic mass: 140.907\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^3\n");
printf("Discovered by: Carl Auer von Welsbach\n");
printf("Charge: +3\n");
break;
case 60:
printf("Name: Neodymium\n");
printf("Symbol: Nd\n");
printf("Atomic number: 60\n");
printf("Atomic mass: 144.242\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^4\n");
printf("Discovered by: Carl Auer von Welsbach\n");
printf("Charge: +3\n");
break;
case 61:
printf("Name: Promethium\n");
printf("Symbol: Pm\n");
printf("Atomic number: 61\n");
printf("Atomic mass: 145\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^5\n");
printf("Discovered by: Marion and Albert Michel\n");
printf("Charge: +3\n");
break;
case 62:
printf("Name: Samarium\n");
printf("Symbol: Sm\n");
printf("Atomic number: 62\n");
printf("Atomic mass: 150.36\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^6\n");
printf("Discovered by: François Demarçay\n");
printf("Charge: +3\n");
break;
case 63:
printf("Name: Europium\n");
printf("Symbol: Eu\n");
printf("Atomic number: 63\n");
printf("Atomic mass: 151.964\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^7\n");
printf("Discovered by: Eugène-Anatole Demarçay\n");
printf("Charge: +3\n");
break;
case 64:
printf("Name: Gadolinium\n");
printf("Symbol: Gd\n");
printf("Atomic number: 64\n");
printf("Atomic mass: 157.25\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^7\n");
printf("Discovered by: Jean-Charles-Galimard de Marignac\n");
printf("Charge: +3\n");
break;
case 65:
printf("Name: Terbium\n");
printf("Symbol: Tb\n");
printf("Atomic number: 65\n");
printf("Atomic mass: 158.925\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^9\n");
printf("Discovered by: Carl Auer von Welsbach\n");
printf("Charge: +3\n");
break;
case 66:
printf("Name: Dysprosium\n");
printf("Symbol: Dy\n");
printf("Atomic number: 66\n");
printf("Atomic mass: 162.500\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^10\n");
printf("Discovered by: Paul-Émile Lecoq de Boisbaudran\n");
printf("Charge: +3\n");
break;
case 67:
printf("Name: Holmium\n");
printf("Symbol: Ho\n");
printf("Atomic number: 67\n");
printf("Atomic mass: 164.930\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^11\n");
printf("Discovered by: Per Teodor Cleve\n");
printf("Charge: +3\n");
break;
case 68:
printf("Name: Erbium\n");
printf("Symbol: Er\n");
printf("Atomic number: 68\n");
printf("Atomic mass: 167.259\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^12\n");
printf("Discovered by: Carl Auer von Welsbach\n");
printf("Charge: +3\n");
break;
case 69:
printf("Name: Thulium\n");
printf("Symbol: Tm\n");
printf("Atomic number: 69\n");
printf("Atomic mass: 168.934\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^13\n");
printf("Discovered by: Per Teodor Cleve\n");
printf("Charge: +3\n");
break;
case 70:
printf("Name: Ytterbium\n");
printf("Symbol: Yb\n");
printf("Atomic number: 70\n");
printf("Atomic mass: 173.04\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^14\n");
printf("Discovered by: Jean Charles Galissard de Marignac\n");
printf("Charge: +3\n");
break;
case 71:
printf("Name: Lutetium\n");
printf("Symbol: Lu\n");
printf("Atomic number: 71\n");
printf("Atomic mass: 174.966\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^1 5s^2 4f^14\n");
printf("Discovered by: Georges Urbain\n");
printf("Charge: +3\n");
break;
case 72:
printf("Name: Hafnium\n");
printf("Symbol: Hf\n");
printf("Atomic number: 72\n");
printf("Atomic mass: 178.49\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^2 5s^2\n");
printf("Discovered by: Dirk Coster and George Charles von Hevesy\n");
printf("Charge: +4\n");
break;
case 73:
printf("Name: Tantalum\n");
printf("Symbol: Ta\n");
printf("Atomic number: 73\n");
printf("Atomic mass: 180.947\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^5 5s^2\n");
printf("Discovered by: Anders Ekeberg\n");
printf("Charge: +5\n");
break;
case 74:
printf("Name: Tungsten\n");
printf("Symbol: W\n");
printf("Atomic number: 74\n");
printf("Atomic mass: 183.84\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^5 5s^2\n");
printf("Discovered by: Fausto Elhuyar and Juan José Elhuyar\n");
printf("Charge: +6\n");
break;
case 75:
printf("Name: Rhenium\n");
printf("Symbol: Re\n");
printf("Atomic number: 75\n");
printf("Atomic mass: 186.207\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^5 5s^2 4f^14\n");
printf("Discovered by: Masataka Ogawa\n");
printf("Charge: +7\n");
break;
case 76:
printf("Name: Osmium\n");
printf("Symbol: Os\n");
printf("Atomic number: 76\n");
printf("Atomic mass: 190.23\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^6 5s^2\n");
printf("Discovered by: Smithson Tennant\n");
printf("Charge: +4/+8\n");
break;
case 77:
printf("Name: Iridium\n");
printf("Symbol: Ir\n");
printf("Atomic number: 77\n");
printf("Atomic mass: 192.217\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^7 5s^2\n");
printf("Discovered by: Smithson Tennant\n");
printf("Charge: +3/+4\n");
break;
case 78:
printf("Name: Platinum\n");
printf("Symbol: Pt\n");
printf("Atomic number: 78\n");
printf("Atomic mass: 195.084\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^9 5s^1\n");
printf("Discovered by: Antonio de Ulloa\n");
printf("Charge: +2/+4\n");
break;
case 79:
printf("Name: Gold\n");
printf("Symbol: Au\n");
printf("Atomic number: 79\n");
printf("Atomic mass: 196.966\n");
printf("Electron configuration: 1s^2 2s^2 2p^6 3s^2 3p^6 4s^2 3d^10 4d^10 5s^1\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +1/+3\n");
break;
case 80:
printf("Name: Mercury\n");
printf("Symbol: Hg\n");
printf("Atomic number: 80\n");
printf("Atomic mass: 200.592\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +1/+2\n");
break;
case 81:
printf("Name: Thallium\n");
printf("Symbol: Tl\n");
printf("Atomic number: 81\n");
printf("Atomic mass: 204.38\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2 6p^1\n");
printf("Discovered by: William Crookes\n");
printf("Charge: +1/+3\n");
break;
case 82:
printf("Name: Lead\n");
printf("Symbol: Pb\n");
printf("Atomic number: 82\n");
printf("Atomic mass: 207.2\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2 6p^2\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +2/+4\n");
break;
case 83:
printf("Name: Bismuth\n");
printf("Symbol: Bi\n");
printf("Atomic number: 83\n");
printf("Atomic mass: 208.980\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2 6p^3\n");
printf("Discovered by: Known since ancient times\n");
printf("Charge: +3\n");
break;
case 84:
printf("Name: Polonium\n");
printf("Symbol: Po\n");
printf("Atomic number: 84\n");
printf("Atomic mass: 209\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2 6p^4\n");
printf("Discovered by: Marie Curie and Pierre Curie\n");
printf("Charge: +2/+4\n");
break;
case 85:
printf("Name: Astatine\n");
printf("Symbol: At\n");
printf("Atomic number: 85\n");
printf("Atomic mass: 210\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2 6p^5\n");
printf("Discovered by: Dale R. Corson, K. R. MacKenzie, and Albert Ghiorso\n");
printf("Charge: -1/+3/+5/+7\n");
break;
case 86:
printf("Name: Radon\n");
printf("Symbol: Rn\n");
printf("Atomic number: 86\n");
printf("Atomic mass: 222\n");
printf("Electron configuration: [Xe] 4f^14 5d^10 6s^2 6p^6\n");
printf("Discovered by: Friedrich Ernst Dorn\n");
printf("Charge: 0\n");
break;
case 87:
printf("Name: Francium\n");
printf("Symbol: Fr\n");
printf("Atomic number: 87\n");
printf("Atomic mass: 223\n");
printf("Electron configuration: [Rn] 7s^1\n");
printf("Discovered by: Marguerite Perey\n");
printf("Charge: +1\n");
break;
case 88:
printf("Name: Radium\n");
printf("Symbol: Ra\n");
printf("Atomic number: 88\n");
printf("Atomic mass: 226\n");
printf("Electron configuration: [Rn] 7s^2\n");
printf("Discovered by: Marie Curie and Pierre Curie\n");
printf("Charge: +2\n");
break;
case 89:
printf("Name: Actinium\n");
printf("Symbol: Ac\n");
printf("Atomic number: 89\n");
printf("Atomic mass: 227\n");
printf("Electron configuration: [Rn] 6d^1 7s^2\n");
printf("Discovered by: Friedrich Oskar Giesel\n");
printf("Charge: +3\n");
break;
case 90:
printf("Name: Thorium\n");
printf("Symbol: Th\n");
printf("Atomic number: 90\n");
printf("Atomic mass: 232.038\n");
printf("Electron configuration: [Rn] 6d^2 7s^2\n");
printf("Discovered by: Jöns Jakob Berzelius\n");
printf("Charge: +4\n");
break;
case 91:
printf("Name: Protactinium\n");
printf("Symbol: Pa\n");
printf("Atomic number: 91\n");
printf("Atomic mass: 231.035\n");
printf("Electron configuration: [Rn] 5f^2 6d^1 7s^2\n");
printf("Discovered by: Frederick Oskar Giesel\n");
printf("Charge: +5\n");
break;
case 92:
printf("Name: Uranium\n");
printf("Symbol: U\n");
printf("Atomic number: 92\n");
printf("Atomic mass: 238.028\n");
printf("Electron configuration: [Rn] 5f^3 6d^1 7s^2\n");
printf("Discovered by: Martin Heinrich Klaproth\n");
printf("Charge: +6\n");
break;
case 93:
printf("Name: Neptunium\n");
printf("Symbol: Np\n");
printf("Atomic number: 93\n");
printf("Atomic mass: 237.048\n");
printf("Electron configuration: [Rn] 5f^4 6d^1 7s^2\n");
printf("Discovered by: Albert Einstein and Otto Hahn\n");
printf("Charge: +5/+6\n");
break;
case 94:
printf("Name: Plutonium\n");
printf("Symbol: Pu\n");
printf("Atomic number: 94\n");
printf("Atomic mass: 244\n");
printf("Electron configuration: [Rn] 5f^6 6d^1 7s^2\n");
printf("Discovered by: Albert Einstein and Otto Hahn\n");
printf("Charge: +4/+5/+6\n");
break;
case 95:
printf("Name: Americium\n");
printf("Symbol: Am\n");
printf("Atomic number: 95\n");
printf("Atomic mass: 243\n");
printf("Electron configuration: [Rn] 5f^7 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Leon O. Morgan\n");
printf("Charge: +3\n");
break;
case 96:
printf("Name: Curium\n");
printf("Symbol: Cm\n");
printf("Atomic number: 96\n");
printf("Atomic mass: 247\n");
printf("Electron configuration: [Rn] 5f^7 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 97:
printf("Name: Berkelium\n");
printf("Symbol: Bk\n");
printf("Atomic number: 97\n");
printf("Atomic mass: 247\n");
printf("Electron configuration: [Rn] 5f^9 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 98:
printf("Name: Californium\n");
printf("Symbol: Cf\n");
printf("Atomic number: 98\n");
printf("Atomic mass: 251\n");
printf("Electron configuration: [Rn] 5f^10 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 99:
printf("Name: Einsteinium\n");
printf("Symbol: Es\n");
printf("Atomic number: 99\n");
printf("Atomic mass: 252\n");
printf("Electron configuration: [Rn] 5f^11 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 100:
printf("Name: Fermium\n");
printf("Symbol: Fm\n");
printf("Atomic number: 100\n");
printf("Atomic mass: 257\n");
printf("Electron configuration: [Rn] 5f^12 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 101:
printf("Name: Mendelevium\n");
printf("Symbol: Md\n");
printf("Atomic number: 101\n");
printf("Atomic mass: 258\n");
printf("Electron configuration: [Rn] 5f^13 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 102:
printf("Name: Nobelium\n");
printf("Symbol: No\n");
printf("Atomic number: 102\n");
printf("Atomic mass: 259\n");
printf("Electron configuration: [Rn] 5f^14 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +2/+3\n");
break;
case 103:
printf("Name: Lawrencium\n");
printf("Symbol: Lr\n");
printf("Atomic number: 103\n");
printf("Atomic mass: 266\n");
printf("Electron configuration: [Rn] 5f^14 6d^1 7s^2\n");
printf("Discovered by: Albert Ghiorso, Ralph A. James, and Albert M. P. W. Morgan\n");
printf("Charge: +3\n");
break;
case 104:
printf("Name: Rutherfordium\n");
printf("Symbol: Rf\n");
printf("Atomic number: 104\n");
printf("Atomic mass: 267\n");
printf("Electron configuration: [Rn] 5f^14 6d^2 7s^2\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: +4\n");
break;
case 105:
printf("Name: Dubnium\n");
printf("Symbol: Db\n");
printf("Atomic number: 105\n");
printf("Atomic mass: 270\n");
printf("Electron configuration: [Rn] 5f^14 6d^3 7s^2\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: +5\n");
break;
case 106:
printf("Name: Seaborgium\n");
printf("Symbol: Sg\n");
printf("Atomic number: 106\n");
printf("Atomic mass: 271\n");
printf("Electron configuration: [Rn] 5f^14 6d^4 7s^2\n");
printf("Discovered by: Lawrence Berkeley National Laboratory\n");
printf("Charge: +6\n");
break;
case 107:
printf("Name: Bohrium\n");
printf("Symbol: Bh\n");
printf("Atomic number: 107\n");
printf("Atomic mass: 270\n");
printf("Electron configuration: [Rn] 5f^14 6d^5 7s^2\n");
printf("Discovered by: GSI Helmholtz Centre for Heavy Ion Research\n");
printf("Charge: +7\n");
break;
case 108:
printf("Name: Hassium\n");
printf("Symbol: Hs\n");
printf("Atomic number: 108\n");
printf("Atomic mass: 277\n");
printf("Electron configuration: [Rn] 5f^14 6d^6 7s^2\n");
printf("Discovered by: GSI Helmholtz Centre for Heavy Ion Research\n");
printf("Charge: +8\n");
break;
case 109:
printf("Name: Meitnerium\n");
printf("Symbol: Mt\n");
printf("Atomic number: 109\n");
printf("Atomic mass: 276\n");
printf("Electron configuration: [Rn] 5f^14 6d^7 7s^2\n");
printf("Discovered by: GSI Helmholtz Centre for Heavy Ion Research\n");
printf("Charge: +9\n");
break;
case 110:
printf("Name: Darmstadtium\n");
printf("Symbol: Ds\n");
printf("Atomic number: 110\n");
printf("Atomic mass: 281\n");
printf("Electron configuration: [Rn] 5f^14 6d^9 7s^2\n");
printf("Discovered by: GSI Helmholtz Centre for Heavy Ion Research\n");
printf("Charge: +10\n");
break;
case 111:
printf("Name: Roentgenium\n");
printf("Symbol: Rg\n");
printf("Atomic number: 111\n");
printf("Atomic mass: 282\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2\n");
printf("Discovered by: GSI Helmholtz Centre for Heavy Ion Research\n");
printf("Charge: +11\n");
break;
case 112:
printf("Name: Copernicium\n");
printf("Symbol: Cn\n");
printf("Atomic number: 112\n");
printf("Atomic mass: 285\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^1\n");
printf("Discovered by: GSI Helmholtz Centre for Heavy Ion Research\n");
printf("Charge: +12\n");
break;
case 113:
printf("Name: Nihonium\n");
printf("Symbol: Nh\n");
printf("Atomic number: 113\n");
printf("Atomic mass: 286\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^1\n");
printf("Discovered by: RIKEN\n");
printf("Charge: +13\n");
break;
case 114:
printf("Name: Flerovium\n");
printf("Symbol: Fl\n");
printf("Atomic number: 114\n");
printf("Atomic mass: 289\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^2\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: +14\n");
break;
case 115:
printf("Name: Moscovium\n");
printf("Symbol: Mc\n");
printf("Atomic number: 115\n");
printf("Atomic mass: 290\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^3\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: +15\n");
break;
case 116:
printf("Name: Livermorium\n");
printf("Symbol: Lv\n");
printf("Atomic number: 116\n");
printf("Atomic mass: 293\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^4\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: +16\n");
break;
case 117:
printf("Name: Tennessine\n");
printf("Symbol: Ts\n");
printf("Atomic number: 117\n");
printf("Atomic mass: 294\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^5\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: -1/+1/+3/+5/+7\n");
break;
case 118:
printf("Name: Oganesson\n");
printf("Symbol: Og\n");
printf("Atomic number: 118\n");
printf("Atomic mass: 294\n");
printf("Electron configuration: [Rn] 5f^14 6d^10 7s^2 7p^6\n");
printf("Discovered by: Joint Institute for Nuclear Research\n");
printf("Charge: 0\n");
break;
// ...
// Repeat for all elements up to atomic number 118
default:
printf("Element not found.\n");
break;
}
}
int main()
{
int n;
int m;
int a;
printf("Welcome to the Modern Periodic Table\n\n");
printf("> Enter 1 to know about an element\n\n");
printf("> Enter 2 to close the periodic table\n\n");
printf("ENTER\n");
scanf("%d", &n);
if (n == 1)
{
printf("Press 3 to search element by atomic number\n");
printf("ENTER\n");
scanf("%d", &m);
if (m == 3)
{
printf("Enter the atomic number of the element to be searched:\n");
scanf("%d", &a);
printElementDetails(a);
}
}
else if (n == 2)
{
printf("Do you want to exit? (yes/no)\n");
printf("Press 1 for Yes\n");
printf("Press 2 for No\n");
printf("ENTER\n");
int Exit;
scanf("%d", &Exit);
if (Exit == 1)
{
printf("Are you sure, You want to close the periodic table? (Yes/No)\n");
printf("Press 1 for Yes\n");
printf("Press 2 for No\n");
printf("ENTER\n");
scanf("%d", &Exit);
if (Exit == 1)
{
printf("The periodic table has closed.\n");
}
else
{
printf("The periodic table has not closed and you can continue to learn more about elements.\n\n");
printf("Enter the Atomic number of the element to be searched:\n\n");
scanf("%d", &a);
printElementDetails(a);
}
}
}
return 0;
}
49)Phone book...
#include <stdio.h>
int main() {
char name[50], address[50];
int age, phone, dob;
printf("Welcome to Phone Book\n\n");
int choice;
printf("MENU\n");
printf("Press 1 to add a contact\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1) {
int numContacts;
printf("Enter the number of contacts to be added: ");
scanf("%d", &numContacts);
if (numContacts == 1) {
printf("--------------------\n");
printf("Name: ");
scanf("%s", name);
printf("Age: ");
scanf("%d", &age);
printf("Phone Number: ");
scanf("%d", &phone);
printf("Address: ");
scanf("%s", address);
printf("Date of Birth (DDMMYYYY): ");
scanf("%d", &dob);
printf("--------------------\n");
}
printf("Press 2 to view the entered contact\n");
printf("Press 3 to exit the phone book\n");
int subChoice;
printf("Enter your choice: ");
scanf("%d", &subChoice);
if (subChoice == 2) {
printf("--------------------\n");
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Phone Number: %d\n", phone);
printf("Address: %s\n", address);
printf("Date of Birth: %d\n", dob);
printf("--------------------\n");
} else if (subChoice == 3) {
int exitChoice;
printf("Are you sure you want to exit the phone book?\n");
printf("Press 1 to exit\n");
printf("Press 2 to continue\n");
printf("Enter your choice: ");
scanf("%d", &exitChoice);
if (exitChoice == 1) {
printf("The phone book has closed.\n");
printf("Have a good day!\n");
} else if (exitChoice == 2) {
printf("The phone book has not closed.\n");
printf("You can continue.\n");
}
}
} else {
printf("Invalid choice.\n");
}
return 0;
}
50)PAY THE BILL JUST NOW
#include<stdio.h>
int main()
{
char name[50];
int phone_number;
int customer_id;
int body_soap;
int hair_cream;
int hair_spray;
int body_spray;
int sugar;
int tea;
int coffee;
int rice;
int wheat;
int pepsi;
int sprite;
int coke;
int mojitos;
int fanta;
int total;
int cosmetics_total;
int grocery_total;
int beverage_total;
// Customer Details
printf("-----------------\n");
printf("BILLING SYSTEM\n");
printf("-----------------\n");
printf("CUSTOMER DETAILS\n\n");
printf("Customer Name: ");
scanf("%s", name); // No need for & before name since it's an array
printf("Customer Number: ");
scanf("%d", &phone_number);
printf("Customer ID: ");
scanf("%d", &customer_id);
// Getting the quantity of each item
printf("\nEnter quantity for cosmetics:\n");
printf("Body Soap: ");
scanf("%d", &body_soap);
printf("Hair Cream: ");
scanf("%d", &hair_cream);
printf("Hair Spray: ");
scanf("%d", &hair_spray);
printf("Body Spray: ");
scanf("%d", &body_spray);
printf("\nEnter quantity for grocery items:\n");
printf("Sugar: ");
scanf("%d", &sugar);
printf("Tea: ");
scanf("%d", &tea);
printf("Coffee: ");
scanf("%d", &coffee);
printf("Rice: ");
scanf("%d", &rice);
printf("Wheat: ");
scanf("%d", &wheat);
printf("\nEnter quantity for beverages:\n");
printf("Pepsi: ");
scanf("%d", &pepsi);
printf("Sprite: ");
scanf("%d", &sprite);
printf("Coke: ");
scanf("%d", &coke);
printf("Mojitos: ");
scanf("%d", &mojitos);
printf("Fanta: ");
scanf("%d", &fanta);
// Calculating totals for each category
cosmetics_total = body_soap * 40 + hair_cream * 50 + hair_spray * 60 + body_spray * 70;
grocery_total = sugar * 30 + tea * 20 + coffee * 25 + rice * 40 + wheat * 35;
beverage_total = pepsi * 20 + sprite * 20 + coke * 25 + mojitos * 30 + fanta * 20;
// Calculating grand total
total = cosmetics_total + grocery_total + beverage_total;
// Displaying the bill
printf("\n\n-----------------\n");
printf("BILL SUMMARY\n");
printf("-----------------\n");
printf("Cosmetics Total: %d\n", cosmetics_total);
printf("Grocery Total: %d\n", grocery_total);
printf("Beverage Total: %d\n", beverage_total);
printf("Grand Total: %d\n", total);
return 0;
}
51)Game of luck!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rules();
int round1();
int main()
{
rules();
printf("\n\n");
round1();
return 0;
}
int rules()
{
printf("Welcome to the Game of Luck!\n");
printf("Rules:\n");
printf("1. You will start with a certain amount of money.\n");
printf("2. You will place a bet and guess a number between 1 and 10.\n");
printf("3. If you guess correctly, you win 10 times your bet amount.\n");
printf("4. If you guess incorrectly, you lose your bet amount.\n");
printf("5. The game continues until you decide to stop or run out of money.\n");
return 0;
}
int round1()
{
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("\n\n");
int deposit1;
printf("Enter the amount you want to deposit for the game: ");
scanf("%d", &deposit1);
printf("\n\n");
printf("Your current balance is $%d\n", deposit1);
printf("\n\n");
int bet1;
printf("Enter the amount you want to bet: $");
scanf("%d", &bet1);
printf("\n\n");
while (bet1 > deposit1)
{
printf("Money Exceeds,\n");
printf("Enter Again : $");
scanf("%d", &bet1);
}
printf("\n\n");
srand(time(0)); // Seed for random number generation
int computer1 = rand() % 10 + 1;
int guess1;
printf("Guess the number from 1 to 10: ");
scanf("%d", &guess1);
printf("\n\n");
while (guess1 > 10 || guess1 < 1)
{
printf("Number out of range,\n");
printf("Enter Again : ");
scanf("%d", &guess1);
}
printf("\n\n");
if (guess1 == computer1)
{
printf("You Won $%d!\n", bet1 * 10);
printf("\n\n");
int new_won = deposit1 + (bet1 * 10);
printf("Your new balance is $%d\n", new_won);
deposit1 = new_won;
}
else
{
printf("You Lost $%d\n", bet1);
printf("\n\n");
int new_lost = deposit1 - bet1;
printf("Your new balance is $%d\n", new_lost);
if (new_lost == 0)
{
printf("Sir, You have no money left. Better luck next time.\n");
printf("Have a nice day.\n");
return 0;
}
deposit1 = new_lost;
}
int decision;
printf("Do you want to continue?\n");
printf("Press 1 for Yes\n");
printf("Press 2 for No\n");
printf("Your choice: ");
scanf("%d", &decision);
printf("\n\n");
if (decision == 1)
{
return round1();
}
else
{
printf("Thank you for playing! Your final balance is $%d\n", deposit1);
printf("Have a nice day!\n");
}
return 0;
}
52)Chess game text base.py
class ChessGame:
def __init__(self):
self.board = self.reset_board()
self.current_player = "white"
def reset_board(self):
#Initialize an 8x8 board with pieces in starting positions
board = []
for i in range(8):
row = []
for j in range(8):
if i == 1:
row.append("bp") # Black pawn
elif i == 6:
row.append("wp") # White pawn
elif i == 0:
if j in [0, 7]:
row.append("br") # Black rook
elif j in [1, 6]:
row.append("bn") # Black knight
elif j in [2, 5]:
row.append("bb") # Black bishop
elif j == 3:
row.append("bq") # Black queen
elif j == 4:
row.append("bk") # Black king
elif i == 7:
if j in [0, 7]:
row.append("wr") # White rook
elif j in [1, 6]:
row.append("wn") # White knight
elif j in [2, 5]:
row.append("wb") # White bishop
elif j == 3:
row.append("wq") # White queen
elif j == 4:
row.append("wk") # White king
else:
row.append("--") # Empty square
board.append(row)
return board
def print_board(self):
print(" a b c d e f g h")
for i in range(8):
print(i+1, end=" ")
for j in range(8):
print(self.board[i][j], end=" ")
print()
def make_move(self, start, end):
start_x = ord(start[0]) - 97
start_y = int(start[1]) - 1
end_x = ord(end[0]) - 97
end_y = int(end[1]) - 1
piece = self.board[start_y][start_x]
self.board[start_y][start_x] = "--"
self.board[end_y][end_x] = piece
self.current_player = "black" if self.current_player == "white" else "white"
def play_game(self):
while True:
self.print_board()
print("Player", self.current_player, "turn")
start = input("Enter start position (e.g., a2): ")
end = input("Enter end position (e.g., a3): ")
self.make_move(start, end)
game = ChessGame()
game.play_game()
53)ATM for you...
#include <stdio.h>
int main()
{
char card;
int pin;
int balance = 0;
int amount;
printf("Welcome to the ATM\n\n");
printf("Please insert your card (k/s/i): ");
scanf(" %c", &card);
switch (card)
{
case 'k':
pin = 1234;
balance = 50000;
break;
case 's':
pin = 5678;
balance = 100000;
break;
case 'i':
pin = 9123;
balance = 60000;
break;
default:
printf("Invalid card\n");
return 1;
}
printf("Hello Krishna\n\n");
printf("> Press 1 to withdraw money\n");
printf("> Press 2 to deposit money\n");
printf("> Press 3 to check balance\n");
int choice;
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter your 4-digit pin: ");
int enteredPin;
scanf("%d", &enteredPin);
if (enteredPin == pin)
{
printf("Enter the amount to withdraw: ");
scanf("%d", &amount);
if (amount > balance)
{
printf("Insufficient balance\n");
}
else
{
balance -= amount;
printf("Collect the money\n");
printf("Your updated balance is: %d\n", balance);
}
}
else
{
printf("Incorrect pin\n");
printf("Your request has been blocked\n");
}
break;
case 2:
printf("Enter your 4-digit pin: ");
int enteredPin2;
scanf("%d", &enteredPin2);
if (enteredPin2 == pin)
{
printf("Enter the amount to deposit: ");
scanf("%d", &amount);
balance += amount;
printf("Your updated balance is: %d\n", balance);
}
else
{
printf("Incorrect pin\n");
printf("Your request has been blocked\n");
}
break;
case 3:
printf("Your current balance is: %d\n", balance);
break;
default:
printf("Invalid choice\n");
break;
}
return 0;
}
54)library for you...
#include <stdio.h>
#include <string.h>
// Define a struct to represent a book
struct Book {
char name[50];
char author[50];
int pages;
int price;
int status; // 0: available, 1: borrowed
};
// Function prototypes
void displayMenu();
void addBook(struct Book books[], int *bookCount);
void displayBooks(const struct Book books[], int bookCount);
void searchBook(const struct Book books[], int bookCount);
int main() {
struct Book books[100]; // Database for storing books
int bookCount = 0;
int choice;
while (1) {
displayMenu();
printf("Enter your choice: ");
scanf("%d", &choice);
printf("\n");
switch (choice) {
case 1:
addBook(books, &bookCount);
break;
case 2:
displayBooks(books, bookCount);
break;
case 3:
searchBook(books, bookCount);
break;
case 4:
printf("The Library is closed.\nThank you for visiting.\nHave a nice day!\n\n");
return 0;
default:
printf("Invalid choice. Please try again.\n\n");
break;
}
}
return 0;
}
// Function to display the main menu
void displayMenu() {
printf("-------- Main Menu --------\n");
printf("1. Add Books\n");
printf("2. Display Book Information\n");
printf("3. Search Books (Book Status)\n");
printf("4. Exit\n\n");
}
// Function to add a book to the library
void addBook(struct Book books[], int *bookCount) {
printf("You can add book information.\n\n");
struct Book newBook;
printf("Enter book name: ");
getchar(); // To consume the leftover newline character
fgets(newBook.name, 50, stdin);
newBook.name[strcspn(newBook.name, "\n")] = 0; // Remove newline character
printf("Enter author name: ");
fgets(newBook.author, 50, stdin);
newBook.author[strcspn(newBook.author, "\n")] = 0; // Remove newline character
printf("Enter number of pages: ");
scanf("%d", &newBook.pages);
printf("Enter price: ");
scanf("%d", &newBook.price);
newBook.status = 0; // Book is available by default
books[*bookCount] = newBook;
(*bookCount)++;
printf("Book added successfully!\n\n");
}
// Function to display information about all books
void displayBooks(const struct Book books[], int bookCount) {
if (bookCount == 0) {
printf("No books in the library.\n\n");
return;
}
for (int i = 0; i < bookCount; i++) {
printf("Book #%d:\n", i + 1);
printf("Name: %s\n", books[i].name);
printf("Author: %s\n", books[i].author);
printf("Pages: %d\n", books[i].pages);
printf("Price: %d\n", books[i].price);
printf("Status: %s\n\n", books[i].status == 0 ? "Available" : "Borrowed");
}
}
// Function to search for a book by name
void searchBook(const struct Book books[], int bookCount) {
if (bookCount == 0) {
printf("No books in the library to search.\n\n");
return;
}
char searchName[50];
printf("Enter the book name to search: ");
getchar(); // To consume the leftover newline character
fgets(searchName, 50, stdin);
searchName[strcspn(searchName, "\n")] = 0; // Remove newline character
int found = 0;
for (int i = 0; i < bookCount; i++) {
if (strcmp(books[i].name, searchName) == 0) {
printf("Book found!\n");
printf("Name: %s\n", books[i].name);
printf("Author: %s\n", books[i].author);
printf("Pages: %d\n", books[i].pages);
printf("Price: %d\n", books[i].price);
printf("Status: %s\n\n", books[i].status == 0 ? "Available" : "Borrowed");
found = 1;
break;
}
}
if (!found) {
printf("Book not found.\n\n");
}
}
*)Trial...
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Set Seaborn style
sns.set(style="whitegrid")
# Figure for the barplot
plt.figure(figsize=(10, 6))
# Barplot for top songs by popularity
sns.barplot(x="name", y="popularity", data=top_songs) # Assuming `top_songs` is a DataFrame
# Sorting the DataFrame `tracks` by least popular songs and displaying the top 10
least_popular = tracks.sort_values(by="popularity", ascending=True).head(10)
print(least_popular)
# Convert release dates to datetime
tracks['dates'] = pd.to_datetime(tracks['release_dates'], format='%Y-%m-%d', errors='coerce')
tracks['dates'] = tracks['dates'].fillna(pd.to_datetime('2020-01-01'))
# Display artist at index 18
print(tracks.loc[18, ['artists']])
# Convert duration from milliseconds to seconds
tracks['duration'] = tracks['duration_ms'].apply(lambda x: round(x / 1000))
# Display the first few rows of the DataFrame
tracks.head()
# Drop the 'duration_ms' column
tracks.drop('duration_ms', axis=1, inplace=True)
# Correlation matrix
cm = tracks.corr(method='pearson')
# Plot the heatmap of the correlation matrix
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, cmap='coolwarm')
# Random sample of the DataFrame
sampled_tracks = tracks.sample(int(0.004 * len(tracks)))
print(len(sampled_tracks))
# Scatter plot of popularity vs duration
plt.figure(figsize=(10, 6))
sns.regplot(x='popularity', y='duration', data=sampled_tracks)
plt.xlabel('Popularity')
plt.ylabel('Duration')
plt.title('Popularity vs Duration')
# Histogram of the number of songs per year
sns.displot(tracks['dates'].dt.year, discrete=True, aspect=2, height=5, kind='hist').set(title='Number of Songs per Year')
# Bar plot of total duration of songs by year
total_duration = tracks.groupby(tracks['dates'].dt.year)['duration'].sum()
fig_dims = (18, 7)
fig, ax = plt.subplots(figsize=fig_dims)
sns.barplot(x=total_duration.index, y=total_duration.values, ax=ax)
plt.title("Total Duration of Songs by Year")
# Pairplot example (from the Seaborn penguins dataset)
penguins = sns.load_dataset("penguins")
sns.pairplot(penguins, hue='species')
55)Snake game.py
import tkinter
import random
ROWS = 25
COLS = 25
TILE_SIZE = 25
WINDOW_WIDTH = TILE_SIZE * ROWS
WINDOW_HEIGHT = TILE_SIZE * COLS
class Tile:
def __init__(self, x, y):
self.x = x
self.y = y
# Game window
window = tkinter.Tk()
window.title("Snake")
window.resizable(False, False)
canvas = tkinter.Canvas(window, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg="black", borderwidth=0, highlightthickness=0)
canvas.pack()
window.update()
# Center the window
window_width = window.winfo_width()
window_height = window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
window_x = int((screen_width/2) - (window_width/2))
window_y = int((screen_height/2) - (window_height/2))
window.geometry(f"{window_width}x{window_height}+{window_x}+{window_y}")
# Initialize game
snake = Tile(5 * TILE_SIZE, 5 * TILE_SIZE) # Single tile snake's head
food = Tile(10 * TILE_SIZE, 10 * TILE_SIZE)
snake_body = [] # Multiple snake tiles
velocityX = 0
velocityY = 0
game_over = False
score = 0
def change_direction(e): # e = event
global velocityX, velocityY, game_over
if game_over:
return
if e.keysym == "Up" and velocityY != 1:
velocityX = 0
velocityY = -1
elif e.keysym == "Down" and velocityY != -1:
velocityX = 0
velocityY = 1
elif e.keysym == "Left" and velocityX != 1:
velocityX = -1
velocityY = 0
elif e.keysym == "Right" and velocityX != -1:
velocityX = 1
velocityY = 0
def move():
global snake, food, snake_body, game_over, score
if game_over:
return
# Collision with walls
if snake.x < 0 or snake.x >= WINDOW_WIDTH or snake.y < 0 or snake.y >= WINDOW_HEIGHT:
game_over = True
return
# Collision with itself
for tile in snake_body:
if snake.x == tile.x and snake.y == tile.y:
game_over = True
return
# Collision with food
if snake.x == food.x and snake.y == food.y:
snake_body.append(Tile(snake.x, snake.y))
food.x = random.randint(0, ROWS - 1) * TILE_SIZE
food.y = random.randint(0, COLS - 1) * TILE_SIZE
score += 1
# Update snake body
if snake_body:
for i in range(len(snake_body) - 1, 0, -1):
snake_body[i].x = snake_body[i - 1].x
snake_body[i].y = snake_body[i - 1].y
snake_body[0].x = snake.x
snake_body[0].y = snake.y
snake.x += velocityX * TILE_SIZE
snake.y += velocityY * TILE_SIZE
def draw():
global snake, food, snake_body, game_over, score
move()
canvas.delete("all")
# Draw food
canvas.create_rectangle(food.x, food.y, food.x + TILE_SIZE, food.y + TILE_SIZE, fill="red")
# Draw snake
canvas.create_rectangle(snake.x, snake.y, snake.x + TILE_SIZE, snake.y + TILE_SIZE, fill="lime green")
for tile in snake_body:
canvas.create_rectangle(tile.x, tile.y, tile.x + TILE_SIZE, tile.y + TILE_SIZE, fill="lime green")
# Display game over or score
if game_over:
canvas.create_text(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, text=f"Game Over! Score: {score}", font=("Arial", 20), fill="white")
else:
canvas.create_text(WINDOW_WIDTH / 2, 20, text=f"Score: {score}", font=("Arial", 20), fill="white")
window.after(100, draw) # 100 ms = 1/10 second, 10 frames per second
draw()
window.bind("<KeyRelease>", change_direction)
window.mainloop()
56)Flappy bird...
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up display
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("PFlappy Bird")
# Set up the clock for controlling the frame rate
clock = pygame.time.Clock()
# Load images
bird_img = pygame.image.load("flappy_bird.png")
pipe_img = pygame.image.load("pipe1.png")
bg_img = pygame.image.load("flappy bridge.png")
# Define colors
WHITE = (255, 255, 255)
# Game constants
GRAVITY = 0.25
BIRD_FLAP = -5
# Bird properties
bird_x = 50
bird_y = SCREEN_HEIGHT // 2
bird_y_speed = 0
# Pipe properties
pipe_width = pipe_img.get_width()
pipe_gap = 150
pipe_speed = 3
pipes = []
# Score
score = 0
font = pygame.font.Font(None, 36)
def draw_bird(screen, x, y):
screen.blit(bird_img, (x, y))
def draw_pipes(screen, pipes):
for pipe in pipes:
screen.blit(pipe_img, (pipe['x'], pipe['y']))
screen.blit(pygame.transform.flip(pipe_img, False, True), (pipe['x'], pipe['y'] - pipe_gap - pipe_img.get_height()))
def create_pipe():
y = random.randint(200, SCREEN_HEIGHT - 200)
pipe = {'x': SCREEN_WIDTH, 'y': y}
return pipe
# Main game loop
running = True
while running:
screen.blit(bg_img, (0, 0))
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_y_speed = BIRD_FLAP
# Update bird position
bird_y_speed += GRAVITY
bird_y += bird_y_speed
# Add new pipes
if len(pipes) == 0 or pipes[-1]['x'] < SCREEN_WIDTH - 200:
pipes.append(create_pipe())
# Update pipe positions
pipes = [{'x': p['x'] - pipe_speed, 'y': p['y']} for p in pipes if p['x'] > -pipe_width]
# Check for collisions
for pipe in pipes:
if bird_x + bird_img.get_width() > pipe['x'] and bird_x < pipe['x'] + pipe_width:
if bird_y < pipe['y'] - pipe_gap or bird_y + bird_img.get_height() > pipe['y']:
running = False
# Check if the bird hits the ground or flies too high
if bird_y > SCREEN_HEIGHT - bird_img.get_height() or bird_y < 0:
running = False
# Draw bird and pipes
draw_bird(screen, bird_x, bird_y)
draw_pipes(screen, pipes)
# Update score
score += 1
# Display score
score_text = font.render(str(score), True, WHITE)
screen.blit(score_text, (10, 10))
pygame.display.update()
clock.tick(60)
pygame.quit()
57)Dino game
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dino Game</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
background-color: #f7f7f7;
}
.game-container {
width: 100%;
height: 100vh;
position: relative;
overflow: hidden;
background-color: #fff;
border: 2px solid red;
}
.ground {
position: absolute;
bottom: 0;
width: 100%;
height: 20px;
background-color: #aaa;
}
.dino {
width: 50px;
height: 50px;
background-image: url('dino.png');
background-size: cover;
position: absolute;
bottom: 20px;
left: 50px;
transition: bottom 0.3s;
}
.obstacle {
width: 20px;
height: 50px;
background-image: url('cactus.png');
background-size: cover;
position: absolute;
bottom: 20px;
right: 0;
animation: moveObstacle 2s linear infinite;
}
@keyframes moveObstacle {
from { right: -20px; }
to { right: 100%; }
}
.score {
position: absolute;
top: 10px;
left: 10px;
font-size: 20px;
font-weight: bold;
}
.game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 36px;
font-weight: bold;
color: red;
display: none;
}
.background {
position: absolute;
width: 200%;
height: 100vh;
background-image: url('background.jpg');
background-size: cover;
animation: moveBackground 4s linear infinite;
}
@keyframes moveBackground {
from { left: 0; }
to { left: -100%; }
}
.jump-button {
position: absolute;
bottom: 40px;
right: 20px;
width: 100px;
height: 50px;
background-color: #f90;
border: 2px solid #000;
border-radius: 10px;
text-align: center;
line-height: 50px;
font-size: 20px;
font-weight: bold;
color: #fff;
cursor: pointer;
}
.jump-button:hover {
background-color: #fb3;
}
</style>
</head>
<body>
<div class="game-container">
<div class="background"></div>
<div class="score" id="score">Score: 0</div>
<div class="dino" id="dino"></div>
<div class="obstacle" id="obstacle"></div>
<div class="ground"></div>
<div class="game-over" id="game-over">Game Over!</div>
<div class="jump-button" id="jump-button">JUMP</div>
</div>
<script>
let score = 0;
let gameSpeed = 2000;
let isGameOver = false;
let isJumping = false; // Track if the dino is in the air
// Add an event listener for the spacebar key to trigger the jump
document.addEventListener('keydown', function(event) {
if (event.key === ' ' && !isGameOver && !isJumping) {
jump();
}
});
// Add an event listener for the jump button to trigger the jump
document.getElementById('jump-button').addEventListener('click', function() {
if (!isGameOver && !isJumping) {
jump();
}
});
// Function to make the dinosaur jump
function jump() {
let dino = document.getElementById('dino');
isJumping = true;
dino.style.bottom = '150px'; // Increased jump height
// Remove the jump after the duration
setTimeout(function() {
dino.style.bottom = '20px';
isJumping = false;
}, 600); // Increased jump duration
}
// Check if the dinosaur is alive and hasn't hit an obstacle
let isAlive = setInterval(function() {
// Get the dinosaur and obstacle elements
let dino = document.getElementById('dino');
let obstacle = document.getElementById('obstacle');
let gameOverScreen = document.getElementById('game-over');
// Get the current position of the dinosaur and the obstacle
let dinoBottom = parseInt(window.getComputedStyle(dino).getPropertyValue('bottom'));
let obstacleRight = parseInt(window.getComputedStyle(obstacle).getPropertyValue('right'));
// Check for collision
if (obstacleRight > 50 && obstacleRight < 100 && dinoBottom < 70) {
// If a collision is detected, stop the game
isGameOver = true;
gameOverScreen.style.display = 'block';
clearInterval(isAlive);
clearInterval(scoreInterval);
setTimeout(function() {
location.reload(); // Reload the page to restart the game
}, 3000); // Give a 3-second delay before restarting
}
}, 10);
// Increase the speed of the obstacles over time
let speedInterval = setInterval(function() {
let obstacle = document.getElementById('obstacle');
gameSpeed -= 100;
obstacle.style.animationDuration = (gameSpeed / 1000) + 's';
}, 10000);
// Update score over time
let scoreInterval = setInterval(function() {
if (!isGameOver) {
score++;
document.getElementById('score').textContent = 'Score: ' + score;
}
}, 100);
</script>
</body>
</html>
58)Doodle game...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doodle Game</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
background: #87CEEB;
}
canvas {
display: block;
margin: 0 auto;
background: #f0f0f0;
border: 1px solid #000;
}
#startScreen, #gameOverScreen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-size: cover;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 24px;
cursor: pointer;
display: none;
}
#startScreen {
background-image: url('dino/background.webp'); /* Replace with your start screen background image */
display: flex;
}
#gameOverScreen {
background-image: url('dino/background.webp'); /* Replace with your end screen background image */
}
#restartButton {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="startScreen">Click to Start Game</div>
<canvas id="gameCanvas"></canvas>
<div id="gameOverScreen">
<div>
<p>Game Over</p>
<button id="restartButton">Restart</button>
</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const startScreen = document.getElementById('startScreen');
const gameOverScreen = document.getElementById('gameOverScreen');
const restartButton = document.getElementById('restartButton');
canvas.width = 400;
canvas.height = 600;
let player, platforms, obstacles, score, gameStarted, obstaclesStarted, springBoostActive, gameOver;
function initializeGame() {
player = {
x: 200,
y: 500,
width: 30,
height: 30,
gravity: 0.8,
jumpPower: -15,
dy: -15, // Start with an initial jump
grounded: false,
color: 'green'
};
platforms = [];
obstacles = [];
score = 0;
gameStarted = false;
obstaclesStarted = false;
springBoostActive = false;
gameOver = false;
// Create initial platforms
for (let i = 0; i < 5; i++) {
let platWidth = 100;
let platHeight = 10;
let platX = Math.random() * (canvas.width - platWidth);
let platY = i * 120;
let type = (Math.random() < 0.1) ? 'spring' : 'normal';
platforms.push(new Platform(platX, platY, platWidth, platHeight, type));
}
}
// Platform Constructor
function Platform(x, y, width, height, type = 'normal') {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = type === 'spring' ? 'yellow' : 'brown';
this.type = type; // 'normal', 'spring'
}
// Obstacle Constructor
function Obstacle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = 'red';
}
function startGame() {
gameStarted = true;
startScreen.style.display = 'none';
// Start generating obstacles immediately
obstaclesStarted = true;
generateObstacles();
update();
}
function generateObstacles() {
if (obstaclesStarted && !gameOver) {
const obstacleWidth = Math.random() * 30 + 10;
const obstacleX = Math.random() * (canvas.width - obstacleWidth);
obstacles.push(new Obstacle(obstacleX, -obstacleWidth, obstacleWidth, obstacleWidth));
setTimeout(generateObstacles, Math.random() * 2000 + 1000);
}
}
// Handle player movement
function updatePlayer() {
player.y += player.dy;
player.dy += player.gravity;
if (player.y + player.height > canvas.height) {
triggerGameOver();
}
if (player.y < canvas.height / 2 && player.dy < 0) {
platforms.forEach(platform => {
platform.y -= player.dy;
});
obstacles.forEach(obstacle => {
obstacle.y -= player.dy;
});
score++;
}
// Wrap player around screen horizontally
if (player.x < 0) player.x = canvas.width;
if (player.x > canvas.width) player.x = 0;
}
// Handle platform and obstacle collisions
function handleCollisions() {
platforms.forEach(platform => {
if (player.x < platform.x + platform.width &&
player.x + player.width > platform.x &&
player.y + player.height < platform.y + platform.height &&
player.y + player.height + player.dy >= platform.y) {
player.grounded = true;
if (platform.type === 'spring') {
player.dy = player.jumpPower * 1.5; // Boost the jump
springBoostActive = true;
setTimeout(() => springBoostActive = false, 1000);
} else {
player.dy = player.jumpPower;
}
}
});
obstacles.forEach(obstacle => {
if (player.x < obstacle.x + obstacle.width &&
player.x + player.width > obstacle.x &&
player.y < obstacle.y + obstacle.height &&
player.y + player.height > obstacle.y) {
triggerGameOver();
}
});
// Loop obstacles back to the top when they exit the screen
obstacles.forEach(obstacle => {
if (obstacle.y > canvas.height) {
obstacle.y = -obstacle.height;
obstacle.x = Math.random() * (canvas.width - obstacle.width);
}
});
}
function triggerGameOver() {
gameOver = true;
gameOverScreen.style.display = 'flex';
}
// Draw everything on canvas
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
platforms.forEach(platform => {
ctx.fillStyle = platform.color;
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
});
obstacles.forEach(obstacle => {
ctx.fillStyle = obstacle.color;
ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
});
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Score: ' + score, 10, 30);
if (springBoostActive) {
ctx.fillStyle = 'red';
ctx.fillText('Spring Boost!', 250, 30);
}
}
// Update the game state
function update() {
if (gameStarted && !gameOver) {
updatePlayer();
handleCollisions();
draw();
requestAnimationFrame(update);
}
}
// Handle user input
document.addEventListener('keydown', (e) => {
if (e.code === 'ArrowLeft') {
player.x -= 20;
}
if (e.code === 'ArrowRight') {
player.x += 20;
}
if (e.code === 'Space' && player.grounded) {
player.dy = player.jumpPower;
player.grounded = false;
}
});
// Restart the game
restartButton.addEventListener('click', () => {
gameOverScreen.style.display = 'none';
initializeGame();
startGame();
});
// Start game on click
startScreen.addEventListener('click', startGame);
// Initialize game on load
initializeGame();
</script>
</body>
</html>
59)2048 game
<<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<meta content="width=device-width, initial-scale=1.0" name="viewport"></meta>
<title>2048 Game</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
background-color: #faf8ef;
margin: 0;
padding: 20px;
box-sizing: border-box;
}
h1 {
font-size: 2em;
margin-bottom: 20px;
color: #776e65;
}
#board-container {
width: 100%;
max-width: 420px;
margin: 0 auto;
padding: 10px;
background-color: #bbada0;
border-radius: 6px;
box-sizing: border-box;
}
#board {
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
}
.tile {
width: 100%;
padding-top: 100%; /* Maintains square shape */
position: relative;
background-color: #cdc1b4;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
font-weight: bold;
color: #776e65;
box-sizing: border-box;
transition: all 0.3s ease;
}
.tile-inner {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
/* Tile Colors */
.x2 { background-color: #eee4da; color: #776e65; }
.x4 { background-color: #ede0c8; color: #776e65; }
.x8 { background-color: #f2b179; color: #f9f6f2; }
.x16 { background-color: #f59563; color: #f9f6f2; }
.x32 { background-color: #f67c5f; color: #f9f6f2; }
.x64 { background-color: #f65e3b; color: #f9f6f2; }
.x128 { background-color: #edcf72; color: #f9f6f2; }
.x256 { background-color: #edcc61; color: #f9f6f2; }
.x512 { background-color: #edc850; color: #f9f6f2; }
.x1024 { background-color: #edc53f; color: #f9f6f2; }
.x2048 { background-color: #edc22e; color: #f9f6f2; }
/* New Tile Styles for numbers up to 1000 */
.x4096 { background-color: #3c3a32; color: #f9f6f2; }
.x8192 { background-color: #3c3a32; color: #f9f6f2; }
.x16384 { background-color: #3c3a32; color: #f9f6f2; }
.x32768 { background-color: #3c3a32; color: #f9f6f2; }
.x65536 { background-color: #3c3a32; color: #f9f6f2; }
.x131072 { background-color: #3c3a32; color: #f9f6f2; }
.x262144 { background-color: #3c3a32; color: #f9f6f2; }
.x524288 { background-color: #3c3a32; color: #f9f6f2; }
.x1048576 { background-color: #3c3a32; color: #f9f6f2; }
.x1000 { background-color: #3c3a32; color: #f9f6f2; }
#score-container {
margin-top: 20px;
}
#score, #highScore {
font-size: 1.5em;
margin: 10px;
color: #776e65;
}
.button {
padding: 10px 20px;
margin: 5px;
background-color: #8f7a66;
color: #f9f6f2;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
}
.button:hover {
background-color: #6f5e50;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>2048 Game</h1>
<div id="score-container">
<div id="score">Score: 0</div>
<div id="highScore">High Score: 0</div>
</div>
<div id="board-container">
<div id="board"></div>
</div>
<div id="controls">
<button class="button" onclick="moveBoard('up')">Up</button>
<button class="button" onclick="moveBoard('left')">Left</button>
<button class="button" onclick="moveBoard('down')">Down</button>
<button class="button" onclick="moveBoard('right')">Right</button>
</div>
<audio class="hidden" id="newTileSound">
<source src="newTile.mp3" type="audio/mpeg"></source>
</audio>
<audio class="hidden" id="mergeSound">
<source src="merge.mp3" type="audio/mpeg"></source>
</audio>
<script>
const boardSize = 4;
let board = [];
let score = 0;
let highScore = 0;
let canMove = true;
function initBoard() {
board = Array.from({ length: boardSize }, () => Array(boardSize).fill(0));
score = 0;
updateScore();
addRandomTile();
addRandomTile();
updateBoard();
}
function addRandomTile() {
let emptyTiles = [];
for (let r = 0; r < boardSize; r++) {
for (let c = 0; c < boardSize; c++) {
if (board[r][c] === 0) emptyTiles.push({ r, c });
}
}
if (emptyTiles.length > 0) {
const { r, c } = emptyTiles[Math.floor(Math.random() * emptyTiles.length)];
board[r][c] = Math.random() < 0.9 ? 2 : 4;
playSound('newTileSound');
}
}
function updateBoard() {
const boardElement = document.getElementById('board');
boardElement.innerHTML = '';
for (let r = 0; r < boardSize; r++) {
for (let c = 0; c < boardSize; c++) {
const tileValue = board[r][c];
const tileElement = document.createElement('div');
tileElement.className = `tile x${tileValue}`;
tileElement.innerHTML = `<div class="tile-inner">${tileValue > 0 ? tileValue : ''}</div>`;
boardElement.appendChild(tileElement);
}
}
updateScore();
}
function updateScore() {
document.getElementById('score').textContent = `Score: ${score}`;
if (score > highScore) {
highScore = score;
document.getElementById('highScore').textContent = `High Score: ${highScore}`;
}
}
function moveBoard(direction) {
if (!canMove) return;
canMove = false;
let moved = false;
function slideAndMerge(rowOrCol) {
let line = rowOrCol.map(cell => board[cell[0]][cell[1]]);
let mergedLine = mergeLine(line);
for (let i = 0; i < boardSize; i++) {
let value = mergedLine[i];
let [r, c] = rowOrCol[i];
if (board[r][c] !== value) {
moved = true;
board[r][c] = value;
}
}
}
for (let i = 0; i < boardSize; i++) {
if (direction === 'left') {
slideAndMerge(Array.from({ length: boardSize }, (_, j) => [i, j]));
} else if (direction === 'right') {
slideAndMerge(Array.from({ length: boardSize }, (_, j) => [i, boardSize - 1 - j]));
} else if (direction === 'up') {
slideAndMerge(Array.from({ length: boardSize }, (_, j) => [j, i]));
} else if (direction === 'down') {
slideAndMerge(Array.from({ length: boardSize }, (_, j) => [boardSize - 1 - j, i]));
}
}
if (moved) {
addRandomTile();
}
updateBoard();
canMove = true;
checkGameOver();
}
function mergeLine(line) {
let merged = [];
for (let i = 0; i < boardSize; i++) {
if (line[i] !== 0) {
if (merged.length > 0 && merged[merged.length - 1] === line[i]) {
merged[merged.length - 1] *= 2;
score += merged[merged.length - 1];
playSound('mergeSound');
} else {
merged.push(line[i]);
}
}
}
while (merged.length < boardSize) merged.push(0);
return merged;
}
function checkGameOver() {
for (let r = 0; r < boardSize; r++) {
for (let c = 0; c < boardSize; c++) {
if (board[r][c] === 0) return; // still have empty tiles
if (r < boardSize - 1 && board[r][c] === board[r + 1][c]) return; // can merge down
if (c < boardSize - 1 && board[r][c] === board[r][c + 1]) return; // can merge right
}
}
alert('Game Over!');
initBoard();
}
function playSound(soundId) {
document.getElementById(soundId).play();
}
window.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp') moveBoard('up');
else if (e.key === 'ArrowDown') moveBoard('down');
else if (e.key === 'ArrowLeft') moveBoard('left');
else if (e.key === 'ArrowRight') moveBoard('right');
});
initBoard();
</script>
</body>
</html>
60)Beginner AI!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Conversation</title>
<style>
body {
font-family: Arial, sans-serif;
background-image: url(dino\ background.webp); /* Replace with your image URL */
background-size: cover;
background-position: center;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.chat-container {
width: 400px;
background-color: rgba(255, 255, 255, 0.85);
border-radius: 8px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.chat-box {
height: 300px;
padding: 10px;
overflow-y: auto;
border-bottom: 1px solid #ddd;
}
.chat-box .message {
margin: 10px 0;
padding: 10px 15px;
border-radius: 20px;
max-width: 75%;
line-height: 1.5;
}
.message.user {
background-color: #a2d5f2;
color: #000;
align-self: flex-end;
text-align: right;
margin-left: auto;
}
.message.ai {
background-color: #ffffff;
color: #333;
align-self: flex-start;
text-align: left;
margin-right: auto;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"] {
width: calc(100% - 60px);
padding: 10px;
border: none;
border-top: 1px solid #ddd;
font-size: 16px;
}
button {
width: 50px;
padding: 10px;
border: none;
background-color: #007bff;
color: white;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="chat-container">
<div id="chat-box" class="chat-box">
<!-- Chat messages will appear here -->
</div>
<input type="text" id="user-input" placeholder="Ask me something...">
<button onclick="sendMessage()">Send</button>
</div>
<script>
const responses = {
"hello": ["Hello! How can I help you today?", "Hi there! What can I do for you?"],
"how are you": ["I'm just a bunch of code, but I'm doing great! How about you?"],
"i am fine": ["That's good to hear! How can I assist you today?"],
"who are you": ["I'm an AI assistant, here to help you with any questions or tasks you have."],
"what can you do": ["I can answer questions, provide information, and help you with tasks."],
"what is your name": ["I'm your AI assistant, here to help you.", "You can call me Jarvis!"],
"bye": ["Goodbye! Have a great day!"],
"youtube": ["Opening YouTube for you..."],
"google": ["Let's search Google..."],
"facebook": ["Opening Facebook..."],
"instagram": ["Opening Instagram..."],
"blog": ["Opening your blog..."],
"time": ["Let me check the time for you..."],
"weather": ["Let me check the weather for you..."],
"open my site": ["Opening your site..."],
"city": ["That's great! Your city is Maharashtra."],
"country": ["That's great! Your country is India."],
"language": ["Your language is Marathi."],
"currency": ["Sorry, I don't want to share your currency..."],
"timezone": ["Yoo! You are living in the Indian time zone."],
"population": ["Sorry, I don't want to share that..."],
"capital": ["Your capital is Mumbai."],
"place": ["Your famous place is Mumbai."],
"person": ["Your famous person is from Maharashtra."],
"food": ["Your famous food is Biryani."],
"religion": ["Your famous religion is Hinduism."],
"festival": ["Your famous festival is Diwali."],
"currency": ["Your famous currency is Rupee."],
"what are the delicious foods in maharashtra": ["Biryani, Pani Puri, Vada Pav, etc."],
"what are the famous places in maharashtra": ["Mumbai, Pune, Nashik, etc."],
"what are the famous people from maharashtra": ["Mahatma Gandhi, Ratan Tata, etc."],
"default": ["I'm not sure how to respond to that. Can you ask me something else?"]
};
function sendMessage() {
const userInput = document.getElementById('user-input').value.trim().toLowerCase();
if (!userInput) return;
appendMessage(userInput, 'user');
setTimeout(() => {
const aiResponse = generateAIResponse(userInput);
appendMessage(aiResponse, 'ai');
handleCommands(userInput);
}, 1000);
document.getElementById('user-input').value = "";
}
function appendMessage(message, sender) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('div');
messageElement.className = `message ${sender}`;
messageElement.textContent = message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
}
function generateAIResponse(userInput) {
for (const key in responses) {
if (userInput.includes(key)) {
const possibleResponses = responses[key];
return possibleResponses[Math.floor(Math.random() * possibleResponses.length)];
}
}
const defaultResponses = responses["default"];
return defaultResponses[Math.floor(Math.random() * defaultResponses.length)];
}
function handleCommands(userInput) {
if (userInput.includes("youtube")) {
window.open("https://www.youtube.com", "_blank");
} else if (userInput.includes("google")) {
window.open("https://www.google.com", "_blank");
} else if (userInput.includes("facebook")) {
window.open("https://www.facebook.com", "_blank");
} else if (userInput.includes("instagram")) {
window.open("https://www.instagram.com", "_blank");
} else if (userInput.includes("blog")) {
window.open("https://krishnablogy.blogspot.com", "_blank");
} else if (userInput.includes("time")) {
const currentTime = new Date().toLocaleTimeString();
appendMessage(`The current time is ${currentTime}`, 'ai');
} else if (userInput.includes("weather")) {
fetchWeatherData();
} else if (userInput.includes("open my site")) {
window.open("https://your-specific-site.com", "_blank"); // Replace with your actual URL
}
}
async function fetchWeatherData() {
const apiKey = 'your_openweathermap_api_key'; // Replace with your OpenWeatherMap API key
const city = 'Maharashtra'; // Replace with your desired city
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
const data = await response.json();
const weatherDescription = data.weather[0].description;
const temperature = data.main.temp;
const weatherMessage = `The weather in ${city} is ${weatherDescription} with a temperature of ${temperature}°C.`;
appendMessage(weatherMessage, 'ai');
} catch (error) {
appendMessage("Sorry, I couldn't fetch the weather data at the moment.", 'ai');
}
}
</script>
</body>
</html>
61)Carrom game...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Carrom Game</title>
<style>
.carrom-game-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
width: 100%;
background-color: #fafafa;
margin: 0;
}
.carrom-board {
position: relative;
width: 400px;
height: 400px;
background-color: #e6b800;
border: 20px solid #8b4513;
border-radius: 10px;
overflow: hidden;
}
.coins {
position: absolute;
width: 100%;
height: 100%;
}
.coin {
position: absolute;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #ffffff;
}
.coin.black {
background-color: #000000;
}
.coin.red {
background-color: #ff0000;
}
.striker {
position: absolute;
width: 40px;
height: 40px;
background-color: #cccccc;
border-radius: 50%;
left: 50%;
bottom: 10px;
transform: translateX(-50%);
}
.hole {
position: absolute;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #333;
}
.hole.one { top: 0; left: 0; }
.hole.two { top: 0; right: 0; }
.hole.three { bottom: 0; left: 0; }
.hole.four { bottom: 0; right: 0; }
button {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.status, .score {
margin-top: 10px;
font-size: 18px;
}
</style>
</head>
<body>
<div class="carrom-game-container">
<div class="carrom-board">
<div class="coins">
<!-- Add more white and black balls -->
<div class="coin" id="white-1" style="left: 50%; top: 50%;"></div>
<div class="coin" id="white-2" style="left: 30%; top: 30%;"></div>
<div class="coin" id="white-3" style="left: 70%; top: 30%;"></div>
<div class="coin" id="white-4" style="left: 30%; top: 70%;"></div>
<div class="coin" id="white-5" style="left: 70%; top: 70%;"></div>
<div class="coin black" id="black-1" style="left: 50%; top: 60%;"></div>
<div class="coin black" id="black-2" style="left: 40%; top: 50%;"></div>
<div class="coin black" id="black-3" style="left: 60%; top: 50%;"></div>
<div class="coin black" id="black-4" style="left: 50%; top: 40%;"></div>
<div class="coin red" id="red" style="left: 50%; top: 50%;"></div>
</div>
<div class="striker" id="striker"></div>
<div class="hole one"></div>
<div class="hole two"></div>
<div class="hole three"></div>
<div class="hole four"></div>
</div>
<button id="strikeButton">Strike</button>
<div id="status" class="status">Player 1's Turn</div>
<div id="score" class="score">Player 1: 0 | Player 2: 0</div>
</div>
<script>
let currentPlayer = 1;
let scores = {1: 0, 2: 0};
document.getElementById('strikeButton').addEventListener('click', () => {
const striker = document.getElementById('striker');
const balls = document.querySelectorAll('.coin');
const board = document.querySelector('.carrom-board').getBoundingClientRect();
const status = document.getElementById('status');
const scoreDisplay = document.getElementById('score');
// Reset striker position
striker.style.bottom = '10px';
// Animate the striker with increased speed
let strikerSpeed = 10; // Increased speed
let strikerInterval = setInterval(() => {
let currentBottom = parseInt(striker.style.bottom) || 0;
striker.style.bottom = `${currentBottom + strikerSpeed}px`;
if (currentBottom >= board.height - striker.offsetHeight) {
clearInterval(strikerInterval);
// Animate balls with realistic physics and increased speed
balls.forEach(ball => {
let ballLeft = parseInt(ball.style.left) || (board.width / 2) - 15;
let ballTop = parseInt(ball.style.top) || (board.height / 2) - 15;
let ballVelocityX = (Math.random() - 0.5) * 8; // Increased speed
let ballVelocityY = (Math.random() - 0.5) * 8; // Increased speed
let ballFriction = 0.95; // Adjusted friction for faster movement
let ballInterval = setInterval(() => {
ballVelocityX *= ballFriction;
ballVelocityY *= ballFriction;
ballLeft += ballVelocityX;
ballTop += ballVelocityY;
// Boundary constraints
if (ballLeft < 0 || ballLeft > board.width - ball.offsetWidth) {
ballVelocityX *= -1;
}
if (ballTop < 0 || ballTop > board.height - ball.offsetHeight) {
ballVelocityY *= -1;
}
ball.style.left = `${ballLeft}px`;
ball.style.top = `${ballTop}px`;
// Check if ball is in any hole
document.querySelectorAll('.hole').forEach(hole => {
const holeRect = hole.getBoundingClientRect();
const ballRect = ball.getBoundingClientRect();
if (
ballRect.left < holeRect.right &&
ballRect.right > holeRect.left &&
ballRect.top < holeRect.bottom &&
ballRect.bottom > holeRect.top
) {
ball.style.left = `${holeRect.left + (holeRect.width / 2) - (ballRect.width / 2)}px`;
ball.style.top = `${holeRect.top + (holeRect.height / 2) - (ballRect.height / 2)}px`;
clearInterval(ballInterval);
// Update scores
if (ball.classList.contains('red') || ball.classList.contains('black')) {
scores[currentPlayer]++;
}
updateScore();
}
});
// Stop if ball is not moving
if (Math.abs(ballVelocityX) < 0.1 && Math.abs(ballVelocityY) < 0.1) {
clearInterval(ballInterval);
}
}, 50);
});
// Change player turn
currentPlayer = currentPlayer === 1 ? 2 : 1;
status.textContent = `Player ${currentPlayer}'s Turn`;
}
}, 20);
});
function updateScore() {
const scoreDisplay = document.getElementById('score');
scoreDisplay.textContent = `Player 1: ${scores[1]} | Player 2: ${scores[2]}`;
}
</script>
</body>
</html>
62)Shooting game
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { margin: 0; display: flex; justify-content: center; align-items: center; height: 100vh; }
canvas { display: block; }
button { font-size: 18px; padding: 10px; }
</style>
<title>Shooting Game</title>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<button id="playButton" onclick="startGame()">Play</button>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const playButton = document.getElementById('playButton');
let score = 0;
let health = 500;
let gameRunning = false;
let difficulty = 1;
const player = {
x: canvas.width / 2,
y: canvas.height - 30,
width: 30,
height: 30,
color: 'blue',
speed: 5
};
const enemies = [];
const projectiles = [];
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x - player.width / 2, player.y - player.height / 2, player.width, player.height);
}
function drawEnemies() {
enemies.forEach(enemy => {
ctx.fillStyle = enemy.color;
ctx.fillRect(enemy.x - enemy.width / 2, enemy.y - enemy.height / 2, enemy.width, enemy.height);
});
}
function drawProjectiles() {
projectiles.forEach(projectile => {
ctx.fillStyle = 'green';
ctx.fillRect(projectile.x - projectile.width / 2, projectile.y - projectile.height / 2, projectile.width, projectile.height);
});
}
function moveEnemies() {
enemies.forEach(enemy => {
enemy.y += enemy.speed * difficulty;
if (enemy.y > canvas.height) {
enemies.splice(enemies.indexOf(enemy), 1); // Remove enemy if it goes off the screen
score++;
spawnEnemy(); // Spawn a new enemy
}
if (
player.x < enemy.x + enemy.width / 2 &&
player.x + player.width > enemy.x - enemy.width / 2 &&
player.y < enemy.y + enemy.height / 2 &&
player.y + player.height > enemy.y - enemy.height / 2
) {
health -= 10;
if (health <= 0) {
endGame();
}
}
});
}
function moveProjectiles() {
projectiles.forEach((projectile, index) => {
projectile.y -= projectile.speed;
if (projectile.y < 0) {
projectiles.splice(index, 1);
}
enemies.forEach((enemy, enemyIndex) => {
if (
projectile.x < enemy.x + enemy.width / 2 &&
projectile.x + projectile.width > enemy.x - enemy.width / 2 &&
projectile.y < enemy.y + enemy.height / 2 &&
projectile.y + projectile.height > enemy.y - enemy.height / 2
) {
enemies.splice(enemyIndex, 1);
projectiles.splice(index, 1);
score += 10;
spawnEnemy(); // Spawn a new enemy when one is destroyed
}
});
});
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawEnemies();
drawProjectiles();
moveEnemies();
moveProjectiles();
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText(`Score: ${score}`, 10, 30);
ctx.fillText(`Health: ${health} HP`, canvas.width - 150, 30);
if (gameRunning) {
requestAnimationFrame(draw);
}
}
function startGame() {
playButton.style.display = 'none';
canvas.style.display = 'block';
gameRunning = true;
resetGame();
draw();
}
function endGame() {
gameRunning = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.font = '30px Arial';
ctx.fillText(`Game Over! Score: ${score}`, canvas.width / 2 - 150, canvas.height / 2 - 15);
playButton.style.display = 'block';
canvas.style.display = 'none';
}
function resetGame() {
player.x = canvas.width / 2;
player.y = canvas.height - 30;
score = 0;
health = 500;
enemies.length = 0;
projectiles.length = 0;
difficulty = 1;
for (let i = 0; i < 5; i++) {
spawnEnemy();
}
}
function spawnEnemy() {
const enemyType = Math.floor(Math.random() * 3); // Randomly choose an enemy type
let enemy = {
x: Math.random() * canvas.width,
y: -30, // Start above the screen
width: 30,
height: 30,
color: 'red',
speed: 2 + difficulty // Default speed
};
switch (enemyType) {
case 0:
enemy.color = 'red';
enemy.speed = 2 + difficulty; // Basic enemy
break;
case 1:
enemy.color = 'orange';
enemy.speed = 3 + difficulty; // Medium enemy
break;
case 2:
enemy.color = 'purple';
enemy.speed = 4 + difficulty; // Hard enemy
break;
}
enemies.push(enemy);
}
function increaseDifficulty() {
difficulty += 0.1;
}
document.addEventListener('keydown', (event) => {
if (event.code === 'Space' && gameRunning) {
projectiles.push({
x: player.x,
y: player.y - player.height / 2,
width: 5,
height: 20,
speed: 7
});
}
if (event.code === 'ArrowLeft' && player.x - player.width / 2 > 0) {
player.x -= player.speed;
}
if (event.code === 'ArrowRight' && player.x + player.width / 2 < canvas.width) {
player.x += player.speed;
}
});
setInterval(increaseDifficulty, 5000);
</script>
</body>
</html>
-----------------------------XXXXXXXXX Ended XXXXXXXXXXX----------------------------------
0 Comments
if you have any doubts. please let me know