## Posted By

Sverri on 08/30/10

# Nim (play against PC, without winning algorithm)

/ Published in: Java

nim

`import java.util.Random;import java.util.Scanner; public class Nim{  public static int total;  public static Random generator = new Random();   public static void main(String args[])  {    // Yada yada yada...    System.out.println("This is the game of matches. As long as there are mathes left we alternate");    System.out.println("between taking 1, 2 or 3 matches from the table. The one who takes the last");    System.out.println("match looses. First, however, we need to know how many matches we will play with.\n");    System.out.print("Please enter a number from 25 to 100: ");     // Get answer    Scanner input = new Scanner(System.in);    int num = input.nextInt();    total = (num<25||num>100) ? 25 : num;     // And boom goes the dynamite...    System.out.println("\nOkay. You may start.\n");    do {      System.out.print("Your turn: ");      int response = input.nextInt();      if (response < 1 || response > 3) System.out.print("Not valid. You may only pick 1, 2 or 3 matches!\n");      else {        total -= response;        System.out.println("\nMatches left: " + total); }      myTurn();    } while (total > 1);    if (total == 1) System.out.println("Oh oh, you have to take the last match!. You loose, muhahaha.");    else System.out.println("PC lost...");  }   public static void myTurn()  {    int take;     // Nim algorithm goes here...    // ...     // No algorithm...    take = generator.nextInt(3) + 1;     // Subtract taken matches    total -= take;     // Report back    System.out.println("PC's turn: " + take + "\n");    System.out.println("Total matches: " + total);  } }`