在单元格中添加一个字母

时间:2014-12-22 01:19:26

标签: javascript

我想弄清楚如何在单元格中添加一个字母。我正在制作一个匹配的游戏,在我尝试制作之前,所以在单元格中随机实现了一个字母,我想知道如何在页面加载时在单元格中放置一个字母,即使它是预设的而不是随机的。因此,目前我有12个单元格(12个tds),我想这样做,当你点击其中一个单元格时,它会显示该单元格中的字母。有人会知道我会如何开始这个吗?我到目前为止的代码是一个jsfiddle,即使它不是很多我只是想告诉你我的意思。如你所见,我正在努力匹配信件

由于

我想知道的是,当我点击其中一个绿色单元格时,我可以在我提供的数组中的一个字母的框中显示一个字母

http://jsfiddle.net/6c9qg845/

var letters = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"];


<table>
<tr>
    <td id="cell1"></td>
    <td id="cell2"></td>
    <td id="cell3"></td>
    <td id="cell4"></td>
</tr>
<tr>
    <td id="cell5"></td>
    <td id="cell6"></td>
    <td id="cell7"></td>
    <td id="cell8"></td>
</tr>
    <tr>
    <td id="cell9"></td>
    <td id="cell10"></td>
    <td id="cell11"></td>
    <td id="cell12"></td>
</tr>

3 个答案:

答案 0 :(得分:1)

首先,我建议给出从0到11的表格单元格数字,以指示它们应该从数组中得到哪个字母。您可以使用data-属性:

<td data-cell="0"></td>
<td data-cell="1"></td>

然后你可以在游戏开始前使用改组算法来改组字母数组:

function swap(array, pos1, pos2) {
    var temp = array[pos1];
    array[pos1] = array[pos2];
    array[pos2] = temp;
}

// Fisher-Yates shuffle
function shuffle(array) {
    for (var i = array.length - 1; i >= 0; i -= 1) {
        var swapPos = Math.floor(Math.random() * i);
        swap(array, i, swapPos);
    }
}

shuffle(letters);

最后,您可以为表提供ID,并设置事件委派以处理表格单元格上的点击事件:

document.getElementById("board").addEventListener("click", function (e) {
    var target = e.target,
        cellNo;

    if (target && target.tagName === "TD") {
        cellNo = target.getAttribute("data-cell");
        target.className = "revealed";
        target.textContent = letters[cellNo];
    }
});

(并且还添加了一些CSS来垂直居中文本,并在类更改时更改单元格的颜色。)


结果:

&#13;
&#13;
window.onload = function () {
    var letters = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"];

    function swap(array, pos1, pos2) {
        var temp = array[pos1];
        array[pos1] = array[pos2];
        array[pos2] = temp;
    }

    // Fisher-Yates shuffle
    function shuffle(array) {
        for (var i = array.length - 1; i >= 0; i -= 1) {
            var swapPos = Math.floor(Math.random() * i);
            swap(array, i, swapPos);
        }
    }

    shuffle(letters);

    document.getElementById("board").addEventListener("click", function (e) {
        var target = e.target,
            cellNo;

        if (target && target.tagName === "TD") {
            cellNo = target.getAttribute("data-cell");
            target.className = "revealed";
            target.textContent = letters[cellNo];
        }
    });
};
&#13;
td {
    border: 2px solid black;
    width: 100px;
    height: 100px;
    background-color: green;
    text-align: center;
    line-height: 100px;
    font-size: 24pt;
}
td.revealed {
    background-color: white;
}
&#13;
<table id="board">
    <tr>
        <td data-cell="0"></td>
        <td data-cell="1"></td>
        <td data-cell="2"></td>
        <td data-cell="3"></td>
    </tr>
    <tr>
        <td data-cell="4"></td>
        <td data-cell="5"></td>
        <td data-cell="6"></td>
        <td data-cell="7"></td>
    </tr>
    <tr>
        <td data-cell="8"></td>
        <td data-cell="9"></td>
        <td data-cell="10"></td>
        <td data-cell="11"></td>
    </tr>
</table>
&#13;
&#13;
&#13;

http://jsfiddle.net/27kxe8gd/2/

答案 1 :(得分:0)

不太确定你在做什么,但似乎有两个选项可能会有所帮助:

  1. 小提琴HERE - 每次点击一个方格时选择一个随机字母并显示它:

    letters = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"]; $('td').click(function() { rn = Math.round(Math.random()* 12); $(this).html(letters[rn]); });

  2. 小提琴HERE。如果字母是预设的但不可见,则只需更改单击时的不透明度或颜色,以使文本透明(不透明度0)或不透明(不透明度1);或者它的颜色在背景和背景之间切换不同的东西:

    $('td').click(function() { $(this).css('color', 'black'); });

答案 2 :(得分:0)

尝试重建已删除的评论部分。

以下是带注释行的最新代码:

&#13;
&#13;
var letters = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"];
    
    var tds = document.querySelectorAll('td');          // fetch all td elements
    
    for (var i = 0; i < tds.length; i++) {              // loop through them
        tds[i].addEventListener('click', function () {  // add a click listener to each of them
            if (this.textContent == '') {               // check if cell is empty
                var index = Math.floor(Math.random() * letters.length); // if so, get a random index
                this.textContent = letters[index];      // and assign it to the cell
                this.className = 'clicked';             // change the class
            }
        })
    }
&#13;
td {
    border: 2px solid black;
    width: 100px;
    height: 100px;
    background-color: green;
    text-align: center;
}

td.clicked {
    background-color: white;
}
}
&#13;
<table>
    <tr>
        <td id="cell1"></td>
        <td id="cell2"></td>
        <td id="cell3"></td>
        <td id="cell4"></td>
    </tr>
    <tr>
        <td id="cell5"></td>
        <td id="cell6"></td>
        <td id="cell7"></td>
        <td id="cell8"></td>
    </tr>
    <tr>
        <td id="cell9"></td>
        <td id="cell10"></td>
        <td id="cell11"></td>
        <td id="cell12"></td>
    </tr>
</table>
&#13;
&#13;
&#13;

http://jsfiddle.net/6c9qg845/5/


我记得你提到你想检查配对,在这种情况下你需要跟踪每一个&#34;转弯&#34;并比较第一个和第二个单元格if (t1 === t2)的值。


更新

这是一个稍微修改过的,更真实的游戏版本:

&#13;
&#13;
var letters = ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"];

var tds = document.querySelectorAll('td');

for (var i = 0; i < tds.length; i++) {
  var t = tds[i];
  if (t.textContent == '') {
    var index = Math.floor(Math.random() * letters.length);
    t.textContent = letters.splice(index, 1);
    console.log(letters); // notice how splice modifies the array so that all the elements are used exactly once
  }
  //})
}

var turn = 0; // can be used better later, for now used just for keeping track of t1 and t2
var t1, t2;   // tiles

// setup clicks
for (var i = 0; i < tds.length; i++) {
  tds[i].addEventListener('click', function() {
    if (this.className != '') {
      return false; // it has to be a "playable" cell, refuse clicks otherwise
    }
    if (turn % 2 == 0) {  // first tile
      t1 = this;
      this.className = 'clicked';
    } else {              // second tile
      t2 = this;
      this.className = 'clicked';
      setTimeout(function() {   // slight timeout, just looks nicer
        if (t1.textContent == t2.textContent) {     // see if they match
          //alert('it\'s a match!');
          t1.className = t2.className = 'matched';  // assign them this class if they do
        } else {                                    // otherwise

          //alert('no match...');
          t1.className = t2.className = '';         // reset classes

        }
      }, 1000);
    }
    turn++;   // increment turn number (this could easily be a boolean)
  })
}
&#13;
td {
  border: 2px solid black;
  width: 100px;
  height: 100px;
  background-color: green;
  text-align: center;
  color: green;
  transition: all 0.2s linear;
}
td.clicked {
  background-color: white;
}

td.matched {
  background-color: #0F0;
}
&#13;
<table>
  <tr>
    <td id="cell1"></td>
    <td id="cell2"></td>
    <td id="cell3"></td>
    <td id="cell4"></td>
  </tr>
  <tr>
    <td id="cell5"></td>
    <td id="cell6"></td>
    <td id="cell7"></td>
    <td id="cell8"></td>
  </tr>
  <tr>
    <td id="cell9"></td>
    <td id="cell10"></td>
    <td id="cell11"></td>
    <td id="cell12"></td>
  </tr>
</table>
&#13;
&#13;
&#13;

还有很多关于这个的工作:玩家的想法,优化代码(将部件移动到功能中,我给你一个非常原始的版本,试图坚持原始代码),防止各种打破游戏的方式(比如快速点击瓷砖)等等。所有这些都应该足以让你开始。