Cornelius Eanes's Programming Portal
Assignments (Project 2)
[Project 2] Nim

Goal: Recreate the game of Nim. Two players, three piles of some amount of tokens. The player to remove the last token is the loser.

/// Name: Cornelius Eanes
/// Period: 5
/// Program Name: Nim
/// File Name: Nim.java
/// Date Finished: Mar 4, 2016

import java.util.Scanner;

public class Nim {

    public static void main(String[] args) {

        Scanner userIn = new Scanner(System.in);

        int pileA = 10, pileB = 10, pileC = 10, amountToRemove;
        String player1, player2, choice;
        boolean player1Turn = true;

        System.out.print("Player 1, enter your name: ");
        player1 = userIn.next();
        System.out.print("Player 2, enter your name: ");
        player2 = userIn.next();

        while (pileA > 0 || pileB > 0 || pileC > 0) {
            System.out.println("\n\tA: " + pileA + "\tB: " + pileB + "\tC: " + pileC + "\n");
            if (player1Turn) {
                System.out.print(player1);
            } else {
                System.out.print(player2);
            }
            System.out.print(", choose a pile: ");
            choice = userIn.next();
            System.out.print("How many tokens to remove? ");
            amountToRemove = userIn.nextInt();

            if (amountToRemove < 0) {
                System.out.println("ERROR: Cannot remove 0 or a negative amount of tokens.");
                continue;
            }

            if (choice.equalsIgnoreCase("A")) {
                int result = pileA - amountToRemove;
                if (result < 0) {
                    System.out.println("Invalid resulting amount: " + result);
                    continue;
                }
                pileA = result;
            } else if (choice.equalsIgnoreCase("B")) {
                int result = pileB - amountToRemove;
                if (result < 0) {
                    System.out.println("Invalid resulting amount: " + result);
                }
                pileB = result;
            } else if (choice.equalsIgnoreCase("C")) {
                int result = pileC - amountToRemove;
                if (result < 0) {
                    System.out.println("Invalid resulting amount: " + result);
                    continue;
                }
                pileC -= amountToRemove;
            } else {
                System.out.println("Invalid choice: " + choice);
                // skips switching turns
                continue;
            }
            player1Turn = !player1Turn;
        }

        if (player1Turn) {
            System.out.print(player1);
        } else {
            System.out.print(player2);
        }
        System.out.println(", looks like there aren't any tokens left, that means you're the winner!");

    }

}

Output