LoginSignup
metaton
@metaton (metaton Go)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

[javascript]オセロで駒の初期配置をしたい

解決したいこと

今オセロを作っていたのですがクリックで駒を置けるところまでは来たのですが、どうすれば真ん中にだけ最初から駒を置いている状態にできるのか悩んでいます。
テーブルをHTMLでたくさん作ればいいのでしょうがどうしても動的に作りたいのでわかる方がいたらお願いします。

javascript

let tarn=0;  
let ban = document.getElementById("table");
let field = [];
window.onload=function ban_new() {
  fieldset();
  for (var x = 0; x < 8; x++) {
  var tr = document.createElement("tr")
  ban.appendChild(tr)
  for (var y = 0; y < 8; y++) {
  var td = document.createElement("td")
  tr.appendChild(td)
  }
  }
  };
  $("#table").on("click","td",selclick);
  $("#reset").click(reset);
  function selclick(){
    if(!($(this).text())){
      if(tarn==0){
        $(this).html("");
        tarn = 1;
      }
      else if(tarn==1){
        $(this).html("");
        tarn = 0;
      }      
    }
  }
  function reset(){
    $("td").html("");
    tarn = 0;
  }

html

<!DOCTYPE html>
<meta http-equiv="content-type" charset="utf-8">
<html>
<head>
<title>オセロ</title>
<style type="text/css">
  td{
    background: rgb(0, 255, 0);
    font-size: 30px;
    color: black;
    width: 50px;
    height: 50px;
    text-align: center;
  }
  body{
    margin: 1;
    padding: 0;
  }
  table{
    border: 5px solid black;
  }
  #reset {
    width: 100px;
    height: 50px;
    background: rgb(0, 255, 179);
    border-radius: 5px;
    border: 1px solid rgb(0, 255, 85);
  }
</style>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>

  <table id="table">
  </table>
  <button id="reset">リセット</button>
  <script src="ocero.js"></script>
</body>
</html>

自分で試したこと

いろいろと調べてみましたがどうもピンと来なかったので質問させていただきました。

0

1Answer

こんな感じでどうでしょう。

function setCell(x, y, n) {
  const cell = document.querySelector(`#table tr:nth-child(${y}) td:nth-child(${x})`);
  if(cell) cell.textContent = ['', ''][n];
}
setCell(4, 4, 1);
setCell(5, 5, 1);
setCell(4, 5, 0);
setCell(5, 4, 0);
0

Comments

  1. @metaton

    Questioner
    素晴らしい回答どうもありがとうございました。
    おかげさまで先に進めました。
    とてもスムーズなコードでありがとうございます。

Your answer might help someone💌