簡體   English   中英

井字游戲Java語言

[英]Tic-Tac-Toe in Javascript

我已經嘗試解決了幾個小時,但最終我還是覺得自己像個白痴。 這是針對編程類的,代碼應該做的是在偶數匝上單擊時在框中顯示“ 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM