好的,下面是一个简单的 JavaScript 象棋游戏的代码供你参考:
``` // 定义棋盘大小和棋盘格子的大小 const BOARD_SIZE = 8; const TILE_SIZE = 50;
// 定义棋盘元素 let board = document.getElementById('board');
// 初始化棋盘 for (let row = 0; row < BOARD_SIZE; row++) { for (let col = 0; col < BOARD_SIZE; col++) { // 创建棋盘格子 let tile = document.createElement('div'); // 设置样式 tile.style.top = row * TILE_SIZE + 'px'; tile.style.left = col * TILE_SIZE + 'px'; tile.style.width = TILE_SIZE + 'px'; tile.style.height = TILE_SIZE + 'px'; // 奇数行和偶数行的颜色不同 if ((row + col) % 2 === 0) { tile.classList.add('light-tile'); } else { tile.classList.add('dark-tile'); } // 将格子添加到棋盘中 board.appendChild(tile); } }
// 定义棋子类型常量 const PAWN = 'pawn'; const KNIGHT = 'knight'; const BISHOP = 'bishop'; const ROOK = 'rook'; const QUEEN = 'queen'; const KING = 'king';
// 定义棋子颜色常量 const WHITE = 'white'; const BLACK = 'black';
// 定义棋子类 class Piece { // 构造函数 constructor(type, color, row, col) { this.type = type; this.color = color; this.row = row; this.col = col; this.element = document.createElement('div'); this.element.classList.add('piece', ${color}-${type}
); board.appendChild(this.element); this.moveTo(row, col); }
// 移动棋子 moveTo(row, col) { this.row = row; this.col = col; this.element.style.top = row * TILE_SIZE + 'px'; this.element.style.left = col * TILE_SIZE + 'px'; } }
// 创建棋子 let whitePawn1 = new Piece(PAWN,