I tried to save a random number, just one time in J.
let Machine = {
position : 0,
num_move : 0,
isEmpty : true,
memory : [],
start : function () {
for (let index = 0; index < 9; index++) {
this.memory.push({move:undefined,isEmpty: true})
}
},
generateMove:function () {
let num = Math.floor((Math.random()*9)+1)
if (num>=10) {
num-=1
}
return num
},
// Update move
move : function () {
let move = this.generateMove()
let prev = this.num_move
if (!this.memory[this.num_move] && this.num_move<=0) {
this.memory[this.num_move]=move
this.num_move+=1
}
},
//Return data values
data : function () {
return {
memory : this.memory,
num_move : this.num_move
}
}
}
The problem is Javascript save a new random number, but i just want to save it once. Like a memory.
Machine.move() //First time
console.log(Machine.data())
// {memory : [2], num_move : 1}
Machine.move() //Second time
console.log(Mahine.data())
// {memory : [9], num_move : 1}
I also tried initialize the Machine Object with start method. And change move method like this. To check if is Empty, before push memory
move : function () {
let move = this.generateMove()
if (this.memory[this.num_move].isEmpty) {
this.memory[this.num_move].isEmpty = false
this.memory[this.num_move].move=move
this.num_move+=1
}
}
but it doesn't work. JS generate a new random number ever whenever i call from console.
I just try it and save the object and got the same result in both turns.
let Machine = {
position : 0,
num_move : 0,
isEmpty : true,
memory : [],
start : function () {
for (let index = 0; index < 9; index++) {
this.memory.push({move:undefined,isEmpty: true})
}
},
generateMove:function () {
let num = Math.floor((Math.random()*9)+1)
if (num>=10) {
num-=1
}
return num
},
// Update move
move : function () {
let move = this.generateMove()
let prev = this.num_move
if (!this.memory[this.num_move] && this.num_move<=0) {
this.memory[this.num_move]=move
this.num_move+=1
}
},
//Return data values
data : function () {
return {
memory : this.memory,
num_move : this.num_move
}
}
}
var obj = Object.create(Machine);
obj.move();
console.log(obj.data());
// {memory : [2], num_move : 1}
obj.move();
console.log(obj.data());
// {memory : [2], num_move : 1}