首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript中的Tic-Tac-Toe

Javascript中的Tic-Tac-Toe
EN

Stack Overflow用户
提问于 2014-10-20 12:32:13
回答 1查看 378关注 0票数 0

我已经试着解决这个问题好几个小时了,但最后我觉得自己像个笨蛋。这是用于编程类的,代码应该做的是在单击偶数转弯时在框中显示"x“,在奇数转弯时显示"o”。现在,当单击这些框时,只会显示“x”。我想我在涉及全局变量的某个地方搞砸了。有人能帮我找出我做错了什么吗?

下面是HTML和Javascript代码:

代码语言: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);
}
代码语言:javascript
复制
<!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>

EN

回答 1

Stack Overflow用户

发布于 2014-10-20 12:37:31

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

代码语言:javascript
复制
p = markCount % 2;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26458612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档