0% found this document useful (0 votes)
3 views

Chess Board

Uploaded by

bhayanianandi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chess Board

Uploaded by

bhayanianandi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Chess Game

1. Chess board.java
2. import React, { useState } from 'react';
3. import { Board, Position, ChessPiece } from '@/types/chess';
4. import { createInitialBoard, getPieceMoves } from
'@/utils/chessLogic';
5.
6. const ChessBoard = () => {
7. const [board, setBoard] =
useState<Board>(createInitialBoard());
8. const [selectedPosition, setSelectedPosition] =
useState<Position | null>(null);
9. const [possibleMoves, setPossibleMoves] =
useState<Position[]>([]);
10. const [currentPlayer, setCurrentPlayer] =
useState<'white' | 'black'>('white');
11.
12. const handleSquareClick = (row: number, col: number) => {
13. const clickedPosition = { row, col };
14. const clickedPiece = board[row][col];
15.
16. // If no piece is selected
17. if (!selectedPosition) {
18. if (clickedPiece && clickedPiece.color ===
currentPlayer) {
19. setSelectedPosition(clickedPosition);
20. setPossibleMoves(getPieceMoves(board,
clickedPosition, clickedPiece));
21. }
22. return;
23. }
24.
25. // If a piece is already selected
26. const selectedPiece = board[selectedPosition.row]
[selectedPosition.col];
27. if (!selectedPiece) return;
28.
29. // Check if the clicked position is a valid move
30. const isValidMove = possibleMoves.some(
31. move => move.row === row && move.col === col
32. );
33.
34. if (isValidMove) {
35. // Make the move
36. const newBoard = board.map(row => [...row]);
37. newBoard[row][col] = selectedPiece;

Created by: mann chavda


yaksh raval
Chess Game
38. newBoard[selectedPosition.row][selectedPosition.col]
= null;
39. setBoard(newBoard);
40. setCurrentPlayer(currentPlayer === 'white' ?
'black' : 'white');
41. }
42.
43. // Reset selection
44. setSelectedPosition(null);
45. setPossibleMoves([]);
46. };
47.
48. const getPieceSymbol = (piece: ChessPiece | null): string
=> {
49. if (!piece) return '';
50. const symbols: Record<string, Record<string, string>> =
{
51. white: {
52. king: '♔', queen: '♕', rook: '♖',
53. bishop: '♗', knight: '♘', pawn: '♙'
54. },
55. black: {
56. king: '♚', queen: '♛', rook: '♜',
57. bishop: '♝', knight: '♞', pawn: '♟'
58. }
59. };
60. return symbols[piece.color][piece.type];
61. };
62.
63. return (
64. <div className="flex flex-col items-center justify-
center min-h-screen bg-gray-100">
65. <div className="mb-4 text-xl font-semibold">
66. Current Turn: {currentPlayer === 'white' ?
'White' : 'Black'}
67. </div>
68. <div className="border-4 border-gray-800 rounded">
69. {board.map((row, rowIndex) => (
70. <div key={rowIndex} className="flex">
71. {row.map((piece, colIndex) => {
72. const isSelected = selectedPosition?.row ===
rowIndex &&
73. selectedPosition?.col ===
colIndex;
74. const isPossibleMove = possibleMoves.some(
75. move => move.row === rowIndex && move.col
=== colIndex
76. );

Created by: mann chavda


yaksh raval
Chess Game
77. const isLight = (rowIndex + colIndex) % 2 ===
0;
78.
79. return (
80. <div
81. key={`${rowIndex}-${colIndex}`}
82. onClick={() =>
handleSquareClick(rowIndex, colIndex)}
83. className={`
84. w-16 h-16 flex items-center justify-
center text-4xl cursor-pointer
85. transition-colors duration-200
86. ${isLight ? 'bg-[#F0D9B5]' : 'bg-
[#B58863]'}
87. ${isSelected ? 'bg-blue-300' : ''}
88. ${isPossibleMove ? 'bg-blue-200' : ''}
89. ${piece ? 'hover:bg-blue-100' : ''}
90. `}
91. >
92. {getPieceSymbol(piece)}
93. </div>
94. );
95. })}
96. </div>
97. ))}
98. </div>
99. </div>
100. );
101. };
102.
103. export default ChessBoard;

2.Chess board.java

// Update this page (the content is just a fallback if you fail to


update the page)

import ChessBoard from '@/components/ChessBoard';

const Index = () => {


return (
<div className="min-h-screen flex items-center justify-center bg-
gray-100">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4">Welcome to Your Blank
App</h1>

Created by: mann chavda


yaksh raval
Chess Game
<p className="text-xl text-gray-600">Start building your
amazing project here!</p>
</div>
</div>
);
return <ChessBoard />;
};

export default Index;

3.chesslogic.java

import { Board, ChessPiece, Position } from '@/types/chess';

export const createInitialBoard = (): Board => {


const board: Board = Array(8).fill(null).map(() =>
Array(8).fill(null));

// Place pawns
for (let i = 0; i < 8; i++) {
board[1][i] = { type: 'pawn', color: 'black' };
board[6][i] = { type: 'pawn', color: 'white' };
}

// Place other pieces


const pieceOrder: (typeof board[0][0])[] = [
{ type: 'rook', color: 'black' },
{ type: 'knight', color: 'black' },
{ type: 'bishop', color: 'black' },
{ type: 'queen', color: 'black' },
{ type: 'king', color: 'black' },
{ type: 'bishop', color: 'black' },
{ type: 'knight', color: 'black' },
{ type: 'rook', color: 'black' },
];

board[0] = pieceOrder;
board[7] = pieceOrder.map(piece => piece ? { ...piece, color: 'white'
} : null);

return board;
};

export const isValidMove = (


board: Board,
from: Position,
to: Position,
piece: ChessPiece

Created by: mann chavda


yaksh raval
Chess Game
): boolean => {
// Basic validation - ensure the move is within the board
if (
to.row < 0 || to.row > 7 ||
to.col < 0 || to.col > 7
) {
return false;
}

// Can't capture your own piece


const targetPiece = board[to.row][to.col];
if (targetPiece && targetPiece.color === piece.color) {
return false;
}

return true;
};

export const getPieceMoves = (


board: Board,
position: Position,
piece: ChessPiece
): Position[] => {
const moves: Position[] = [];
const { row, col } = position;

// Simple pawn movement logic


if (piece.type === 'pawn') {
const direction = piece.color === 'white' ? -1 : 1;
const startRow = piece.color === 'white' ? 6 : 1;

// Move forward one square


if (!board[row + direction]?.[col]) {
moves.push({ row: row + direction, col });

// Move forward two squares from starting position


if (row === startRow && !board[row + 2 * direction]?.[col]) {
moves.push({ row: row + 2 * direction, col });
}
}

// Capture diagonally
const captureSquares = [
{ row: row + direction, col: col - 1 },
{ row: row + direction, col: col + 1 },
];

captureSquares.forEach(square => {

Created by: mann chavda


yaksh raval
Chess Game
const targetPiece = board[square.row]?.[square.col];
if (targetPiece && targetPiece.color !== piece.color) {
moves.push(square);
}
});
}

return moves.filter(move => isValidMove(board, position, move,


piece));
};

Created by: mann chavda


yaksh raval

You might also like