Find Us On:

# Game of Nim Java Program

dpatel23

Write a program (GameOfNim.java) in which the computer plays against a human opponent: • Generate a random integer between 10 and 100 to denote the initial size of the pile. • Generate a random integer between 0 and 1 to decide whether the computer or the human takes the first turn. • Generate a random integer between 0 and 1 to decide whether the computer plays smart or stupid. In stupid mode, the computer simply takes a random legal value from the pile whenever it has a turn (i.e., between 1 and n/2, where n is the number ￼of marbles left). In smart mode, the computer takes off enough marbles to make the size of the pile a power of two minus 1—that is, 3, 7, 15, 31, or 63. That is always a legal move, except if the size of the pile is currently one less than a power of two. In that case, the computer makes a random legal move. You will note that the computer cannot be beaten in smart mode when it has the first move, unless the pile size happens to be 15, 31, or 63. Of course, a human player who has the first turn and knows the winning strategy can win against the computer. Hint: Your program must contain a few meaningful methods to manage the complexity of the problem. Focus on and test the correctness of one method before implementing the next method. For example, you may implement a method that computes how many marbles the computer should take when it runs in smart or stupid mode. Think of what kinds of input are required to do this task. You’re free to break down your program into various methods, as long as the methods are logical and useful. Example (user input underlined): The number of marbles = 21 How many marbles do you want to take? 10 <---User Input The number of marbles = 11 Computer took 4 marbles The number of marbles = 7 How many marbles do you want to take? 4 <---- User Input Illegal move: You must take between 1 and 3 marbles How many marbles do you want to take? 3 <---- User Input The number of marbles = 4 Computer took 1 marbles The number of marbles = 3 How many marbles do you want to take? 1 <---- User Input The number of marbles = 2 Computer took 1 marbles One marble left! You lost! Attachments
Tags Clarifications