Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package nimgame;
- import java.util.Scanner;
- /**
- *
- * @author Monty
- */
- public class NimGame {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- int comNum, humanNum, stones, remove;
- double randNum;
- randNum = (30 - 15 + 1) * Math.random() + 15;
- stones = (int)randNum;
- comNum = 0;
- humanNum = 0;
- while (stones > 0) {
- remove = humanTurn(humanNum, stones);
- stones = remove;
- if (stones > 0){
- remove = comTurn(comNum, stones);
- stones = remove;
- if (stones <= 0) {
- System.out.println("\nPlayer wins.");
- }
- } else {
- System.out.println("\nComputer wins.");
- }
- }
- }
- public static int comTurn(int comNum, int stones) {
- int remove;
- double num = (3 - 1 + 1) * Math.random() + 1;
- System.out.print("\nThere are " + stones + " stones. ");
- comNum = (int) num;
- comLegal(comNum, stones);
- remove = stones - comNum;
- stones = remove;
- System.out.print("The computer takes " + comNum + " stones.");
- return(remove);
- }
- public static int humanTurn(int humanNum, int stones) {
- int remove;
- Scanner input = new Scanner(System.in);
- System.out.print("\nThere are " + stones + " stones. How many would you like? ");
- humanNum = input.nextInt();
- humanLegal(humanNum, stones);
- remove = stones - humanNum;
- stones = remove;
- return(remove);
- }
- public static void comLegal(int comNum, int stones) {
- if (comNum < 1 || comNum > 3) {
- comTurn(comNum, stones);
- }
- if (stones - comNum < 0) {
- comTurn(comNum, stones);
- }
- }
- public static void humanLegal(int humanNum, int stones) {
- if (humanNum < 1 || humanNum > 3) {
- humanTurn(humanNum, stones);
- }
- if (stones - humanNum < 0) {
- humanTurn(humanNum, stones);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment