Thursday, May 1, 2014

21 Match Sticks Game

21 Match Sticks is a small game. That can be implemented easily in any programming language.

In this game, user/computer needs to pick 1 to 4 sticks and whoever picks the last stick will lose the game.

import java.util.Scanner;

public class MatchSticks21 {

      public static void main(String[] args) {
            int matchstick = 21;
            int user = 0;
            int computer = 0;
            Scanner scanner = new Scanner(System.in);

            while (matchstick >= 1) {

                  if (matchstick == 1) {
                        System.out.println("Match stick status: " + matchstick);
                        System.out.println("\nYou loose!!!!!!:(:(");
                        break;
                  }                            
                  System.out.println("Match stick status: " + matchstick);
                  System.out.println("\nEnter the choice (1,2,3,4)):");
                  user = scanner.nextInt();

                  System.out.println("\nYou picked: " + user);
                  if (user >= 5 || user <= 0) {
                        System.out.println("\nInvalid value");
                        continue;
                  }
                  computer = 5 - user;

                  System.out.println("\nComputer picked " + computer);
                  matchstick = matchstick - computer - user;
            }
      }
}


4 comments:

  1. Why it is like this???
    computer=5-user;
    ???????? Pls explain

    ReplyDelete
    Replies
    1. This is the heart of the program.
      if user picks 1 stick then computer can pick 4 sticks
      that means, 5 (i.e. max+1) sticks will be picked out for each round.
      For 4 rounds, 20 sticks are out and only 1 stick will be left.
      And user picks it, he lose the game.




      Delete