0

I'm creating a tic-tac-toe game in Javascript for an online course. I'm trying to set up various properties within an object literal I'm calling "Game". However, I know that when I start writing the AI functions, I will need to create several instances of a state class that holds board state, score & player info. My question is - how do I create a constructor like this from within my Game object? As an example:

var Game = {  
  board:       [0, 1, 2, 
                3, 4, 5, 
                6, 7, 8],

  // 0 = Empty, 1 = X, 2 = O
  boardState:  [0, 0, 0,
                0, 0, 0,
                0, 0, 0],

  empty:       this.availableMoves(this.board),

  // either "human" or "AI"
  whoseTurn:          "",

  // etc.. other initial properties...
  //
  //

  state: {
     turn :    this.startingPlayer,
     boardState:   this.boardState,
     value:                       0
  }
}

As I understand it right now, "state" is just an object literal within Game that holds static values for the current state of the board. If I wanted to create new instances of state for the purposes of iterating through possible states, though, how might I go about doing that without affecting the current state? Something like:

function changeState(state){
   var state1 = new state();
   // edit state1 object without affecting current state.
}

I was originally thinking of creating an entirely different "State" object for this outside of "Game", but to me that didn't seem to be the right way of going about it since states are part of the game. Any advice would be appreciated!

Nate Kimball
  • 928
  • 8
  • 22
  • [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) – Teemu Feb 17 '16 at 19:31
  • Sounds like a duplicate of [Most elegant way to clone a JavaScript object](http://stackoverflow.com/q/728360/1048572)? – Bergi Feb 17 '16 at 19:31
  • I think you should just use another object literal: `return {turn: changedTurn, boardState: changedBoardState, value: changedValue};` – Bergi Feb 17 '16 at 19:32

0 Answers0