Monty374

Game of Nim

Oct 24th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. package nimgame;
  2.  
  3. import java.util.Scanner;
  4.  
  5. /**
  6. *
  7. * @author Monty
  8. */
  9. public class NimGame {
  10.  
  11. /**
  12. * @param args the command line arguments
  13. */
  14. public static void main(String[] args) {
  15. int comNum, humanNum, stones, remove;
  16. double randNum;
  17.  
  18.  
  19. randNum = (30 - 15 + 1) * Math.random() + 15;
  20. stones = (int)randNum;
  21. comNum = 0;
  22. humanNum = 0;
  23.  
  24. while (stones > 0) {
  25. remove = humanTurn(humanNum, stones);
  26. stones = remove;
  27.  
  28. if (stones > 0){
  29. remove = comTurn(comNum, stones);
  30. stones = remove;
  31. if (stones <= 0) {
  32. System.out.println("\nPlayer wins.");
  33. }
  34. } else {
  35. System.out.println("\nComputer wins.");
  36. }
  37. }
  38.  
  39.  
  40. }
  41.  
  42. public static int comTurn(int comNum, int stones) {
  43. int remove;
  44. double num = (3 - 1 + 1) * Math.random() + 1;
  45. System.out.print("\nThere are " + stones + " stones. ");
  46. comNum = (int) num;
  47. comLegal(comNum, stones);
  48. remove = stones - comNum;
  49. stones = remove;
  50. System.out.print("The computer takes " + comNum + " stones.");
  51. return(remove);
  52.  
  53. }
  54.  
  55. public static int humanTurn(int humanNum, int stones) {
  56. int remove;
  57. Scanner input = new Scanner(System.in);
  58. System.out.print("\nThere are " + stones + " stones. How many would you like? ");
  59. humanNum = input.nextInt();
  60. humanLegal(humanNum, stones);
  61. remove = stones - humanNum;
  62. stones = remove;
  63. return(remove);
  64. }
  65.  
  66. public static void comLegal(int comNum, int stones) {
  67. if (comNum < 1 || comNum > 3) {
  68. comTurn(comNum, stones);
  69. }
  70. if (stones - comNum < 0) {
  71. comTurn(comNum, stones);
  72. }
  73. }
  74.  
  75. public static void humanLegal(int humanNum, int stones) {
  76.  
  77. if (humanNum < 1 || humanNum > 3) {
  78. humanTurn(humanNum, stones);
  79. }
  80.  
  81. if (stones - humanNum < 0) {
  82. humanTurn(humanNum, stones);
  83. }
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment