Nim in 38 lines

(See: Nim.)

import java.util.*;
import static java.lang.System.*;

public class Nim {
	static int[] heaps = {3, 4, 5};
	static Scanner sc = new Scanner(in);
	static Random rnd = new Random();

	static void playerMove() {
		int h, n;
		do {
			out.print("Heap to remove from: "); h = sc.nextInt();
			out.print("Number of pieces to remove: "); n = sc.nextInt();
		} while (h < 0 || h >= 3 || n <= 0 || n > heaps[h]);
		heaps[h] -= n;
	}

	static void compMove() {
		int sum = heaps[0] ^ heaps[1] ^ heaps[2], heap = -1, amount = 0, i;
		for (i = 0; i < 3; ++i)
			if ((heaps[i] ^ sum) < heaps[i])
				amount = heaps[heap = i] - (heaps[i] ^ sum);
		while (heap == -1)
			if (heaps[i = rnd.nextInt(3)] > 0)
				amount = 1 + (heaps[heap = i] > 1? rnd.nextInt(heaps[heap = i] - 1) : 0);
		out.printf("Computer removes %d pieces from heap %d\n", amount, heap);
		heaps[heap] -= amount;
	}

	public static void main(String[] _) {
		boolean move;
		for (move = true; heaps[0] + heaps[1] + heaps[2] > 0; move = !move) {
			out.printf("heaps: %s\n", Arrays.toString(heaps));
			if (move) playerMove(); else compMove();
		}
		out.println(move? "You lost!" : "You won!");
	}
}
Posted in Java at April 12th, 2011. No Comments.