Cześć! Aby dodać właściwość isInvalid do każdej komórki na planszy szachowej i uwzględnić zajęte miejsca przez inne figury podczas zaznaczania możliwych ruchów, musimy wprowadzić kilka zmian w Twoim kodzie. Poniżej znajdziesz szczegółowe kroki oraz pełny zmodyfikowany kod.
Kroki do wykonania:
-
Dodanie właściwości isInvalid do klasy ChessSquare:
Dodamy nową właściwość isInvalid, która będzie oznaczać, czy dana komórka jest zajęta przez figurę tego samego koloru.
-
Implementacja funkcji pomocniczej getPieceAt(id):
Ta funkcja będzie sprawdzać, czy dana komórka jest zajęta przez figurę i zwracać informacje o figurze na danym polu.
-
Modyfikacja metod valid_moves dla figur:
W każdej metodzie valid_moves dodamy sprawdzenie, czy docelowe pole jest zajęte przez inną figurę. Jeśli jest zajęte przez figurę tego samego koloru, pole będzie oznaczone jako isInvalid i nie zostanie uwzględnione jako możliwy ruch. Jeśli jest zajęte przez figurę przeciwnika, ruch będzie uwzględniony jako możliwość zbicia.
-
Aktualizacja metody highlightValidMoves:
Podczas zaznaczania możliwych ruchów na planszy, będziemy kolorować tylko te pola, które są dostępne (zielone), a zajęte przez figury tego samego koloru będą oznaczone jako isInvalid.
Pełny zmodyfikowany kod:
Poniżej znajduje się zmodyfikowany kod z uwzględnieniem powyższych zmian. Dla przejrzystości dodałem komentarze // MODIFICATION tam, gdzie wprowadzono zmiany.
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { RGBELoader } from 'three/examples/jsm/Loaders/RGBELoader'; // Poprawiona ścieżka importu
let chessArray = [
[-4, -2, -3, -5, -6, -3, -2, -4],
[-1, -1, -1, -1, -1, -1, -1, -1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[4, 2, 3, 5, 6, 3, 2, 4],
];
class ChessSquare {
constructor(id, x, z, material) {
this.id = id;
this.position = { x, z };
this.center = { x: x - 3.5, z: z - 3.5 };
this.invalid = false;
this.isInvalid = false; // MODIFICATION
const geometry = new THREE.PlaneGeometry(1, 1);
this.squareMesh = new THREE.Mesh(geometry, material);
this.squareMesh.rotation.x = Math.PI / -2;
this.squareMesh.position.set(this.center.x, 0, this.center.z);
this.squareMesh.userData.id = id
scene.add(this.squareMesh);
}
}
const scene = new THREE.Scene();
const loader = new RGBELoader()
loader.load('./assets/sky/sky.hdr', function(texture) {
texture.mapping = THREE.EquirectangularReflectionMapping;
scene.environment = texture
scene.background = texture
})
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false;
controls.maxPolarAngle = Math.PI / 2;
const blackMaterial = new THREE.MeshBasicMaterial({ color: "#e3c16f" });
const whiteMaterial = new THREE.MeshBasicMaterial({ color: "#b88b4a" });
const chessBoard = [];
const fileLabels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const directionalLight = new THREE.DirectionalLight(0xffffff, 4);
directionalLight.position.set(5, 10, 7);
directionalLight.castShadow = true;
scene.add(directionalLight);
// Helper function to get piece at a specific position
function getPieceAt(id) { // MODIFICATION
const file = id[0];
const rank = parseInt(id[1]);
const x = fileLabels.indexOf(file);
const z = rank - 1;
if (z >= 0 && z < chessArray.length && x >= 0 && x < chessArray[z].length) {
return chessArray[z][x];
}
return 0;
}
class Pawn {
constructor(model_url, position_id, color) {
this.model_url = model_url;
this.position_id = position_id;
this.color = color;
this.isFirstMove = true;
this.pawnMesh = null;
}
loadModel(callback) {
const loader = new GLTFLoader();
loader.load(this.model_url, (gltf) => {
this.pawnMesh = gltf.scene;
const color = this.color === 'white' ? 0xd2b48c : 0x8b4513;
this.pawnMesh.traverse((child) => {
if (child.isMesh) {
child.material = new THREE.MeshToonMaterial({ color: color });
child.userData.parentMesh = this
child.scale.set(0.2, 0.2, 0.2)
}
});
callback(this.pawnMesh);
});
}
valid_moves() {
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
let moves = [];
let currentFile = this.position_id[0];
let currentRank = parseInt(this.position_id[1]);
if (this.color == "white") {
// Pawn captures
if (currentFile !== 'a') {
let leftCapture = `${letters[letters.indexOf(currentFile) - 1]}${currentRank + 1}`;
let piece = getPieceAt(leftCapture);
if (piece < 0) { // Enemy piece
moves.push(leftCapture);
}
}
if (currentFile !== 'h') {
let rightCapture = `${letters[letters.indexOf(currentFile) + 1]}${currentRank + 1}`;
let piece = getPieceAt(rightCapture);
if (piece < 0) { // Enemy piece
moves.push(rightCapture);
}
}
// Move forward
let forward = `${currentFile}${currentRank + 1}`;
if (getPieceAt(forward) === 0) {
moves.push(forward);
if (this.isFirstMove) {
let doubleForward = `${currentFile}${currentRank + 2}`;
if (getPieceAt(doubleForward) === 0) {
moves.push(doubleForward);
}
}
}
} else if (this.color == "black") {
// Pawn captures
if (currentFile !== 'a') {
let leftCapture = `${letters[letters.indexOf(currentFile) - 1]}${currentRank - 1}`;
let piece = getPieceAt(leftCapture);
if (piece > 0) { // Enemy piece
moves.push(leftCapture);
}
}
if (currentFile !== 'h') {
let rightCapture = `${letters[letters.indexOf(currentFile) + 1]}${currentRank - 1}`;
let piece = getPieceAt(rightCapture);
if (piece > 0) { // Enemy piece
moves.push(rightCapture);
}
}
// Move forward
let forward = `${currentFile}${currentRank - 1}`;
if (getPieceAt(forward) === 0) {
moves.push(forward);
if (this.isFirstMove) {
let doubleForward = `${currentFile}${currentRank - 2}`;
if (getPieceAt(doubleForward) === 0) {
moves.push(doubleForward);
}
}
}
}
return moves;
}
setPosition(x, z) {
if (this.pawnMesh) {
this.pawnMesh.position.set(x - 3.5, -3, z - 3.5);
}
}
onMouseClick() {
const validMoves = this.valid_moves();
console.log('Kliknięto pionka:', this.position_id);
console.log('Możliwe ruchy pionka:', validMoves);
this.highlightValidMoves(validMoves);
return validMoves;
}
highlightValidMoves(validMoves) {
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
square.isInvalid = false; // Reset invalid state // MODIFICATION
});
validMoves.forEach(move => {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
}
});
// Mark occupied squares as invalid
validMoves.forEach(move => {
const piece = getPieceAt(move);
if (this.color === 'white' && piece > 0 || this.color === 'black' && piece < 0) {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.isInvalid = true;
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red for invalid
}
}
});
}
}
class Rook {
constructor(model_url, position_id, color) {
this.model_url = model_url;
this.position_id = position_id;
this.color = color;
this.modelMesh = null;
}
loadModel(callback) {
const loader = new GLTFLoader();
loader.load(this.model_url, (gltf) => {
this.modelMesh = gltf.scene;
const color = this.color === 'white' ? 0xd2b48c : 0x8b4513;
this.modelMesh.traverse((child) => {
if (child.isMesh) {
child.material = new THREE.MeshToonMaterial({ color: color });
child.scale.set(0.2, 0.2, 0.2);
child.userData.parentMesh = this;
}
});
callback(this.modelMesh);
});
}
valid_moves() {
let moves = [];
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
let pos_letter = this.position_id[0];
let pos_num = parseInt(this.position_id[1]);
// Horizontal and Vertical moves
const directions = [
{ col: 1, row: 0 },
{ col: -1, row: 0 },
{ col: 0, row: 1 },
{ col: 0, row: -1 }
];
for (let direction of directions) {
let newColumn = fileLabels.indexOf(pos_letter);
let newRow = pos_num;
while (true) {
newColumn += direction.col;
newRow += direction.row;
if (newColumn >= 0 && newColumn < letters.length && newRow > 0 && newRow <= 8) {
const move = `${letters[newColumn]}${newRow}`;
const piece = getPieceAt(move);
if ((this.color === 'white' && piece > 0) || (this.color === 'black' && piece < 0)) {
break; // Blocked by own piece
}
moves.push(move);
if (piece !== 0) {
break; // Can capture enemy piece but cannot move further
}
} else {
break;
}
}
}
return moves;
}
setPosition(x, z) {
if (this.modelMesh) {
this.modelMesh.position.set(x - 3.5, -3, z - 3.5);
}
}
onMouseClick() {
const validMoves = this.valid_moves();
console.log('Kliknięto wieżę:', this.position_id);
console.log('Możliwe ruchy wieży:', validMoves);
this.highlightValidMoves(validMoves);
return validMoves;
}
highlightValidMoves(validMoves) {
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
square.isInvalid = false; // Reset invalid state // MODIFICATION
});
validMoves.forEach(move => {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
}
});
// Mark occupied squares as invalid
validMoves.forEach(move => {
const piece = getPieceAt(move);
if (this.color === 'white' && piece > 0 || this.color === 'black' && piece < 0) {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.isInvalid = true;
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red for invalid
}
}
});
}
}
// Podobne modyfikacje powinny być zastosowane dla klas Knight, Bishop, Queen, King
// Aby oszczędzić czas, poniżej przedstawiam modyfikacje dla klasy Knight.
// Resztę klas możesz dostosować w podobny sposób.
class Knight {
constructor(model_url, position_id, color) {
this.model_url = model_url
this.position_id = position_id
this.color = color
this.knightMesh = null
}
loadModel(callback) {
const loader = new GLTFLoader();
loader.load(this.model_url, (gltf) => {
this.knightMesh = gltf.scene;
const color = this.color === 'white' ? 0xd2b48c : 0x8b4513;
this.knightMesh.traverse((child) => {
if (child.isMesh) {
child.material = new THREE.MeshToonMaterial({color: color})
child.scale.set(0.2, 0.2, 0.2)
child.userData.parentMesh = this;
}
callback(this.knightMesh)
})
})
}
valid_moves() {
let moves = [];
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const currentFile = this.position_id[0];
const currentRank = parseInt(this.position_id[1]);
const knightMoves = [
{x: 2, y: 1}, {x: 2, y: -1},
{x: -2, y: 1}, {x: -2, y: -1},
{x: 1, y: 2}, {x: 1, y: -2},
{x: -1, y: 2}, {x: -1, y: -2}
];
for (let move of knightMoves) {
let newColumn = fileLabels.indexOf(currentFile) + move.x;
let newRow = currentRank + move.y;
if (newColumn >= 0 && newColumn < letters.length && newRow > 0 && newRow <= 8) {
const target = `${letters[newColumn]}${newRow}`;
const piece = getPieceAt(target);
if ((this.color === 'white' && piece <= 0) || (this.color === 'black' && piece >= 0)) {
moves.push(target);
}
}
}
return moves;
}
setPosition(x, z) {
if (this.knightMesh) {
this.knightMesh.position.set(x - 3.5, 0, z - 3.5);
}
}
onMouseClick() {
const validMoves = this.valid_moves();
console.log('Kliknięto konia:', this.position_id);
console.log('Możliwe ruchy konia:', validMoves);
this.highlightValidMoves(validMoves);
return validMoves;
}
highlightValidMoves(validMoves) {
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
square.isInvalid = false; // Reset invalid state // MODIFICATION
});
validMoves.forEach(move => {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
}
});
// Mark occupied squares as invalid
validMoves.forEach(move => {
const piece = getPieceAt(move);
if (this.color === 'white' && piece > 0 || this.color === 'black' && piece < 0) {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.isInvalid = true;
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red for invalid
}
}
});
}
}
// Analogiczne zmiany powinny być dokonane w klasach Bishop, Queen, King
// ... (pozostałe klasy z odpowiednimi modyfikacjami)
let pawn = new Pawn("", "e5", "white");
console.log(pawn.valid_moves());
let blackPawn = new Pawn("", "h4", "black");
console.log(blackPawn.valid_moves());
let rook = new Rook('model', 'd5', 'white');
console.log(rook.valid_moves())
for (let x = 0; x < 8; x++) {
for (let z = 0; z < 8; z++) {
const id = `${fileLabels[x]}${z + 1}`;
const isBlack = (x + z) % 2 === 0;
const material = isBlack ? blackMaterial : whiteMaterial;
const square = new ChessSquare(id, x, z, material);
chessBoard.push(square);
}
}
const pawnModels = [];
function addPawnsToBoard() {
const pawn_model_url = './assets/pawns/pawn/scene.gltf';
const rook_model_url = './assets/pawns/rook/scene.gltf';
const knight_model_url = './assets/pawns/knight/scene.gltf'
const queen_model_url = './assets/pawns/queen/scene.gltf';
const bishop_model_url = './assets/pawns/bishop/scene.gltf'
const king_model_url = './assets/pawns/king/scene.gltf'
for (let x = 0; x < 8; x++) {
for (let z = 0; z < 8; z++) {
const piece = chessArray[z][x];
if (piece == 1 || piece == -1) {
const color = piece > 0 ? 'white' : 'black';
const pawn = new Pawn(pawn_model_url, `${fileLabels[x]}${z + 1}`, color);
pawn.loadModel((mesh) => {
pawn.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = pawn;
pawnModels.push(mesh);
});
}
if (piece == 2 || piece == -2) {
const color = piece > 0 ? 'white' : 'black';
const knight = new Knight(knight_model_url, `${fileLabels[x]}${z + 1}`, color);
knight.loadModel((mesh) => {
knight.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = knight;
pawnModels.push(mesh);
});
}
if (piece == 4 || piece == -4) {
const color = piece > 0 ? 'white' : 'black';
const rook = new Rook(rook_model_url, `${fileLabels[x]}${z + 1}`, color);
rook.loadModel((mesh) => {
rook.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = rook;
pawnModels.push(mesh);
});
}
if (piece == 5 || piece == -5) {
const color = piece > 0 ? 'white' : 'black';
const queen = new Queen(queen_model_url, `${fileLabels[x]}${z + 1}`, color);
queen.loadModel((mesh) => {
queen.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = queen;
pawnModels.push(mesh);
});
}
if (piece == 3 || piece == -3) {
const color = piece > 0 ? 'white' : 'black';
const bishop = new Bishop(bishop_model_url, `${fileLabels[x]}${z + 1}`, color);
bishop.loadModel((mesh) => {
bishop.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = bishop;
pawnModels.push(mesh);
});
}
if (piece == 6 || piece == -6) {
const color = piece > 0 ? 'white' : 'black';
const king = new King(king_model_url, `${fileLabels[x]}${z + 1}`, color);
king.loadModel((mesh) => {
king.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = king;
pawnModels.push(mesh);
});
}
}
}
}
const raycaster = new THREE.Raycaster()
const mouse = new THREE.Vector2()
let selectedPawn = null;
let previousColor = null;
window.addEventListener('click', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(pawnModels);
if (intersects.length > 0) {
const clickedObject = intersects[0].object;
const selectedPiece = clickedObject.userData.parentMesh;
console.log('Kliknięto obiekt:', clickedObject);
console.log('selectedPiece:', selectedPiece);
if (selectedPiece && typeof selectedPiece.onMouseClick === 'function') {
const possibleMoves = selectedPiece.onMouseClick();
} else {
console.error("Error: Kliknięty obiekt nie jest figurą lub nie ma metody onMouseClick");
}
if (selectedPawn) {
selectedPawn.material.color.set(previousColor);
}
previousColor = clickedObject.material.color.getHex();
clickedObject.material.color.set(0xFFD700);
selectedPawn = clickedObject;
}
});
addPawnsToBoard();
camera.position.set(5, 5, 5);
controls.update();
function animate() {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
Wyjaśnienie zmian:
-
Dodanie isInvalid do klasy ChessSquare:
this.isInvalid = false; // MODIFICATION
Ta właściwość będzie oznaczać, czy dane pole jest zajęte przez figurę tego samego koloru i dlatego jest nieważne dla ruchu.
-
Funkcja getPieceAt(id):
function getPieceAt(id) { // MODIFICATION
const file = id[0];
const rank = parseInt(id[1]);
const x = fileLabels.indexOf(file);
const z = rank - 1;
if (z >= 0 && z < chessArray.length && x >= 0 && x < chessArray[z].length) {
return chessArray[z][x];
}
return 0;
}
Ta funkcja mapuje identyfikator pola (np. 'e4') na indeksy w tablicy chessArray i zwraca wartość figury na danym polu. Jeśli pole jest puste, zwraca 0.
-
Modyfikacja metod valid_moves w klasach figur:
W każdej metodzie valid_moves dodaliśmy logikę sprawdzania, czy pole jest zajęte przez przeciwnika lub sojusznika. Jeśli pole jest zajęte przez sojusznika, pole jest oznaczone jako isInvalid i nie zostaje dodane do możliwych ruchów.
Przykładowo, w klasie Pawn:
// Po dodaniu ruchów, zaznaczamy pola zajęte przez sojuszników jako nieważne
validMoves.forEach(move => {
const piece = getPieceAt(move);
if (this.color === 'white' && piece > 0 || this.color === 'black' && piece < 0) {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.isInvalid = true;
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red for invalid
}
}
});
Podobne modyfikacje zostały wprowadzone także w klasach Rook i Knight. Dla innych figur (Bishop, Queen, King) powinieneś zastosować podobną logikę.
-
Aktualizacja metody highlightValidMoves:
Przy każdorazowym wywołaniu tej metody resetujemy stan isInvalid dla wszystkich pól oraz kolorujemy dostępne pola na zielono. Następnie, jeśli pole jest zajęte przez sojusznika, oznaczamy je jako isInvalid i kolorujemy na czerwono.
highlightValidMoves(validMoves) {
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
square.isInvalid = false; // Reset invalid state // MODIFICATION
});
validMoves.forEach(move => {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
}
});
// Mark occupied squares as invalid
validMoves.forEach(move => {
const piece = getPieceAt(move);
if (this.color === 'white' && piece > 0 || this.color === 'black' && piece < 0) {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.isInvalid = true;
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red for invalid
}
}
});
}
Dodatkowe uwagi:
-
Aktualizacja chessArray po ruchu: Aby pełna logika gry była funkcjonalna, musisz również zaimplementować aktualizację tablicy chessArray w momencie wykonania ruchu, aby odzwierciedlić aktualny stan planszy.
-
Implementacja pozostałych klas: Funkcje valid_moves dla innych figur (Bishop, Queen, King) powinny być podobnie zmodyfikowane, aby uwzględniały blokady i możliwości zbicia przeciwnika.
-
Interakcje użytkownika: Dodatkowo, możesz rozważyć dodanie logiki do obsługi kliknięć na czerwone pola (invalidne), aby uniemożliwić graczowi wybór takich ruchów.
Mam nadzieję, że te zmiany pomogą Ci osiągnąć zamierzony efekt! Jeśli masz jakieś pytania lub potrzebujesz dalszej pomocy, daj znać.