Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
02-26-2014, 07:32 PM #1
- Join Date
- Feb 2014
- Thanked 0 Times in 0 Posts
"In the 21 game, two players start with a pile of 21 stones. The players take turns removing from one to three stones from the pile. The player that removes the last stone is the game's loser.
When you write your program, it is meant to make the first move. Write it so that it picks up from one to three stones per each turn. Use this code:
computerMove = Math.floor(Math.random()* 3 +1;
Your program should then ask the player how many stones she wishes to remove. Repeat this back and forth until all 21 stones are gone."
02-26-2014, 07:56 PM #2
- Join Date
- Jun 2002
- London, England
- Thanked 2,593 Times in 2,571 Posts
However, I'll give you a push forward:-
Note that your random number code is missing a closing bracket. Should be computerMove = Math.floor(Math.random()* 3 +1);
If the computer is intelligent it will try to leave just one stone for the player to be forced to take.
In other words its choice will not be random if there are 2-4 stones left. The computer will take numstones - 1 (leaving one for the player to take). So in this situation the computer will always win.
For further help you must write at least a good chunk of the remaining code.
Be aware that prompts and alerts are obsolete as ways of obtaining and displaying data but I expect that your professor wishes you to use them at this early stage. So prefer to use IE as your browser.
Quizmaster: Evelyn Waugh was a famous female cricketer. True or false?
Last edited by Philip M; 02-27-2014 at 09:06 AM.
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
03-04-2014, 01:35 AM #3
- Join Date
- Sep 2005
- Sydney, Australia
- Thanked 708 Times in 697 Posts
So 4 stones the first player takes three and the second has to take the last stone and so loses.
5 stones the second player always wins.
6 stones the first player takes one and wins.
7 stones the first player takes 2 and wins.
8 stones the first player takes 3 and wins
9 stones the second player wins
and so on with the second player being the winner whenever the number is a multiple of 4 plus one. So with 21 stones the second player always wins - unless they make a mistake).
As the computer goes first and removes randomly one to three stones each time all the player has to do is to subtract the number the computer removed from four and remove that many as their go in order to leave the last stone for the computer. No matter what move the computer selects starting with 21, it will only win if the player makes a mistake.
I think having the computer go second in that situation and have it set to play the correct move instead of a random one would make a far more interesting coding exercise.