Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialErmin Bicakcic
5,144 PointsFor more than 2 players would this work?
So what I am trying to figure out is what if we have a game of let's say 4 players or more... And I wanna go through this with a for loop to add all of the things dynamically.
And what would be the correct approach to do the thing I have in mind?
class Game {
constructor(){
this.board = new Board();
this.players = this.createPlayers(4);
this.ready = false;
}
createPlayers(num){
const players = new Player();
for(let i = 0 ; i < this.players; i++) {
this.name = `Player ${num}`;
this.id += 1;
this.color = "#"+((1<<24)*Math.random()|0).toString(16);
if( players < 1 ) {
this.active = active;
} else {
this.active = false;
}
}
return players;
}
}
1 Answer
Steven Parker
231,269 PointsHere's a few hints:
- you probably want "players" to be an array of objects, but it's being set to a single instance of "Player"
- the loop iterations should be limited by "num" instead of "this.players"
- remember that "createPlayers" is being called before "this.players" gets created
- the player number would be "i" (the loop index) instead of "num" (the total players)
- "this" would represent the instance of "Game" and not an individual player
- if "players" is an array (or even if it is an object) you wouldn't compare it to a number