grade11coder Ответов: 1

Как я могу изменить значение кнопки при нажатии?


In class I am making a tic tac toe game and have been stuck for 2 days trying to make the x's and o's appear and the assignment is due tomorrow! Here is the assignment sheet: COMPSCI20: Tic Tac Toe Assignment

Create an HTML file as shown above. The HTML file should contain the following:  a page title and link to a CSS file  a header division (with an ID) that contains text  a main division (with an ID) containing a 3x3 table of clickable buttons (with a class and each having IDs)  a footer division (with an ID) containing text Title + Links  Main + Table  Header  Footer  Create a CSS file to style the content as shown above. The CSS file should contain the following:  in the header division, define the font, background color, text alignment, and padding  in the main division, define the background color and padding  the buttons should have a defined height, width, font, background color, and border  in the footer division, define the font, background color, text alignment and padding

Create a JS file that contains two global variables: one to store the player turn (X or O) and one to store the winner. The JS file should also contain the following functions:  a Start() function that sets the player turn to start as X and the winner to null  a ChooseSquare() function that places the appropriate letter on the button clicked, disables the button clicked, and switches to other player’s turn  a CheckWin() function that checks each possible winning combination and displays a message in the footer if a player has won


Что я уже пробовал:

`<script>
var winner;
var current;
function Start()
{
  current= "x";
}
function ChooseSquare()
{
 if (document.getElementById("button1").onclick)
 {  
   document.getElementById("button1").value = "x";
   document.getElementById("button1").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button2").onclick)
 {  
   document.getElementById("button2").value = "x";
   document.getElementById("button2").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button3").onclick)
 {  
   document.getElementById("button3").value = "x";
   document.getElementById("button3").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button4").onclick)
 {  
   document.getElementById("button4").value = "x";
   document.getElementById("button4").disabled = true;
   current = "o";
 }
  else if (document.getElementById("button5").onclick)
 {  
   document.getElementById("button5").value = "x";
   document.getElementById("button5").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button6").onclick)
 {  
   document.getElementById("button6").value = "x";
   document.getElementById("button6").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button7").onclick)
 {  
   document.getElementById("button7").value = "x";
   document.getElementById("button7").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button8").onclick)
 {  
   document.getElementById("button8").value = "x";
   document.getElementById("button8").disabled = true;
   current = "o";
 }
 else if (document.getElementById("button9").onclick)
 {  
   document.getElementById("button9").value = "x";
   document.getElementById("button9").disabled = true;
   current = "o";
 }


 if (document.getElementById("button1").onclick)
 {  
   document.getElementById("button1").value = "o";
   document.getElementById("button1").disabled = true;
   current = "x"1;
 }
 else if (document.getElementById("button2").onclick)
 {  
   document.getElementById("button2").value = "o";
   document.getElementById("button2").disabled = true;
   current = "x";
 }
 else if (document.getElementById("button3").onclick)
 {  
   document.getElementById("button3").value = "o";
   document.getElementById("button3").disabled = true;
   current = "x";
 }
 else if (document.getElementById("button4").onclick)
 {  
   document.getElementById("button4").value = "o";
   document.getElementById("button4").disabled = true;
   current = "x";
 }
  else if (document.getElementById("button5").onclick)
 {  
   document.getElementById("button5").value = "x";
   document.getElementById("button5").disabled = true;
   current = "x";
 }
 else if (document.getElementById("button6").onclick)
 {  
   document.getElementById("button6").value = "o";
   document.getElementById("button6").disabled = true;
   current = "x";
 }
 else if (document.getElementById("button7").onclick)
 {  
   document.getElementById("button7").value = "o";
   document.getElementById("button7").disabled = true;
   current = "x";
 }
 else if (document.getElementById("button8").onclick)
 {  
   document.getElementById("button8").value = "o";
   document.getElementById("button8").disabled = true;
   current = "x";
 }
 else if (document.getElementById("button9").onclick)
 {  
   document.getElementById("button9").value = "o";
   document.getElementById("button9").disabled = true;
   current = "x";
 }
}
function CheckWin()
{
 var one = document.getElementById("button1");
 var two = document.getElementById("button2");
 var three = document.getElementById("button3");
 var four = document.getElementById("button4");
 var five = document.getElementById("button5");
 var six = document.getElementById("button6");
 var seven = document.getElementById("button7");
 var eight = document.getElementById("button8");
 var nine = document.getElementById("button9");
//x wins
  if(one=="x" && two=="x" && three=="x")
  {window.alert("player1 has won")}
  if(one=="x" && four=="x" && seven=="x")
  {window.alert("player1 has won")}
  if(one=="x" && five=="x" && nine=="x")
  {window.alert("player1 has won")}
  if(two=="x" && five=="x" && eight=="x")
  {window.alert("player1 has won")}
  if(three=="x" && six=="x" && nine=="x")
  {window.alert("player1 has won")}
  if(three=="x" && five=="x" && seven=="x")
  {window.alert("player1 has won")}
  if(four=="x" && five =="x" && six=="x")
  {window.alert("player1 has won")}
  if(seven=="x" && nine=="x" && eight=="x")
  {window.alert("player1 has won")}
//o wins
  if(one=="o" && two=="o" && three=="o")
  {window.alert("player2 has won")}
  if(one=="o" && four=="o" && seven=="o")
  {window.alert("player2 has won")}
  if(one=="o" && five=="o" && nine=="o")
  {window.alert("player2 has won")}
  if(two=="o" && five=="o" && eight=="o")
  {window.alert("player2 has won")}
  if(three=="o" && six=="o" && nine=="o")
  {window.alert("player2 has won")}
  if(three=="o" && five=="o" && seven=="o")
  {window.alert("player2 has won")}
  if(four=="o" && five =="o" && six=="o")
  {window.alert("player2 has won")}
  if(seven=="o" && nine=="o" && eight=="o")
  {window.alert("player2 has won")}
}
function reset()
{
  one.value=" "
  one.disabled=false
  two.value=" "
  two.disabled=false
  two.value=" "
  three.disabled=false
  three.value=" "
  four.disabled=false
  four.value=" "
  five.disabled=false
  five.value=" "
  six.disabled=false
  six.value=" "
  seven.disabled=false
  seven.value=" "
  eight.disabled=false
  eight.value=" "
  nine.disabled=false
  nine.disabled=false
}
</script>
<html>
<head>
<title> Tic Tac Toe </title>
<link href="https://fonts.googleapis.com/css?family=Acme|Playfair+Display&display=swap" 
rel="stylesheet">
</head>
<body onload = "Start()">

<div id = "Header">
<h1> Tic Tac Toe </h1>
</div>
<div id = "Main">
<table>
<tr> 
<td id="button1"> <input class="button"type="button"onclick ="ChooseSquare()"></td> 
<td id="button2"> <input class="button"type="button"onclick ="ChooseSquare()"></td> 
<td id="button3"> <input class="button"type="button"onclick ="ChooseSquare()"></td> 
</tr>
<tr> 
<td id="button4"> <input class="button"type="button"onclick ="ChooseSquare()"></td> 
<td id="button5"> <input class="button"type="button"onclick ="ChooseSquare()"></td> 
<td id="button6"> <input class="button"type="button"onclick ="ChooseSquare()"></td>
</tr>
<tr> 
<td id="button7"> <input class="button"type="button"onClick ="ChooseSquare()"></td>
<td id="button8"> <input class="button"type="button"onClick ="ChooseSquare()"></td> 
<td id="button9"> <input class="button"type="button"onClick ="ChooseSquare()"></td> 
</tr>
</table>
<input type="button" onClick='reset()' value="reset">
</div>
<div id="Footer" >
<p id = "foot"> Read to Play? Click on a square!</p>
</div>
</body>
</html>
<style>
#Header {
  background-color:Red;
  color:white;
  text-align:center;
  font-family:Acme, Arial, sans-serif;
  padding: 5px;
}
#Main {
  margin-left:200px;
  margin-right:100px;
  padding:0px;
  background-color:white;
}
td {
  width:30px;
  height:70px;
}
#Footer {
  background-color:grey;
  text-align:center;
  color:white;
  font-family:"Playfair Display", "Times New Roman", serif;
  padding:0px;
  font-size:20px;
}
.button {
  height:100px;
  width:100px;
  background-color:purple;
  font-family:Acme, Arial, sans-serif;
  border-color:black;
  border-width:5px;
  color:white;
  font-size:20px;
}
</style>`

phil.o

Вы забыли описать проблему.

1 Ответов

Рейтинг:
2

F-ES Sitecore

На самом деле слишком много нужно сказать. У вас есть свой сценарий и теги стиля вне html-блока, вы должны, по крайней мере, поместить тег сценария в элемент head. У вас есть лишний "1" в коде, который может вызвать ошибку компиляции и остановить любой запуск js.

current = "x"1;


Ваши проверки функций ChooseSquare

if (document.getElementById("button1").onclick)


onclick-это обработчик событий, вы просто спрашиваете, есть ли у button1 обработчик событий click, которого у него нет, поэтому он всегда будет оцениваться как false. Даже если он оценивается как true, код внутри устанавливает значение "button1" в "x", однако "button1" - это строка, а не кнопка, и строка не может иметь значения.

После огромного списка проверок кнопок, которые установлены на x, вы затем делаете то же самое, чтобы установить значение o, но код не делает попыток установить значение "current". В вашем коде слишком много дублирования, которое можно было бы обрабатывать с помощью функций.

Вам нужно выбросить этот код и начать заново с лучшего, более простого дизайна. Дайте каждой кнопке событие щелчка (все они могут использовать одну и ту же функцию для события щелчка), на этом событии щелчка установите значение "this" на "current", а затем измените значение current на "o", если это "x" и "x", если это "o"

JavaScript 'this' и обработчики событий — SitePoint[^]