This is my first time writing a basic program/game in any programming language. It is supposed to a be a Nim game vs a computer with these basic parameters:
- Use
prompt()
to prompt moves and input. - Use
console.log()
draw the board.
The board should look like this:
Pile A: ooooo
Pile B: ooo
Pile C: ooooo
It has been very difficult for me to approach this problem, and I know the logic that I have used is very basic and buggy. Any pointers would be appreciated, whether in the code or my approach to solving the problem in general.
var pileA = {
circles: "ooooo",
print: function() {
console.log("Pile A: " + this.circles);
}
};
var pileB = {
circles: "ooooo",
print: function() {
console.log("Pile B: " + this.circles);
}
};
var pileC = {
circles: "ooooo",
print: function() {
console.log("Pile C: " + this.circles);
}
};
function printBoard(){
console.log("**** Nim ****");
pileA.print();
pileB.print();
pileC.print();
}
function yourMove(){
printBoard();
var moveData = prompt("Type letter of pile and # of o's you are removing.\n" +
"Ex. A1 or C4");
if (moveData[0] == 'A') {
var x = pileA.circles.length - moveData[1];
pileA.circles = pileA.circles.slice(0,x);
return pileA.circles;
} else if (moveData[0] == 'B') {
var x = pileB.circles.length - moveData[1];
pileB.circles = pileB.circles.slice(0,x);
return pileB.circles;
} else if (moveData[0] == 'C') {
var x = pileC.circles.length - (moveData[1]+1);
pileC.circles = pileC.circles.slice(0,x);
return pileC.circles;
}
}
function computersMove() {
printBoard();
alert("Now it is the computer's turn!");
if (pileA.circles != "") {
pileA.circles = pileA.circles.slice(0,0);
return pileA.circles;
} else if (pileB.circles != "") {
pileB.circles = pileB.circles.slice(0,0);
return pileB.circles;
} else if (pileC.circles != "") {
pileC.circles = pileC.circles.slice(0,0);
return pileC.circles;
}
if (pileA.circles == "" &&
pileB.circles == "" &&
pileC.circles == "") {
console.log("Computer Wins!!!");
}
}
while (pileA.circles != "" ||
pileB.circles != "" ||
pileC.circles != "") {
yourMove();
if (pileA.circles == "" &&
pileB.circles == "" &&
pileC.circles == "") {
console.log("You win!!!");
}
if (pileA.circles != "" ||
pileB.circles != "" ||
pileC.circles != "") {
computersMove();
}
}
alert('Game Over!');