08.20.12 - 12.16.12
Introduction to Java Programming
Monday Wednesday
04:00 PM - 05:20 PM
Comments placed in each source code file. | 5 pts |
Files put into JAR format. | 5 pts |
Application JAR file is executable | 5 pts |
Application source and class files included. | 5 pts |
Program compiles and executes without errors or exceptions | 10 pts |
Program allows required user inputs | 10 pts |
Program performs required input error checking | 30 pts |
Game executes play correctly and without error | 20 pts |
Computer player uses optimal strategy correctly | 10 pts |
Total | 100 pts |
The assignment is to write a program to play the well-known game of Nim. The game starts with some number of stones in a pile. The players take turns removing either one or two stones at each move. The player who takes the last stone loses.
It is easy to program an optimal strategy for Nim:
Take the remainder of dividing the number of stones left by three; this will be 0, 1, or 2. If it is 0 then take 2 stones; if it is 2, take one stone. If the remainder is 1, then the game cannot be won assuming the opponent is also playing the optimal strategy; however, the program should still put up a good show of it, and take one stone (delaying the inevitable and giving the opponent more chances to make a mistake).
Your program should start out by asking the user for the number of stones to start with, and then asking who moves first (0 = program, 1 = user). It then runs in a loop, alternating turns between the program and the user. The program chooses one or two stones according to the above strategy, and prompts the user for how many stones they wish to take. When the number of stones reaches zero, the program announces a winner.
Note:
An important part of this assignment is input error checking. Your program should check for the following conditions:
If an error is detected, the program should output an appropriate error message and repeat the input request. For this assignment, it is not necessary to check for non-numeric input.
For this lab you will need to be able to allow the user to enter values from the keyboard. To do this you can use either the MyInput class, the Scanner class, or the JOptionPane.showInputDialog( ) method we discussed in class. If you choose to use the MyInput class it can be downloaded below.