Home > Back-end >  How do I have to change my code so that a 3x3 field is created?
How do I have to change my code so that a 3x3 field is created?

Time:02-15

I wrote a C# blazor program for a tictactoe game. I have a list which contains the entire matchfield consisting of the individual fields.

 MatchField = new List<ElementOfMatchField>();
            for(int i = 0; i < 3; i  )
            {
                for(int j = 0; j < 3; j  )
                {
                    MatchField.Add(new ElementOfMatchField(i, j));
                }
            }

I want to print them using html buttons and using a foreach loop:

<table id="tic-tac-toe">
    <tbody>
        <tr>
            <td>
                @foreach(var matchfield in MatchField)
                {
                    <button>

                    </button>
                }
            </td>
        </tr>
        
    </tbody>
</table>

The problem is, If I print them like this, it will be printed in one row and not in a 3x3 field.

How have I to change the code to print them in a 3x3 field?

CodePudding user response:

 MatchField = new List<List<ElementOfMatchField>> ();
 for (int i = 0; i < 3; i  ) {
   var data = new List<ElementOfMatchField>();
   for (int j = 0; j < 3; j  ) {
     data.Add(new ElementOfMatchField(i, j));
   }
   MatchField.Add(data);
 }
<table id="tic-tac-toe">
  <tbody>
    <tr>
      @foreach(var matchfield in MatchField) {
      <td>
        @foreach(var data in matchfield) {
          <button>
          </button>
        }
      </td>
      }
    </tr>
  </tbody>
</table>

CodePudding user response:

You can use css grid, if you are sure for number of columns, you can get three column layout like this

<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 10px">    
     @foreach(var matchfield in MatchField)
      {
          <button>
          </button>
      }            
</div>

You can set margin around buttons

grid-gap: 10

Can set number of columns in grid with

grid-template-columns: 1fr 1fr 1fr
  • Related