简体   繁体   中英

How to update a multi-dimensional array with an object on a boardgame

I'm trying to make a boardgame using oop in javascript. (very new to oop). The idea is to have a multi-dimensional array with objects represented by a value or id. I have made a multi-dimensional array to be the board. I have created an object for the players as an example. I can't seem to find a way to:

  1. add the player (and other objects) to the board itself
  2. add the player (and other objects) in a random spot on the board
createPlayers() {
  for (let i = 0; i < players; i++) {
    let players = [new Player("Player 1", 1),
      new Player("Player 2", 2)
    ];
    players.push(m);
  }
}

I've tried using push() in a for loop but I'm not sure if this is correct or anywhere close.

this is what i have that works:

 class Board { constructor(rows, cols) { let Board = []; for (let i = 0; i < rows; i++) { Board[i] = []; for (let j = 0; j < cols; j++) { Board[i][j] = 0; } } return Board } } let m = new Board(10, 10); class Player { constructor(name, id) { this.name = name; this.id = id; } } let players = [new Player("Player 1", 1), new Player("Player 2", 2) ]; 

I get this far - no problem, when I console.table(m) the array shows with 0 as the default

The aim is to have the object (player) represented in the array as the number 1 and 2 and in a random spot.

I can get a random 1's to appear using

board[i][j] = (Math.random() * 2 | 0) + 0; 

in the for loop for the board. but this is fairly useless at this stage as I can't seem to work out how to update the array. any suggestions will be appreciated!

 class Board { constructor(rows, cols) { let Board = []; for (let i = 0; i < rows; i++) { Board[i] = []; for (let j = 0; j < cols; j++) { Board[i][j] = 0; } } return Board } } let totalRows = 10; let totalCols = 10; let m = new Board(totalRows, totalCols); class Player { constructor(name, id) { this.name = name; this.id = id; } } let players = [ new Player("Player 1", 1), new Player("Player 2", 2) ]; players.forEach(function(player){ let row, col, notInserted = true; while (notInserted) { row = Math.floor(Math.random() * 100) % totalRows; col = Math.floor(Math.random() * 100) % totalCols; if (m[row][col] === 0) { m[row][col] = player.id; notInserted = false; } } }); console.log(m); 

Once you have created the board and the players, loop over each player. For each player, get a random row and column number inside the boundary of the board. If that position on the board is 0 , set the player there. If it is not 0 , repeat the random number logic to get another position and continue until one is found that is 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM