/ Assignment / assignment_28.java
assignment_28.java
1 // Question: 2 // Implement a simple Nim game where two players take turns removing 1 to 3 stones from a pile. 3 // The player who removes the last stone wins the game. 4 // Find if you can win the game if number of stones is 0 5 6 import java.util.Scanner; 7 8 public class assignment_28 { 9 public static boolean canWin(int n) { 10 return n % 4 != 0; 11 } 12 public static void main(String[] args) { 13 Scanner scanner = new Scanner(System.in); 14 int stones; 15 16 // Initialize the game with a pile of stones 17 System.out.print("Enter the total number of stones: "); 18 stones = scanner.nextInt(); // Read the total number of stones from user input 19 System.out.println(canWin(stones)); 20 21 while (stones > 0) { // Continue the game until all stones are removed 22 // Player's turn 23 stones = playerMove(scanner, stones); // Player makes a move 24 if (stones == 0) { // Check if the player has won 25 System.out.println("You win!"); 26 break; // End the game if the player wins 27 } 28 29 // Friend's turn (replace with AI if needed) 30 stones = playerMove(scanner, stones); // Friend makes a move 31 if (stones == 0) { // Check if the friend has won 32 System.out.println("Your friend wins!"); 33 break; // End the game if the friend wins 34 } 35 } 36 scanner.close(); // Close the scanner to prevent resource leak 37 } 38 39 // Method for handling a player's move 40 private static int playerMove(Scanner scanner, int stones) { 41 int move; 42 do { 43 System.out.print("Enter number of stones to remove (1-3): "); 44 move = scanner.nextInt(); // Read player's move 45 } while (move < 1 || move > 3 || move > stones); // Ensure move is valid 46 47 stones -= move; // Reduce the number of stones 48 System.out.println("Stones left: " + stones); // Display remaining stones 49 return stones; // Return updated stone count 50 } 51 }