Posted By

Sverri on 08/30/10


Tagged


Versions (?)

Nim (play against PC, without winning algorithm)


 / Published in: Java
 

nim

  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4. public class Nim
  5. {
  6. public static int total;
  7. public static Random generator = new Random();
  8.  
  9. public static void main(String args[])
  10. {
  11. // Yada yada yada...
  12. System.out.println("This is the game of matches. As long as there are mathes left we alternate");
  13. System.out.println("between taking 1, 2 or 3 matches from the table. The one who takes the last");
  14. System.out.println("match looses. First, however, we need to know how many matches we will play with.\n");
  15. System.out.print("Please enter a number from 25 to 100: ");
  16.  
  17. // Get answer
  18. Scanner input = new Scanner(System.in);
  19. int num = input.nextInt();
  20. total = (num<25||num>100) ? 25 : num;
  21.  
  22. // And boom goes the dynamite...
  23. System.out.println("\nOkay. You may start.\n");
  24. do {
  25. System.out.print("Your turn: ");
  26. int response = input.nextInt();
  27. if (response < 1 || response > 3) System.out.print("Not valid. You may only pick 1, 2 or 3 matches!\n");
  28. else {
  29. total -= response;
  30. System.out.println("\nMatches left: " + total); }
  31. myTurn();
  32. } while (total > 1);
  33. if (total == 1) System.out.println("Oh oh, you have to take the last match!. You loose, muhahaha.");
  34. else System.out.println("PC lost...");
  35. }
  36.  
  37. public static void myTurn()
  38. {
  39. int take;
  40.  
  41. // Nim algorithm goes here...
  42. // ...
  43.  
  44. // No algorithm...
  45. take = generator.nextInt(3) + 1;
  46.  
  47. // Subtract taken matches
  48. total -= take;
  49.  
  50. // Report back
  51. System.out.println("PC's turn: " + take + "\n");
  52. System.out.println("Total matches: " + total);
  53. }
  54.  
  55. }

Report this snippet  

You need to login to post a comment.