如何通过单击正方形在使用 for 循环创建的板上显示 X

How to display an X on a board created using for loops by clicking on a square

我是初学者所以请手下留情:) 我正在尝试使用 html、css 和纯 JS 制作井字游戏。我一直在尝试显示一个 "X" 符号(或 "O" ),同时单击我板上的一个正方形(我用它来循环,就像我之前在俄罗斯方块游戏中使用它一样)。我尝试了事件侦听器但无法让它工作,可能是我做错了什么 :P 所以无论如何我的问题是:如何通过单击在板上显示符号?

<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="tic-tac-toe.css">
    <title>TIC TAC TOE IN JS</title>
    <h1 class='header'>TIC TAC TOE in JS</h1>
  </head>
<body>
    <div class='canvas'>
        <canvas id="canvas" width='300px' height="300px"></canvas>
    </div>
    <div class='scores'>
        <div>Player 1 Wins: <span id="score-x">0</span></div>
        <div>Ties: <span id="score-tie">0</span> </div>
        <div>Player 2 Wins: <span id="score-o">0</span> </div>
    </div>

<script src="./tictactoe.js"></script>

</body>

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

//CONSTS
const row = 3;
const col = 3;
const vacant = "white";
const sq = 100;
let w = canvas.clientWidth/3;
let h = canvas.clientHeight/3;


//draw a square
function drawSquare(x, y, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x*sq, y*sq, sq, sq);
    ctx.strokeStyle = 'black';
    ctx.strokeRect(x*sq, y*sq, sq, sq);
}

    //Create board

let board = [ ];
for(let r = 0; r < row; r++){
    board[r] = [ ];
        for(let c = 0; c < col; c++) {
            board[r][c] = vacant;
        }
}
    //Draw Board

function drawBoard() {
    for(r = 0; r < row; r++) {
        for(c = 0; c < col; c++){
            drawSquare(c, r, board[r][c]);
        }
    }
}
drawBoard();

//players
const players = ['X', 'O']
const player1 = players[0];
const player2 = players[1];

//let the starting player be selected at random
const spot = board[r-1][c-1];

function setup() {
    let randomPlayer = Math.floor(Math.random() *2 );
    let currentPlayer = "";
    if (randomPlayer == 0){
        currentPlayer = player1;
        alert('Player 1 starts the game !')
    }else {
        currentPlayer = player2;
        alert('Player 2 starts the game !')
    };
}
function drawSymbol () {
    let x = w * r + w/2;
    let y = h * c + h/2;
    let xr = w/4;
    spot.addEventListener('click', (x, y, xr) => {
    line(x-xr, y-xr, x+xr, y+xr);
    line(x+xr, y-xr, x-xr, y+xr);
})
}


setup();
//Check if player clicked on the board 

//Place X

//Place O

更新代码

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

//Variables
let row = 3;
let col = 3;
const vacant = "white";
let sq = 100;
let w = canvas.clientWidth/3;
let h = canvas.clientHeight/3;
let currentPlayer = "";

//players
const players = ['X', 'O']
const player1 = players[0];
const player2 = players[1];


//draw a square
function drawSquare(x, y, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x*sq, y*sq, sq, sq);
    ctx.strokeStyle = 'black';
    ctx.strokeRect(x*sq, y*sq, sq, sq);
}

//Create board
let board = [ ];
for(let r = 0; r < row; r++){
    board[r] = [ ];
        for(let c = 0; c < col; c++) {
            board[r][c] = vacant;
        }
}
//Draw Board
function drawBoard() {
    for(r = 0; r < row; r++) {
        for(c = 0; c < col; c++){
            drawSquare(c, r, board[r][c]);
        }
    }
}
drawBoard();



// sets up the game
function setup() {

    //let the starting player be selected at random
    let randomPlayer = Math.floor(Math.random() *2 );
    if (randomPlayer == 0){
        currentPlayer = player1;
        alert('Player 1 starts the game !')
    }else {
        currentPlayer = player2;
        alert('Player 2 starts the game !')
    };

    function calculatePos () {
        // checks for click position
        canvas.addEventListener('click', event => {

            // get the position of the board relative to the page
            let {left, top} = canvas.getBoundingClientRect();

            // get the position of the click relative to the page
            let mouseX = event.clientX - left;
            let mouseY = event.clientY - top;

            // calculate which square is being clicked 
            let newRow = Math.floor(mouseY / sq);
            let newCol = Math.floor(mouseX / sq);
            drawSymbol(newRow, newCol)
        })  
    }




calculatePos();
}
setup();
// listens for clicks on the canvas to draw the symbol
function drawSymbol (newRow, newCol) {
    let x = w * newRow + w/2;
    let y = h * newCol + h/2;
    let xr = w/4;
    if(currentPlayer == players[0]) {
        canvas.addEventListener('click', () => {
            ctx.lineWidth = 5;
            ctx.strokeStyle = 'black';
            ctx.beginPath();
            ctx.moveTo(x-xr, y-xr);
            ctx.lineTo(x+xr, y+xr);
            ctx.moveTo(x+xr, y-xr);
            ctx.lineTo(x-xr, y+xr);
            ctx.stroke();
    }) 
    } else {
            canvas.addEventListener('click', () => {
                ctx.lineWidth = 5;
                ctx.strokeStyle = 'black';
                ctx.beginPath();
                ctx.arc(x , y, 40, 0, 2 * Math.PI);
                ctx.stroke();
    }
)}
}
drawSymbol(r, c);

您似乎从未向 canvas 本身添加事件侦听器? 从这样的事件侦听器中,您可以获得点击的 X 和 Y 坐标以确定点击了哪个单元格。如果该单元格为空,则为当前玩家画一个符号。

所以您需要让 drawSymbol 获取有关要在哪个单元格中绘制的信息。

您创建了一个点变量,我不明白它的作用,并在 drawSymbol 中添加了一个事件侦听器,但这可能不是一个元素?而且 drawSymbol 函数从未被调用,因此代码不会被执行,因此您也不会收到错误。

到目前为止看起来还不错!实现此目的的一种方法是将事件侦听器添加到 整个 canvas 元素 。添加它的合适位置是在您的 setup 函数中;这样,一旦设置好电路板,您的 canvas 就会监听点击。

现在,如果整个 canvas 都在监听点击,您将需要一种方法来确定点击了哪个方块。这并不太难,但是有一些障碍。让我们想象一下尝试为“一维板”确定这一点:

"The board"
+---------+---------+---------+

假设点击某处发生:

+---------+---------+---------+
             ^click
|------------| <-clickPos = the distance between the click and the edge of the board

我们如何确定它发生在哪个单元格中?如果我们知道每个单元格的大小,以及点击的位置,就可以用除法来完成:

const clickedCell = Math.floor(clickPos / cellSize);

我们将这个值取底以产生一个整数值(第一个单元格为 0,第二个单元格为 1,依此类推)。

这里是 "gotcha" 出现的地方:当点击事件发生时,很容易提取点击的位置 相对于页面 ,但这不一定是你想要的。

这是反映这一点的新 "board":

|            +---------+---------+---------+
^ edge                    ^click
of page                   |
|-------------------------| <-this distance is easy to extract from the event
             |------------| <-this is the distance you want
|------------| <-this is the distance between the edge of the board and the edge of the page

如图所示,我们关心的点击位置其实并不是事件中记录的位置。为了确定这一点,我们需要从板的左边缘位置减去点击的位置。

这是 JavaScript 中的样子:

canvas.addEventListener('mouseup', event => {
  const { left, top } = canvas.getBoundingClientRect();
  //      ^^^^  ^^^ These give us the position of the board relative to the page
  const mouseX = event.clientX - left;
  const mouseY = event.clientY - top;
  //                   ^^^^^^^ These give us the position of the click relative to the page

  const row = Math.floor(mouseY / sq);
  const col = Math.floor(mouseX / sq);

  // Now draw your "X" or "O" here, using the `row` and `col` values
  // calculated above to determine where to place it
});

提醒一下,您只需要添加一次该事件监听器;添加后,它会在每次点击时调用我们提供的函数。将位置计算工作分解成一个单独的函数等可能是有意义的,但是您会在进行时弄明白这一点。希望这可以帮助;坚持下去!