Initial commit

This commit is contained in:
VA-run23
2025-03-11 15:40:46 +05:30
commit 4b25bb931b
5 changed files with 1885 additions and 0 deletions
+146
View File
@@ -0,0 +1,146 @@
// const express = require("express");
// const socket = require("socket.io");
// const http = require("http");
// const { Chess } = require("chess.js");
// const path = require("path");
// const app = express(); //Routing and middleware setup are done by express ////app has an instance of express
// const server = http.createServer(app);
// const io = socket(server); //socket is used to connect in real time
// const chess = new Chess(); //now all the rules of chess is stored in chess variable
// let players = {};
// let currentPlayer = "w";
// app.set("view engine", "ejs");
// app.use(express.static(path.join(__dirname, "public"))); //by this we can use images and all
// app.get("/", (req, res) => {
// res.render("index", { title: "Chess Game" });
// });
// io.on("connection", function (uniquesocket) {
// console.log("connected");
// if (!players.white) {
// players.white = uniquesocket.id;
// uniquesocket.emit("playerRole", "w");
// } else if (!players.black) {
// players.black = uniquesocket.id;
// uniquesocket.emit("playerRole", "b");
// } else {
// uniquesocket.emit("spectatorRole");
// }
// uniquesocket.on("disconnect", function () {
// if (uniquesocket.id === players.white) {
// delete players.white;
// } else if (uniquesocket.id === players.black) {
// delete players.black;
// }
// });
// uniquesocket.on("move", (move) => {
// try {
// if (chess.turn() === "w" && uniquesocket.id !== players.white) return; //uniquesocket.on("move", (move) => {} isse move event record hoga
// if (chess.turn() === "b" && uniquesocket.id !== players.black) return;
// const result = chess.move(move); //idhar move event(jo bhi pawn move hua hai wo) valid hai ki nahi evaluate hoga
// if (result) {
// currentPlayer = chess.turn();
// io.emit("move", move);
// io.emit("boardState", chess.fen());
// } else {
// console.log("Invalid move: ", move); ////consoling in browser
// uniquesocket.emit("invalidMove", move); ////informing the player that the move is invalid
// }
// } catch (err) {
// console.log(err);
// uniquesocket.emit("Invalid move: ", move); ////const result = chess.move(move);if this line fails then catch is executed///////timestamp:1:06:06
// }
// });
// });
// server.listen(3000, function () {
// console.log("Listening");
// });
// //3 types of server method
// //server sends the message to the sender itself also, so only the sender can be able to know that the message is sent to other/s
// //server sends the message to only particular person
// //server send the message to all except sender , this is called broadcasting. Eg:When you are typing in whatsapp, it shows typing to others except the typer
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const { Chess } = require("chess.js");
const path = require("path");
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const chess = new Chess();
let players = {};
let currentPlayer = "w";
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.render("index", { title: "Chess Game" });
});
io.on("connection", (socket) => {
console.log("A player connected:", socket.id);
if (!players.white) {
players.white = socket.id;
socket.emit("playerRole", "w");
} else if (!players.black) {
players.black = socket.id;
socket.emit("playerRole", "b");
} else {
socket.emit("spectatorRole");
}
socket.on("disconnect", () => {
if (socket.id === players.white) {
delete players.white;
} else if (socket.id === players.black) {
delete players.black;
}
});
socket.on("move", (move) => {
try {
if ((chess.turn() === "w" && socket.id !== players.white) ||
(chess.turn() === "b" && socket.id !== players.black)) {
return;
}
const result = chess.move(move);
if (result) {
currentPlayer = chess.turn();
io.emit("move", move);
io.emit("boardState", chess.fen());
} else {
console.log("Invalid move:", move);
socket.emit("invalidMove", move);
}
} catch (err) {
console.error(err);
socket.emit("error", "Invalid move");
}
});
socket.emit("boardState", chess.fen());
});
server.listen(3000, () => {
console.log("Server listening on port 3000");
});
+1380
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
// {
// "name": "newchessgame",
// "version": "1.0.0",
// "main": "app.js",
// "scripts": {
// "test": "echo \"Error: no test specified\" && exit 1"
// },
// "keywords": [],
// "author": "",
// "license": "ISC",
// "description": "",
// "dependencies": {
// "chess.js": "^1.0.0-beta.8",
// "ejs": "^3.1.10",
// "express": "^4.19.2",
// "nodemon": "^3.1.2",
// "socket.io": "^4.7.5"
// }
// }
{
"name": "newchessgame",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"chess.js": "^1.0.0-beta.8",
"ejs": "^3.1.10",
"express": "^4.19.2",
"nodemon": "^3.1.2",
"socket.io": "^4.7.5"
},
"engines": {
"node": ">=14.0.0"
}
}
+227
View File
@@ -0,0 +1,227 @@
// const socket = io();
// const chess = new Chess();
// const boardElement = document.querySelector(".chessboard");
// let draggedPiece = null;
// let sourceSquare = null;
// let playerRole = null;
// const renderBoard = () => {
// const board = chess.board();
// boardElement.innerHTML = "";
// board.forEach((row, rowIndex) => {
// row.forEach((square, squareindex) => {
// const squareElement = document.createElement("div");
// squareElement.classList.add(
// "square",
// (rowIndex + squareindex) % 2 === 0 ? "light" : "dark"
// );
// squareElement.dataset.row = rowIndex;
// squareElement.dataset.column = squareindex;
// if (square) {
// const pieceElement = document.createElement("div");
// pieceElement.classList.add(
// "piece",
// square.color === "w" ? "white" : "black" // piece.type
// );
// pieceElement.innerText = getPieceUnicode(square); ///this one has empty string at 1:26:38
// pieceElement.draggable = playerRole === square.color;
// pieceElement.addEventListener("dragstart", (e) => {
// if (pieceElement.draggable) {
// draggedPiece = pieceElement;
// sourceSquare = { row: rowIndex, col: squareindex };
// e.dataTransfer.setData("text/plain", ""); ////to makesure that it runs in cross platforms
// }
// });
// pieceElement.addEventListener("dragend", (e) => {
// draggedPiece = null;
// sourceSquare = null;
// });
// squareElement.appendChild(pieceElement);
// } //if anything goes wrong check from above till here
// squareElement.addEventListener("dragover", function (e) {
// e.preventDefault();
// });
// squareElement.addEventListener("drop", function (e) {
// e.preventDefault();
// if (draggedPiece) {
// const targetSquare = {
// row: parseInt(squareElement.dataset.row),
// col: parseInt(squareElement.dataset.col),
// };
// handleMove(sourceSquare, targetSquare);
// }
// });
// boardElement.appendChild(squareElement); //this at 63line
// });
// });
// if (playerRole === "b") {
// boardElement.classList.add("flipped");
// } else {
// boardElement.classList.remove("flipped");
// }
// };
// const handleMove = (source, target) => {
// //handle move ::: at 1:41:28 , is at 68
// const move = {
// from: `${String.fromCharCode(97 + source.col)}${8 - source.row}`,
// to: `${String.fromCharCode(97 + target.col)}${8 - target.row}`,
// promotion: "q",
// };
// socket.emit("move", move); //sending the new move to the backend
// };
// const getPieceUnicode = (piece) => {
// const unicodePieces = {
// p: "♟", // BLACK CHESS PAWN
// r: "♜", // BLACK CHESS ROOK
// n: "♞", // BLACK CHESS KNIGHT
// b: "♝", // BLACK CHESS BISHOP
// q: "♛", // BLACK CHESS QUEEN
// k: "♚", // BLACK CHESS KING
// P: "♙", // WHITE CHESS PAWN
// R: "♖", // WHITE CHESS ROOK
// N: "♘", // WHITE CHESS KNIGHT
// B: "♗", // WHITE CHESS BISHOP
// Q: "♕", // WHITE CHESS QUEEN
// K: "♔", // WHITE CHESS KING
// };
// return unicodePieces[piece.type] || "";
// };
// socket.on("playerRole", function (role) {
// //at 14602 at 95
// playerRole = role;
// renderBoard();
// });
// socket.on("spectatorRole", function () {
// playerRole = null;
// renderBoard();
// });
// socket.on("boardState", function (fen) {
// //the new fen equation formed will be loaded freshly by chess.load and then the board is rendered with new equations
// chess.load(fen);
// renderBoard();
// });
// socket.on("move", function (move) {
// //jo bhi move hua hoga use hum receive karke chaladenge, aur boardRender kardenge
// chess.move(move);
// renderBoard();
// });
// renderBoard();
const socket = io();
const chess = new Chess();
const boardElement = document.querySelector(".chessboard");
let draggedPiece = null;
let sourceSquare = null;
let playerRole = null;
const renderBoard = () => {
const board = chess.board();
boardElement.innerHTML = "";
board.forEach((row, rowIndex) => {
row.forEach((square, colIndex) => {
const squareElement = document.createElement("div");
squareElement.classList.add(
"square",
(rowIndex + colIndex) % 2 === 0 ? "light" : "dark"
);
squareElement.dataset.row = rowIndex;
squareElement.dataset.col = colIndex;
if (square) {
const pieceElement = document.createElement("div");
pieceElement.classList.add(
"piece",
square.color === "w" ? "white" : "black"
);
pieceElement.innerText = getPieceUnicode(square);
pieceElement.draggable = playerRole === square.color;
pieceElement.addEventListener("dragstart", (e) => {
if (pieceElement.draggable) {
draggedPiece = pieceElement;
sourceSquare = { row: rowIndex, col: colIndex };
e.dataTransfer.setData("text/plain", ""); // Ensuring cross-platform compatibility
}
});
pieceElement.addEventListener("dragend", () => {
draggedPiece = null;
sourceSquare = null;
});
squareElement.appendChild(pieceElement);
}
squareElement.addEventListener("dragover", (e) => e.preventDefault());
squareElement.addEventListener("drop", (e) => {
e.preventDefault();
if (draggedPiece) {
const targetSquare = {
row: parseInt(squareElement.dataset.row),
col: parseInt(squareElement.dataset.col),
};
handleMove(sourceSquare, targetSquare);
}
});
boardElement.appendChild(squareElement);
});
});
boardElement.classList.toggle("flipped", playerRole === "b");
};
const handleMove = (source, target) => {
const move = {
from: `${String.fromCharCode(97 + source.col)}${8 - source.row}`,
to: `${String.fromCharCode(97 + target.col)}${8 - target.row}`,
promotion: "q",
};
socket.emit("move", move);
};
const getPieceUnicode = (piece) => {
const unicodePieces = {
p: "♟", r: "♜", n: "♞", b: "♝", q: "♛", k: "♚",
P: "♙", R: "♖", N: "♘", B: "♗", Q: "♕", K: "♔",
};
return unicodePieces[piece.type] || "";
};
socket.on("playerRole", (role) => {
playerRole = role;
renderBoard();
});
socket.on("spectatorRole", () => {
playerRole = null;
renderBoard();
});
socket.on("boardState", (fen) => {
chess.load(fen);
renderBoard();
});
socket.on("move", (move) => {
chess.move(move);
renderBoard();
});
renderBoard();
+90
View File
@@ -0,0 +1,90 @@
<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chess Game</title>
<style>
.chessboard {
display: grid;
grid-template-columns: repeat(8, minmax(0, 1fr));
grid-template-rows: repeat(8, minmax(0, 1fr));
width: 400px;
height: 400px;
transform: rotate(0deg);
}
.piece.white {
color: white;
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 1));
}
.piece.black {
color: black;
}
.flipped {
transform: rotate(180deg);
}
</style>
</head>
<body>
<div class="d-flex align-items-center justify-content-center vh-100">
<div class="bg-danger width: 24rem; height: 24rem;"></div>
</div>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"
integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.3/chess.min.js"
integrity="sha512-xRllwz2gdZciIB+AkEbeq+gVhX8VB8XsfqeFbUh+SzHlN96dEduwtTuVuc2u9EROlmW9+yhRlxjif66ORpsgVA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html> -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chess Game</title>
<style>
.chessboard {
display: grid;
grid-template-columns: repeat(8, minmax(0, 1fr));
grid-template-rows: repeat(8, minmax(0, 1fr));
width: 400px;
height: 400px;
}
.square {
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
width: 50px;
height: 50px;
}
.light { background-color: #f0d9b5; }
.dark { background-color: #b58863; }
.piece { position: relative; cursor: grab; }
.piece.white { color: white; text-shadow: 0 0 3px black; }
.piece.black { color: black; }
.flipped { transform: rotate(180deg); }
</style>
</head>
<body>
<div class="d-flex align-items-center justify-content-center vh-100">
<div class="chessboard"></div>
</div>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.3/chess.min.js"></script>
<script src="/js/chessGame.js"></script>
</body>
</html>