井字游戏;JavaScript;代码已编写,但不起作用



我正在尝试在JavaScript上创建一个"井字游戏"。这实际上是我的家庭作业,但是我的老师拒绝给我任何反馈,即使我完全陷入困境。反正我的任务是编造游戏的逻辑,动作监听器已经由任务给出。我做了研究,我写了代码,但游戏无法正常工作,即程序不检查是否有赢家,也没有显示谁是赢家。此外,它不会检查是否有平局。这是我的代码,我需要帮助:

let players = ['x', 'o'];
let activePlayer = 0;
const winningCombos = [
['0', '0', '1', '1', '2', '2'],
['0', '2', '1', '1', '2', '0'],
['0', '0', '0', '1', '0', '2'],
['1', '0', '1', '1', '1', '2'],
['2', '0', '2', '1', '2', '2'],
['0', '0', '1', '0', '2', '0'],
['0', '1', '1', '1', '2', '1'],
['0', '2', '1', '2', '2', '2'],
]
let board = [
['', '', ''],
['', '', ''],
['', '', '']
];
function switchPlayer() {
if (activePlayer == players[0]) {
activePlayer = players[1]
} else if (activePlayer == players[1]) {
activePlayer = players[0]
} else {
console.log('Error')
}
}
function startGame() {
activePlayer = players[Math.floor(players.length * Math.random())]; // Random selection of the first active player
alert ('Active player is: ' + activePlayer);
renderBoard(board);
}
let oResult = []; // an Arry for storing the rows and columns of the 'o' 
let xResult = []; // an Arry for storing the rows and columns of the 'x' 

//This is the function that is supposed to check whether there is a draw, but does not do that. My idea was that it should check, if the 'oResult' and the 'xResult' arrays have reached their maximum (so they are completely filled) and if yes, they should display into the console the phrae "it's a draw"
function ifDraw() {
if (((oResult.length === 7) && (xResult.length === 9)) || ((oResult.length === 9) && (xResult.length === 7))) {
console.log('its a draw')
} 
}
//This function does not work as well, if I understand correctly. I thought, that the FOR cycle would go through each array in the 'winningCombos' array and compare it with the oResult and the 'xResult' arrays. When one of these two arrays matches one of the arrays from 'winningCombos', then the function 'showWinner' is called (the 'showWinner' function is already given by the task)
function ifWon() {
for (let i = 0; i < winningCombos.length; i++) {
if ((oResult === winningCombos[i]) || (xResult === winningCombos[i])) {
showWinner(activePlayer)
} 
}
}
function click(row, column) {
board[row][column] = activePlayer;
switchPlayer();
renderBoard(board);
//Even though it was stated clearly, that the values of 'x' have to be written into the 'xResult' and the values of 'o' - into the 'oResult', the program sometimes mixes it up and the values of 'x' sometimes go to the 'oResult'. Why?
if (activePlayer === 'x') {
xResult.push(row);
xResult.push(column);
} else if (activePlayer === 'o') {
oResult.push(row);
oResult.push(column);
}
//These don't work
ifDraw();
ifWon();
// Here I display what has been assignet to what in the console so that I can check the process
console.log(xResult)
console.log(oResult)
console.log('-')
}

问题是对我来说,代码是有意义的。我的老师也没有指出任何重大错误。但是,我找不到游戏不显示谁赢了,甚至停在一点上的原因。 下面的代码不是必需的,因为它只是给定的任务,如果你想看看游戏的现场外观。

以下是任务给出的内容(也是JS在另一个文件中(:

window.addEventListener('load', startGame);
let boardEl = document.getElementById('board');
let modalEl = document.getElementById('modal');
let resetButtons = document.getElementsByClassName('reset');
for (let btn of resetButtons) {
btn.addEventListener('click', function () {
if (!modalEl.classList.contains('hidden')) {
modalEl.classList.add('hidden');
}
startGame();
});
}
boardEl.addEventListener('click', function (event) {
let targetClasses = event.target.classList;
let targetData = event.target.dataset;
if (targetClasses.contains('field') && !targetClasses.contains('busy')) {
click(targetData.row, targetData.col);
}
});
function showWinner(winner) {
let header = modalEl.getElementsByTagName('h2')[0];
header.textContent = `🍾 Won the player №${winner + 1}! 🍾`;
modalEl.classList.remove('hidden');
}
function renderBoard(board) {
const fields = [];
for (let [i, row] of board.entries()) {
for (let [j, value] of row.entries()) {
fields.push(`
<div class="field ${value ? 'busy' : 'free'}" 
data-row="${i}" 
data-col="${j}"
style="grid-row:${i + 1};grid-column:${j + 1};"
>
${value || ''}
</div>
`);
}
}
boardEl.innerHTML = fields.join('');
}

下面是构成外观的HTML和CSS文件(也是任务给出的(。如果你想看看我看到的,我用 Repl.it 平台来做我的写作。 .HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tic-tac-toe</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="board"></div>
<div id="modal" class="hidden">
<div id="modal__window">
<h2></h2>
<div id="modal__buttons">
<button class="reset">Play again</button>
</div>
</div>
</div>
<div class="panel">
<button class="reset">From the beginning</button>
</div>
<script src="logic.js"></script>
<script src="ui.js"></script>
</body>
</html>

.CSS:

* {
box-sizing: border-box;
}
.panel {
text-align: center;
}

#board {
position: relative;
height: 450px;
width: 450px;
margin: 50px auto 30px auto;
overflow: hidden;
display: grid;
grid-auto-columns: 1fr;
grid-auto-rows: 1fr;
grid-gap: 10px;
}
.field {
background-color: #78bec5;
border-radius: 14px;
cursor: pointer;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
font-size: 5em;
font-family: 'Arial', sans-serif;
}
.free:hover {
background-color: #3d4250;
}
#modal {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
#modal__window {
position: relative;
top: 30%;
width: 30%;
margin: 0 auto;
padding: 5px 20px 20px;
background-color: #f8f6f6;
text-align: center;
}
button {
min-width: 100px;
border: 1px solid lightgray;
padding: 15px;
background-color: #fff;
font-size: 20pt;
border-radius: 15px;
opacity: 0.7;
}
button:hover {
box-shadow: 2px 1px 0 rgb(0, 0, 0);
}
button:active {
box-shadow: inset 2px 1px 0;
}
.hidden {
display: none;
}

我真的很感激任何帮助或指示,我不知道我做错了什么,错误在哪里。提前谢谢你!

看起来检查游戏结果的函数,如ifWonifDraw正在尝试使用===检查数组相等性。这是行不通的,因为检查数组的相等性需要检查一个数组中的每个元素是否与第二个数组中的相应元素(即同一索引处的元素(匹配。测试数组相等性的一种快速方法是使用JSON.stringify

if (JSON.stringify(arr1) === JSON.stringify(arr2)) {...your code here}

希望对您有所帮助!

最新更新