gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:52:45 25 4
gpt4 key购买 nike

我是个初学者,请多多指教:)我正在尝试用 html、css 和纯 JS 制作一个 tic tac toe 游戏。我在点击棋盘上的正方形时尝试显示“X”符号(或“O”)(我使用 for 循环,就像我之前在俄罗斯方 block 游戏中使用它一样)。我尝试了事件监听器,但无法让它工作,可能我做错了什么: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 元素。添加它的合适位置是在您的 setup 函数中;这样,一旦设置了面板,您的 Canvas 就会监听点击。

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

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

假设点击发生在其某处:

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

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

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

我们对该值进行取底以产生整数值(第一个单元格为 0,第二个单元格为 1,等等)。

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

这是反射(reflect)这一点的新“板”:

|            +---------+---------+---------+
^ 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
});

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

关于javascript - 如何通过单击正方形在使用 for 循环创建的板上显示 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61565931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com