gpt4 book ai didi

javascript - JavaScript 中的井字游戏

转载 作者:行者123 更新时间:2023-12-03 11:36:49 24 4
gpt4 key购买 nike

我已经尝试解决这个问题几个小时了,但最终我只觉得自己像个白痴。这是用于编程课的,代码应该做的是当在偶数轮上单击时在框中显示“x”,在奇数轮上单击时在框中显示“o”。现在,单击这些框时仅显示“x”。我想我在涉及全局变量的地方搞砸了。有人可以帮我弄清楚我做错了什么吗?

以下是 HTML 和 Javascript 代码:

var markCount

window.onload = function() {
var i;
var prefix;

i = 0; //initializing i
prefix = "square"; //defining prefix
markCount = getMarkCount();
while (i !== null) //will keep repeating until i is null
{
document.getElementById(prefix + i).onclick = markTheSquare; //finds element Id by prefix and i number and references clicked function
i = i + 1; //increments i
} //while
};

function markTheSquare() {
this.onclick = null;
this.innerHTML = getXorO; //causes x or o to be displayed in current element
markCount = markCount + 1;
}

function getMarkCount() {
return setMarkCount(markCount);
}

function setMarkCount(markCount) {
markCount = 0;
}

function getXorO() {
var string;
var p;

string = "xo"
p = getMarkCount % 2;
return string.charAt(p);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title> Tic-Tac-Toe Part 2 </title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<script src="ticTacToePart1.js" type="text/javascript"></script>
<style type="text/css">
body
{
font-size:12pt;
margin-left:auto;
margin-right:auto;
padding-top:5em;
width:33em;
}

.square
{
float:left;
font-size:8em;
height:1.25em;
text-align:center;
width:1.25em;
}

.border1
{
border-left:solid;
border-right:solid;
}

.border2
{
border-bottom:solid;
border-top:solid;
}

</style>
</head>
<body>
<div id=page>
<div class="square" id=square0></div>
<div class="square border1" id=square1></div>
<div class="square" id=square2></div>
<div class="square border2" id=square3></div>
<div class="square border1 border2"id=square4></div>
<div class="square border2" id=square5></div>
<div class="square" id=square6></div>
<div class="square border1" id=square7></div>
<div class="square" id=square8></div>
<div id=ticTacToeBoard></div>
</div>
</body>
</html>

最佳答案

这是因为每次调用 getMarkCount 时,您都会将 markCount 设置为 0(因为您在 getMarkCount 中调用 setMarkCount)。只需将 getMarkCount 替换为 markCount 即可。

p = markCount % 2;

关于javascript - JavaScript 中的井字游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458612/

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