我有一个前端国际象棋棋盘,其中每个棋子都可以移动/拖动到一个正方形,并且移动将通过 post api 传输到后端。
前端:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chess Board</title>
<style>
#chessboard {
width: 400px;
height: 400px;
display: flex;
flex-wrap: wrap;
}
.square {
width: 50px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.black {
background-color: #769656;
}
.white {
background-color: #eeeed2;
}
.piece {
font-size: 40px;
cursor: move;
user-select: none;
-webkit-user-drag: none;
}
</style>
</head>
<body>
<div id="chessboard"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
const chessboard = document.getElementById("chessboard");
let draggedPiece = null;
let prevRow, prevCol;
// Function to generate chessboard
function generateChessboard() {
const piecesOrder = ['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'];
const pawns = '♟'.repeat(8);
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const square = document.createElement("div");
square.classList.add("square");
square.id = `square-${row}-${col}`; // Assign unique id to each square
if ((row + col) % 2 === 0) {
square.classList.add("white");
} else {
square.classList.add("black");
}
square.dataset.row = row;
square.dataset.col = col;
const piece = document.createElement("span");
piece.classList.add("piece");
// Set up initial positions for white and black pieces
if (row === 0) {
piece.textContent = piecesOrder[col];
} else if (row === 1) {
piece.textContent = pawns[col];
} else if (row === 6) {
piece.textContent = pawns[col].toUpperCase(); // Capitalize for black pawns
} else if (row === 7) {
piece.textContent = piecesOrder[col].toUpperCase(); // Capitalize for black pieces
}
piece.draggable = true; // Make pieces draggable
piece.addEventListener("dragstart", dragStart); // Add dragstart event listener
square.appendChild(piece);
chessboard.appendChild(square);
}
}
}
// Drag-and-drop functions
function dragStart(event) {
draggedPiece = event.target;
prevRow = draggedPiece.parentElement.dataset.row;
prevCol = draggedPiece.parentElement.dataset.col;
event.dataTransfer.setData("text/plain", "");
}
chessboard.addEventListener("dragover", dragOver);
chessboard.addEventListener("drop", drop);
function dragOver(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
const targetSquare = event.target.closest(".square");
const targetPiece = targetSquare.querySelector(".piece");
if (!targetPiece) {
targetSquare.appendChild(draggedPiece);
draggedPiece = null;
} else {
const sourceSquare = draggedPiece.parentElement;
const fromSquare = sourceSquare.id;
const toSquare = targetSquare.id;
makeMove(fromSquare, toSquare);
targetSquare.removeChild(targetPiece);
targetSquare.appendChild(draggedPiece);
sourceSquare.appendChild(targetPiece);
}
const newRow = targetSquare.dataset.row;
const newCol = targetSquare.dataset.col;
console.log(`Piece moved from (${prevRow},${prevCol}) to (${newRow},${newCol})`);
}
// Generate the chessboard
generateChessboard();
});
// Function to make a move on the chessboard via the backend server
function makeMove(fromSquare, toSquare) {
fetch('/move', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ fromSquare, toSquare })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
后端:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use((req, res, next) => {
// Allow requests from any origin
res.setHeader('Access-Control-Allow-Origin', '*');
// Allow certain HTTP methods
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// Allow certain HTTP headers
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Allow credentials (if needed)
res.setHeader('Access-Control-Allow-Credentials', true);
// Move to the next middleware
next();
});
app.use(express.static('public'));
app.use(bodyParser.json());
let port=2000;
app.listen(port, () => {
console.log("Listening on port ${port}");
});
// Function to initialize the chessboard with starting positions
function initializeChessboard() {
return [
[5, 3, 4, 6, 7, 4, 3, 5], // Black pieces in the first row
[1, 1, 1, 1, 1, 1, 1, 1], // Black pawns in the second row
Array(8).fill(0),
Array(8).fill(0),
Array(8).fill(0),
Array(8).fill(0),
[11, 11, 11, 11, 11, 11, 11, 11], // White pawns in the second-to-last row
[15, 13, 14, 16, 17, 14, 13, 15] // White pieces in the last row
];
}
// Array to store the current state of the chessboard
let chessboardState = initializeChessboard();
// Route to get the current state of the chessboard
app.get('/chessboard', (req, res) => {
res.json(chessboardState);
});
// Route to make a move on the chessboard
app.post('/move', (req, res) => {
const { fromSquare, toSquare } = req.body;
// Parse the coordinates of the squares
const [fromRow, fromCol] = parseCoordinates(fromSquare);
const [toRow, toCol] = parseCoordinates(toSquare);
// Check if the move is valid
if (!isValidMove(fromRow, fromCol, toRow, toCol)) {
return res.status(400).json({ status: 'error', message: 'Invalid move' });
}
// Make the move on the chessboard
chessboardState[toRow][toCol] = chessboardState[fromRow][fromCol];
chessboardState[fromRow][fromCol] = 0; // Clear the source square
// Send a response indicating the move was successful
res.json({ status: 'success', message: 'Move processed successfully' });
});
// Function to parse coordinates from square notation (e.g., 'a1' to [0, 0])
function parseCoordinates(square) {
const col = square.charCodeAt(0) - 'a'.charCodeAt(0);
const row = 8 - parseInt(square[1]);
return [row, col];
}
// Function to check if a move is valid
function isValidMove(fromRow, fromCol, toRow, toCol) {
return true;
}
每当我运行程序并检查前端的 DEVTOOLS 时,当我在棋盘上移动时,post api 似乎永远不会工作。我不断收到 500 状态代码错误。
问题是因为您在服务器端 Node.js 中使用“charAt”函数。虽然它是有效的 JavaScript,但它不是有效的服务器端 Node.js。
这里有一些代码可以为您解决问题:
function parseCoordinates(square) {
const col = square[0] - "a"[0];
const row = 8 - parseInt(Number(square[1]));
return [row, col];
}