gpt4 book ai didi

使用 DOM 的 JavaScript

转载 作者:行者123 更新时间:2023-11-29 14:43:03 25 4
gpt4 key购买 nike

我需要有关 JavaScript 代码的帮助,这里是说明以及我目前所拥有的...

我需要使用 DOM 操作来让 Tic Tac Toe 游戏运行。以下是提供的说明:

  1. 确保当用户点击一个正方形时没有任何反应已经包含一个标记:

    • 从被点击的TD元素中移除onclick属性squareClicked 函数。
    • 在设置新游戏时为每个TD添加onclick属性
    • 从每个具有标记的 TD 中删除 onclick 属性加载游戏时。
  2. 修改 squareClicked 函数,使其:

    • 确保正方形中没有 X 或 O
    • 确定轮到哪个玩家
    • 用正确的类创建一个新的 DIV 元素并将它放在点击 TD(不要使用 innerHTML)
    • 更改当前播放器
  3. 在 setBanner 函数中,检查是否已设置横幅并在设置新的之前删除旧的。

不寻找任何解决方案.. 只是关于如何让代码正常运行的指南。

// set the class name of the player who will start
document.getElementById('X').className = 'current-player';
document.getElementById('O').removeAttribute('class');

// this will run when the page loads
function init() {
var game = [[1,3,5,8],[4,6,7,2]];
// find the tbody element. It is there even though we did not put it in our HTML.
var tbody = document.querySelector('tbody');
// row is a single row element. We will step through the rows in the outer while loop.
var row = tbody.firstChild;
var td;
while(row) {
console.log(row.nodeName);
// td is a single td element. We will step through each td in this row in the inner while loop.
td = row.firstChild;
while(td) {
if(td.tagName === 'TD') {
console.log('Found a TD');
td.setAttribute('onclick', 'squareClicked(this);');
}
td = td.nextSibling;
}
row = row.nextSibling;
}
loadGame(game);
// Step 3: add a "Set Banner" button
var newGameButton = document.querySelector('#players input');
var setBannerButton = document.createElement('input');
setBannerButton.setAttribute('type', 'button');
setBannerButton.setAttribute('onclick', 'setBanner();');
setBannerButton.setAttribute('value', 'Set Banner');

newGameButton.parentNode.insertBefore(setBannerButton,newGameButton);
}

// reset the board when the "New Game" button is clicked
function newGame() {
// create a NodeList of all the td elements, again.
// We could make tdNodes a global variable so we don't have to recreate it.
// Here I use a different method.
var tdNodes = document.querySelectorAll('td');
var removeNode;
for(var i=0; i<tdNodes.length; i++) {
// clear the content of each node
//tdNodes[i].innerHTML = '';
// Step 2: instead of innerHTML, we will use DOM manipulation
removeNode = tdNodes[i].firstChild;
if(removeNode) {
removeNode.parentNode.removeChild(removeNode);
}
}
}

function squareClicked(sqr) {
// show an alert. As a bonus we show which square was clicked.
alert('You clicked square ' + sqr.id);
}

function loadGame(state) {
var tbody = document.querySelector('tbody');
// row is a single row element. We will step through the rows in the outer while loop.
var row = tbody.firstChild;
var td;
var newEl;
while(row) {
console.log(row.nodeName);
// td is a single td element. We will step through each td in this row in the inner while loop.
td = row.firstChild;
while(td) {
if(td.tagName === 'TD') {
console.log('Found a TD');
idNum = td.id;
idNum = idNum.replace('c', ''); // Remove the c at the beginning.
idNum = parseInt(idNum); // Convert it to a number.
// Check to see if it is in the X array, state[0]
if(state[0].indexOf(idNum) > -1){
//td.innerHTML = '<div class="X-marker"></div>';
// Step 1: instead of innerHTML, we will use DOM manipulation
newEl = document.createElement('DIV');
newEl.className = 'X-marker';
td.appendChild(newEl);
}
// Check to see if it is in the O array, state[1]
if(state[1].indexOf(idNum) > -1){
//td.innerHTML = '<div class="O-marker"></div>';
// Step 1 again
newEl = document.createElement('DIV');
newEl.className = 'O-marker';
td.appendChild(newEl);
}
}
td = td.nextSibling;
}
row = row.nextSibling;
}
}

// Step 4: setBanner function
// - Prompt the user to input a title for the game.
// - Create an h1 element to contain this input.
// - Securely (careful of HTML) insert the input into the h1 element and add it to
// the page immediately after the opening body tag.
function setBanner() {
var banner = prompt('Banner Text?');
var h1 = document.createElement('h1');
h1.textContent = banner;
//var body = document.querySelector('body');
var playerDiv = document.querySelector('#players');
//insertBefore (newNode, referenceNode)
document.body.insertBefore(h1, playerDiv);
}
<body onload="init();">  
<div id="players">
<div id="X" class="">Player X</div>
<div id="O" class="">Player O</div>
<input type="button" class="button" value="New Game" onclick="newGame()"/>
</div>
<table>
<tr>
<td id="c0"></td>
<td id="c1"></td>
<td id="c2"></td>
</tr>
<tr>
<td id="c3"></td>
<td id="c4"></td>
<td id="c5"></td>
</tr>
<tr>
<td id="c6"></td>
<td id="c7"></td>
<td id="c8"></td>
</tr>
</table>
<script src="main.js"></script>
</body>

最佳答案

有我很久以前用js做的井字游戏的代码:)

window.onload = function() {
initXO();
}

function initXO() {
var tbl=document.getElementById('xo');
for(var i=0;i<3;i++) {
var row=tbl.insertRow();
for(var x=0;x<3;x++) {
var cell=row.insertCell();
cell.innerHTML='';
cell.setAttribute('onclick','xoCheck(this);');
}
}
}

function xoCheck(ele) {
if (document.getElementById('ovr').value=='0') {
var row=ele.parentNode;
var red=document.getElementById('red');
var br=(row.rowIndex*3)+(ele.cellIndex+1);
var pl;
if(ele.innerHTML=='' || ele.innerHTML=='&nbsp;') {
if(red.value=='0') {
ele.innerHTML='X';
ele.style.color='red';
red.value='1';
pl=document.getElementById('pl1');
} else {
ele.innerHTML='O';
ele.style.color='blue';
red.value='0';
pl=document.getElementById('pl2');
}
pl.value+=br.toString()+',';
checkWinner();
}
}
}

function checkWinner() {
var pl1=document.getElementById('pl1').value.split(',');
var pl2=document.getElementById('pl2').value.split(',');
pl1.pop(); pl2.pop();
pl1=pl1.sort(function(a, b){return a-b});
pl2=pl2.sort(function(a, b){return a-b});
var arr=[];
arr.push('1,2,3');
arr.push('4,5,6');
arr.push('7,8,9');
arr.push('1,4,7');
arr.push('2,5,8');
arr.push('3,6,9');
arr.push('1,5,9');
arr.push('3,5,7');
//var res1=pl1.join();
//var res2=pl2.join();
for (var i=0;i<arr.length;i++) {
//for testing
var qq=arr[i].split(',');
var tot=0;
for (var x=0;x<pl1.length;x++) {
if(pl1[x]==qq[0]) {
tot+=1;
} else if(pl1[x]==qq[1]) {
tot+=1;
} else if(pl1[x]==qq[2]) {
tot+=1
}
if(tot==3) {
var rr=parseInt(document.getElementById('rezPl1').innerHTML)+1;
document.getElementById('rezPl1').innerHTML=rr.toString();
drawResult(arr[i]);
return;
}
}
tot=0;
for (var x=0;x<pl2.length;x++) {
if(pl2[x]==qq[0]) {
tot+=1;
} else if(pl2[x]==qq[1]) {
tot+=1;
} else if(pl2[x]==qq[2]) {
tot+=1
}
if(tot==3) {
var rr=parseInt(document.getElementById('rezPl2').innerHTML)+1;
document.getElementById('rezPl2').innerHTML=rr.toString();
drawResult(arr[i]);
return;
}
}
}
}

function drawResult(result) {
var pp=result.split(',');
document.getElementById('ovr').value='1';
var tbl=document.getElementById('xo');
for(var i=0;i<pp.length;i++) {
var x=parseInt(pp[i]);
if(x>=1 && x<=3) {
tbl.rows[0].cells[x-1].style.backgroundColor='yellow';
}
if(x>=4 && x<=6) {
tbl.rows[1].cells[x-4].style.backgroundColor='yellow';
}
if(x>=7 && x<=9) {
tbl.rows[2].cells[x-7].style.backgroundColor='yellow';
}
}
}

function clearRes() {
document.getElementById('pl1').value='';
document.getElementById('pl2').value='';
document.getElementById('ovr').value='0';
var tbl=document.getElementById('xo');
for (var i=0;i<3;i++) {
for(var x=0;x<3;x++) {
tbl.rows[i].cells[x].innerHTML='';
tbl.rows[i].cells[x].style.backgroundColor='transparent';
}
}
}

function startGame() {
document.getElementById('tdImeX').innerHTML=document.getElementById('txtX').value;
document.getElementById('tdImeO').innerHTML=document.getElementById('txtO').value;
document.getElementById('pl1').value='';
document.getElementById('pl2').value='';
document.getElementById('ovr').value='0';
document.getElementById('red').value='0';
document.getElementById('divLoad').style.display='none';
document.getElementById('divGame').style.display='block';
}

function endGame() {
document.getElementById('tdImeX').innerHTML='';
document.getElementById('txtX').value='';
document.getElementById('tdImeO').innerHTML='';
document.getElementById('txtO').value='';
document.getElementById('pl1').value='';
document.getElementById('pl2').value='';
document.getElementById('ovr').value='0';
document.getElementById('red').value='0';
document.getElementById('divLoad').style.display='block';
document.getElementById('divGame').style.display='none';
document.getElementById('txtX').focus();
}
body, html {margin: 0; padding: 0;}
body
{
font: normal 14px "Trebuchet MS";
color: black;
background-color: #f1f1f1;
}

.wrapper
{
display: block;
width: 250px;
border:solid 1px orange;
margin: 30px auto;
padding: 10px;
}
.inbox
{
width: 100%;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
#xo
{
display: block;
border:solid 1px gray;
width: 94px;
height: 94px;
box-shadow: 2px 2px 8px silver;
margin:0 auto;
}
#xo tr td
{
width: 30px;
height: 30px;
border-right: solid 1px gray;
border-bottom: solid 1px gray;
cursor: pointer;
text-align: center;
vertical-align: middle;
font-size: 18px;
font-weight: bold;
color: black;
}
#xo tr td:last-child
{
border-right:none;
}
#xo tr:last-child td:last-child
{
border-bottom: none;
}

#tblrez
{
margin: 30px 0px;
width: 100%;
box-sizing:border-box;
}
#tblrez td
{
text-align: center;
vertical-align: middle;
font-size: 18px;
border-bottom: solid 1px gray;
width: 50%;
}
#tblrez td:first-child {border-right: solid 1px gray;}
#rezPl1, #rezPl2
{
border-bottom: none !important;
font-size: 22px;
color: navy;
font-weight: bold;
}
#rezPl2
{
color: firebrick;
}

input[type="button"]
{
border:solid 1px navy;
background-color: lightblue;
color: black;
padding: 4px;
cursor: pointer;
border-radius: 4px;
}
input[type="button"]:hover
{
background-color: firebrick;
color:white;
}

.box
{
display: none;
width: 100%;
height: auto;
padding: 10px;
box-sizing:border-box;
}
<input type="hidden" id="pl1" names="pl1" value="" />
<input type="hidden" id="pl2" name="pl2" value="" />
<input type="hidden" id="red" name="red" value="0">
<input type="hidden" id="ovr" name="ovr" value="0">
<div class="wrapper">
<div id="divLoad" style="display:block;" class="box">
<table cellspacing="0" cellspacing="0" class="inbox">
<tr>
<td style="color:firebrick;font-weight:bold;">X</td>
<td><input type="text" id="txtX" value="" placeholder="Player 1" autofocus />
</tr>
<tr>
<td style="color:navy;font-weight:bold;">O</td>
<td><input type="text" id="txtO" value="" placeholder="Player 2" />
</tr>
</table>
<br><br>
<input type="button" value="Start game" onclick="startGame();">
</div>
<div id="divGame" style="display:none;" class="box">
<table cellpadding="0" cellspacing="0" id="xo">
</table>
<table cellpadding="0" cellspacing="0" id="tblrez">
<tr>
<td id="tdImeX">X</td>
<td id="tdImeO">O</td>
</tr>
<tr>
<td id="rezPl1">0</td>
<td id="rezPl2">0</td>
</tr>
</table>
<input type="button" value="New game" onclick="clearRes();" />
<input type="button" value="End game" onclick="endGame();">
</div>
</div>

关于使用 DOM 的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097319/

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