Description: Program for matchstick game being played between the computer and the user.It ensures that computer always wins.
Rules for the games are as follows:
1. Number of matchsticks are entered by user.
2. The computer asks the player to pick 1,2 or 3 matchsticks.
3. After the person picks, the computer does its picking and vice versa.
4. Whoever is forced to pick up the last matchstick loses the game.
1. Number of matchsticks are entered by user.
2. The computer asks the player to pick 1,2 or 3 matchsticks.
3. After the person picks, the computer does its picking and vice versa.
4. Whoever is forced to pick up the last matchstick loses the game.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
import java.io.*; class MatchStickGame { private int mSticks; private int choice; Console con = System.console(); public void playComputer() { switch (choice) { case 1: choice = 3; break; case 2: choice = 2; break; case 3: choice = 1; break; } mSticks -= choice; System.out.println("Computer picked:" + choice); System.out.println("No. of matchsticks remaining:" + mSticks); playHuman(); } public void playHuman() { System.out.print("Your turn->Pick the matchsticks:"); choice = Integer.parseInt(con.readLine()); if (choice > 3) { System.out.println("You can pick 1,2 or 3 sticks"); playHuman(); } if ((mSticks - choice) == 0) { System.out.println("You lose"); return; } mSticks -= choice; System.out.println("No. of matchsticks remaining:" + mSticks); playComputer(); } public static void main(String args[]) { MatchStickGame m = new MatchStickGame(); Console com = System.console(); System.out.println("You can pick 1,2 or 3 sticks"); System.out.println("Number of matchsticks to be used:"); m.mSticks = Integer.parseInt(com.readLine()); int turn = (m.mSticks % 4) - 1; if (turn > 0) { m.mSticks -= turn; System.out.println("Computer picked:" + turn); System.out.println("No. of matchsticks remaining:" + m.mSticks); m.playHuman(); } else { m.playHuman(); } } } |
if we enter total matchstick as 4 then if user is picking 3 matchstick then this program will not wrk i guess
Hi Tulsi,
I think there is some rule with the game that the Number of matchsticks should be greater than or equal to 5
Actually if the total matchsticks are 4 then computer would play first as the if block in main method checks for.
I hope that explains your doubt.