Showing posts with label Game. Show all posts
Showing posts with label Game. Show all posts

Monday, 10 November 2014

Rock, Paper, Scissors Game in JAVA.

The most loved and played game among the children's is here with JAVA. As the game is simple so is the code. It is based on simple switch...case...default. structure. It is programmed by me within 15 mins as the idea came to my mind

Game Play Instructions :
It is simple. Just enter "rock" or "paper" or "scissor" and the program calls the random functions which in turn uses the computers internal clock to get a random value. As we know that the random function in java returns a value greater than 0.00 and less than 1.00 I have multiped the value to get an integer between 1-3 which i used in the switch...case...default.

Snapshot: 

Source Code:

Sunday, 9 November 2014

Spintires Game : Review, Download.

Spintires is a game where you get to operate off-road trucks. These large, heavy trucks are difficult to maneuver and designed to move large cargothrough muddy woodland areas that are difficult to access. It's a tremendously fun game if you have enough patience to control these mechanical giants
Trucks that use 30 liters of fuel per minute 
The aim of Spintires is deceptively simple: move a load of wood from one point to another. Where's the challenge? Well, the paths are full of mud, rivers, vegetation, and "roads" that are covered with dirt. Throw intrucks that are extremely large, heavy, and difficult to maneuver, and you get something that puts your patience to the test. 
These trucks, however, require control so close to that of a real truck, that Spintires is one of the best simulators I've tried in a while. You have to drive very carefully not to get stuck, using four-wheel drive and the differential lock properly. Over time, you'll learn how to use the tow cable when you need it, and you can attach the cable to trees to help get you out of any nasty ditches you might get stuck in.
If things get too difficult, you can always change vehicles and rescue the one that's stuck in the mud (you'll have to do this many times). You may even end up getting both trucks stuck and having to use a third truck to pull them both out. It's a lot of fun, especially when it takes over half an hour for the second truck to arrive.
You also have to control the damage to the vehicle and the amount of gas you use. Some of these monsters use up to 30 liters of fuel per minute! If you run out, you know what to do: call the fuel truck, of course. 
Spintires has five different terrains to play through, all around the same level of difficulty, but very different. Although you have a map to consult, it's not actually all that useful seeing as the game conceals parts of the terrain so that you don't know where to go. It's very important to explore and see what's out there.
You also have different types of truck at your disposal, which you can customize as you gain experience points with extras such as trailers, cranes, larger loads, and fuel tanks.
Driving the trotter truck
Like the trucks in the game, the controls are rugged and difficult. You'll need some time to get used to using the keyboard and mouse to control everything. It does, however, make it possible to accelerate, change direction, and use the crane, all at the same time.
The hardest part is getting used to the strange camera (which you can move using the mouse).
Very realistic in terms of physics
One area where Spintires has surprised everyone is its graphics. You haveincredibly realistic trucks which move, sway, and chug in a believable way that sometimes make you forget you're playing a video game. The same goes for effects like smoke and the movement of the mud (heavy and sticky).
The physics are completely realistic and should be taken into consideration at all times. For example, the weight of the load can sink the truck in the mud if you stop for too long. When you bump into trees and branches, they behave as they would in real life. Overall, Spintires is a very realistic game.
Get ready for the long haul
Spintires is not only very original, but is also very well done at a technical level. The game is quite rugged as far as menus, interface, and controls go, but then again, so are the trucks you are operating. Nevertheless,Spintires is overall a lot of fun, but you do need patience and nerves of steel. 

Snake and Ladder Game in Java ( 2-D Array Concept)


Name of Game : Snake and Ladder

Concept : 2-D Matrix

Instruction to play: This program will simulate a regular snakes and ladders game,where you will befacing the computer. Both start at square 1, and the first one to square 100 wins, The Default presets of Snakes : [54->19] [90->48] [99->77] Ladders : [9->34] [40->64] [67->86]. In simple words, there are some blocks (numbers) which role as sanke and some block(numbers) which role as ladders. If while playing you get that number then the respective happens.

Snapshots:




Coding :


package Games;
import java.io.*; // used to allow user to input data
 
public class Snakes_and_Ladders
{// start class
 
    //Main Method
    public static void main (String [] args) throws IOException
    {   // start main method
     
        //Welcoming Screen
     
        BufferedReader myInput2 = new BufferedReader (new InputStreamReader (System.in));
        // Print the welcome screen and instructions
        System.out.println ("\t\t\t\t\t\t-----------------------------------");
        System.out.println ("\t\t\t\t\t\t|  Welcome To Snakes And Ladders   |");
        System.out.println ("\t\t\t\t\t\t-----------------------------------\n\n");
        System.out.println ("\t\t\t\t\t\t\tInstructions:");
        System.out.println ("\t\t\t\t This program will simulate a regular snakes and ladders game, ");
        System.out.println ("\t\t\t\t where you will befacing the computer. Both start at square 1,");
        System.out.println ("\t\t\t\t and the first one to square 100 wins, The Default presets of");
        System.out.println ("\t\t\t\t Snakes : [54->19] [90->48] [99->77] Ladders : [9->34] [40->64] [67->86] ");
        System.out.println ("\t\t\t\t\t\t\t Good Luck and Have FUN!!!");
        displayBoard();
        String sGame = "y"; // decare variable used to ask user if he wants to play
     
        System.out.print ("Do you want to play? (y/n) :  "); // ask user if we wants to play the game
        sGame = myInput2.readLine (); // reads the user's input into the variable sGame
        System.out.print ("\n\n\n\n\n\n");
        // While the user says yes, go to startGame method
        // startGame is fuction type method, which start the game
        while (sGame.equals ("Y") || sGame.equals ("y"))
        {
            sGame = startGame(sGame); // give startGame a variable to work with
        }
        System.out.println ("\n\n\n\n\t\t\t\t\t\tSEE YA!!");
     
     
    } //end main method
 
    //The method for displaying The game board
    public static void displayBoard()
    {
     
        int counter= 100,iteration=-1; // sets the counter and iteration vaiables to be used in making the board
        System.out.println ("-----------------------------------------------------Game Board--------------------------------------------------------------------");
     
        /*
        This while loop makes the board for the player to visualize what the
        game looks like, it uses a counter to increment or decrement by 1.
        It will also subtract by 9 or 10 when necessary to create a board
        exactly like the one given.
        */
        while (counter > 0){// start while
            if (counter%10 == 0 && counter != 100){// checks if the counter is at a 90, or 80...
                if(iteration==-1)
                {
                    // subtract 9 from the counter
                    // and sets it to start adding by one
                    counter-=9;
                    iteration=1;
                }
                else
                {
                    System.out.print(counter+"\t");
                    counter-=10;
                    iteration=-1; // set the counter to start subtract by ones
                }
                if(counter!=0)
                System.out.print("\n" + counter + "\t"); // just prints out the counter with a line breck
            }
            else
            System.out.print(counter + "\t"); // just prints out the counter
            counter+=iteration; // sets counter to add by iteration
        }// end while
        System.out.println();
        System.out.println ("__________________________________________________________________________________________________________________________________");
    }
 
 
 
    //-------------------------------------------------------------------startGame Method------------------------------------------------------------------------------
 
    /*
    startGame method:
 
    This method is responsible for organizing the game, asking the user to continue playing,
    and setting the important varibales. It will also return a vaule to the main method, which
    will reset the game so the user can play again.
    */
    public static String startGame (String start) throws IOException // Recieves data from the main method
    {// start startGame method
     
        BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
     
        // sets important variables for the game
        // NOTE: These variables will change as the game progresses
     
        int userPosition = 1; // sets the default loaction for user's piece to 1
        int compPosition = 1; // sets the default loaction for computer's piece to 1
        int diceRoll = 0; // creates the first die
        int diceRoll2 = 0; // creates the second die
        int userRoll = 1; // declares what the user rolled
        int compRoll = 1; // declares what the computer rolled
        String playAgain = "y"; // sets the play again variable
     
        // declare all the snakes and ladders in a array
        int snakesLaddersArray [] = new int [6]; // create a 6 element array
        // store the snakes and ladders location in the array
        snakesLaddersArray [0] = 54;
        snakesLaddersArray [1] = 90;
        snakesLaddersArray [2] = 99;
        snakesLaddersArray [3] = 9;
        snakesLaddersArray [4] = 40;
        snakesLaddersArray [5] = 67;
     
     
        while (playAgain.equals ("y") || playAgain.equals ("Y")) // loops while the playAgaim vaiable equals "y" or "Y".
        {// start playAgain While
         
         
            // gets the dice roll for user and computer
            userRoll =  getDice(diceRoll, diceRoll2); // sends data to a function type method called getDice
            compRoll =  getDice(diceRoll, diceRoll2); // does the same for the computer
            System.out.println("__________________________________________________________________________________________________________________________________");
            System.out.println ("\t\t\t\t\t------------------------------------------");
            System.out.println ("\t\t\t\t\t|\tYou Rolled a " + userRoll + "\t\t|"); // print the roll the user got
            System.out.println ("\t\t\t\t\t|\tThe Computer Rolled a " + compRoll + "\t|"); // print the roll the computer got
            System.out.println ("\t\t\t\t\t------------------------------------------");
         
            // hold the user's last position for switching back if current position was greater than 100
            userPosition = userPosition + userRoll;
         
            // hold the computer's last position for switching back if current position was greater than 100
            compPosition = compPosition + compRoll;
         
         
         
            // check to see if user landed on top of a snake or at the bottom of a ladder
            // give getP parameters to work with, and recieve a final value which can be printed out
            userPosition = getP(userPosition, userRoll, snakesLaddersArray);
            // The same goes for compPosition, however compgetP gets an additional
            // parameter (userPosition) to check if user has already won
            compPosition = compgetP(compPosition, compRoll, snakesLaddersArray, userPosition);
         
            System.out.println("\t\t\t*************************************************************************");
            System.out.println ("\t\t\t*\t\tYou are currently on square " + userPosition + "\t\t\t*"); // print out the user's current location
            System.out.println ("\t\t\t*\t\tThe Computer is currently on square " + compPosition + "\t\t*"); // print out the computer's current location
            System.out.println("\t\t\t*************************************************************************");
         
            // resets the position values, if the user or the computer won
            // so that the user could play the entire game again if he/she wanted to
            if (userPosition == 100 || compPosition == 100)
            {
                userPosition = 1;
                compPosition = 1;
                // asks the user if we wants to play again
                System.out.print ("Do you want to play? Y or N     >  ");
                playAgain = myInput.readLine ();
                System.out.print ("\n\n\n\n\n\n\n\n\n\n\n\n");
            }
            else
            {
                // asks the user if we wants to continue playing
                System.out.print ("Do you want to play? Y or N     >  ");
                playAgain = myInput.readLine ();
             
            }
         
         
        }// end playAgain While
     
        return playAgain; // returns prameter "playAgain" to main: if the user wants to play the game again
    }// end startGame method
 
 
 
 
 
 
    //-------------------------------------------------------------------geDice Method------------------------------------------------------------------------------
 
    /*
    getDice method:
 
    This method generates two random numbers bewteen 1 and 6, then
    adds them to get a final roll. Next it returns the value to be
    diplayed on the screen.
    */
    public static int getDice (int diceRoll, int diceRoll2)
    {// start getDies class
        diceRoll = (int)(Math.random()*6 )+1 ; //creates dice roll number 1
        diceRoll2 = (int)(Math.random()*6 )+1 ; //creates dice roll number 2
        int move = diceRoll + diceRoll2; // adds the two dice rolls to get a final move
        return move; // return parameter move: this will give the final dice roll back to startGame
    }// end getDice class
 
 
 
 
    //-------------------------------------------------------------------getP Method------------------------------------------------------------------------------
    /*
    getP method:
 
    This method is responsible for checking if the USER is on
    top of a snake, or at the bottom of a ladder, and then
    adjusting the user's position to mathch the snake or
    ladders value.
    */
    public static int getP (int userPosition, int userRoll, int snakesLaddersArray []) throws IOException // recieves two parameter from startGame
    {// start getP
     
     
        if(userPosition == snakesLaddersArray[0]) //if position equals snake 1
        {
            userPosition = 19; // set new position
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~You Got Bit By A Snake, GO DOWN!!!~~~~~~~~~~~~~");
        }
        else if (userPosition == snakesLaddersArray[1]) //if position equals snake 2
        {
            userPosition = 48; // set new position
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~You Got Bit By A Snake, GO DOWN!!!~~~~~~~~~~~~~");
         
        }
        else if (userPosition == snakesLaddersArray[2]) //if position equals snake 3
        {
            userPosition = 77; // set new position
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~You Got Bit By A Snake, GO DOWN!!!~~~~~~~~~~~~~");
        }
        else if (userPosition == snakesLaddersArray[3]) //if position equals ladder 1
        {
            userPosition = 34; // set new position
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~You Got A Ladder!! GO UP!!!~~~~~~~~~~~~~");
         
        }
        else if (userPosition == snakesLaddersArray[4]) //if position equals ladder 2
        {
            userPosition = 64; // set new position
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~You Got A Ladder!! GO UP!!!~~~~~~~~~~~~~");
         
        }
        else if (userPosition == snakesLaddersArray[5]) //if position equals ladder 3
        {
         
         
            userPosition = 86; // set new position
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~You Got A Ladder!! GO UP!!!~~~~~~~~~~~~~");
        }
     
        if (userPosition < 0 || userPosition > 112) // This is ab ERROR TRAP to catch any unwanted system errors that may occur by chance
        {
            System.out.println ("An error has occured please reset the game!!!!!!");
        }
     
        else if (userPosition > 100) // checks if user's location if greater then a 100
        {
            userPosition = userPosition - userRoll; // subtract userRoll from the userposition to get back old position
            System.out.println ("OHHH You cant jump, you must land on a 100"); // print out the users current location
         
        }
        else if (userPosition == 100)
        {
            System.out.println ("YOU WON, GOOD JOB!!!"); // print out that the user won
         
        }
     
     
     
        return userPosition; // return the final position to starGame: this position had gone through all checks and test and can be displayed on screen
    }// end getP
 
 
 
 
 
 
    //-------------------------------------------------------------------compgetP Method------------------------------------------------------------------------------
 
    /*
    compgetP method:
 
    This method is responsible for checking if the COMPUTER is on
    top of a snake, or at the bottom of a ladder, and then
    adjusting the compuer's position to mathch the snakes or
    ladders value.
    */
 
    public static int compgetP (int compPosition, int compRoll, int snakesLaddersArray [], int userPosition) throws IOException
    {// start compgetP
     
        // NOTE: this method is similar to getP, so the comments are the same for both!!
        // Look at getP's commments if you need help
     
        if(compPosition == snakesLaddersArray[0])
        {
            compPosition = 19;
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~Computer Got Bit By A Snake, HE WENT GO DOWN!!!~~~~~~~~~~~~~");
         
         
        }
        else if (compPosition == snakesLaddersArray[1])
        {
            compPosition = 48;
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~Computer Got Bit By A Snake, HE WENT GO DOWN!!!~~~~~~~~~~~~~");
         
        }
        else if (compPosition == snakesLaddersArray[2])
        {
            compPosition = 77;
            System.out.println ("\t\t\t\t~~~~~~~~~~~~~Computer Got Bit By A Snake, HE WENT GO DOWN!!!~~~~~~~~~~~~~");
        }
        else if (compPosition == snakesLaddersArray[3])
        {
            compPosition = 34;
            System.out.println ("Computer Got TO A Ladder, HE WENT UP!!!");
        }
        else if (compPosition == snakesLaddersArray[4])
        {
            compPosition = 64;
            System.out.println ("Computer Got TO A Ladder, HE WENT UP!!!");
         
        }
        else if (compPosition == snakesLaddersArray[5])
        {
            compPosition = 86;
            System.out.println ("Computer Got TO A Ladder, HE WENT UP!!!");
        }
     
     
        if (compPosition < 0 || compPosition > 112) //  ERROR TRAP to catch any unwanted system errors that may occur by chance
        {
            System.out.println ("An error has occured for the computer, please reset the game!!!!!!");
        }
     
        else if (compPosition > 100) // checks if computers's location if greater then a 100
        {
            compPosition = compPosition - compRoll; // get old position
            System.out.println ("THE COMPUTER CAN'T JUMP!!! He must land on a 100"); // give message that the computer cant jump
         
        }
        else if (compPosition == 100 && userPosition != 100)
        {
            System.out.println ("THE COMPUTER WON, YOU FAILED!!!"); // print out that the computer won
         
        }
     
        return compPosition; // return the final position to starGame: this position had gone through all checks and test and can be displayed on screen
    } // end compgetPy
}//end clas

Tuesday, 4 November 2014

Hangman game in JAVA : BLUEJ

This is a simple game of Hangman created by me in java environment.

How to play ? 
In this game you are given a clue and required number of blank space for your answer. You are given a finite number of chances to fill the blanks with letters step-by-step. I have made this game different from others by making it case-sensitive, that is, "Albert" is different from "albert"

Snapshots from Game Play :


Code:
Click Here to download the code as .rar file
If you don't have an extractor you may download the .txt file from here.. The .txt file consist of 3 classes compile them separately in your java compiler (Bluej). And Enjoy !!!

////////////////////////////////////////////////////////////////////////////////////////////  Main class  
import java.util.Scanner;
/* Created by Shouvik Mitra */
public class hangManProject
{
    public static void main( String[] args) 
    {
        Scanner scan = new Scanner( System.in);
        // VARIABLES
        int totalMistake = 0;
        boolean b = false;
        // PROGRAM CODE
        showWelcome();
        SecretWord word = new SecretWord();
        System.out.println("Your clue: " + word.getClue());
        KeyboardInput input = new KeyboardInput();
        while (totalMistake < 4 && !word.isSolved())
        {
            System.out.println(word);
            char c = input.getNewLetter();
            if (!word.update(c))
                totalMistake = totalMistake + 1 ;
        }
        if (word.isSolved())
            System.out.println("Great, you done it.");
        else
            System.out.println("Sorry, too many errors.");
       
    }
        
        public static void showWelcome()
        {
            System.out.println( "Welcome to Hangman Game !!!" );
        }
        
}

//////////////////////////////////////////////////////////////////////////////////////////// Subsidiary Class 
import java.util.ArrayList;
import java.util.Scanner;

public class KeyboardInput
{   
    // Properties
    ArrayList<String> keyList ; 
    boolean chosen;
    
    //Constructor   
    public KeyboardInput()
    {
        keyList = new ArrayList<String>();
    }
    
    // Adds and stores the entered key in the Arraylist
    public void keyChosen( String key )
    {
        keyList.add( key );
    }
    
    // Checks if the entered key has been chosed before
    public boolean hasBeenChosen( String key)
    {
        chosen = keyList.contains( key );
        return chosen;
    }
    
    
    public char getNewLetter() 
    {
        Scanner scan=new Scanner( System.in);
    
        char a;
        boolean chosen;
        String aTmp;    // used to convert a into a String for compatibility with Group 6
        
        do
        {   
            System.out.println("Enter a Letter");
            a = scan.next().charAt( 0); 
            aTmp = "" + a;
            chosen = hasBeenChosen( aTmp);
            if(!chosen)
                keyChosen( aTmp);
            else
            {   
                System.out.println("You've already used that one. Please enter a new Letter");
                
            }
            
                        
        }
        // we repeat the process until we're out of trials.
        while(chosen);
        
        return a;  
    }
}

////////////////////////////////////////////////////////////////////////////////////// The Class for the Secret Word to Store
public class SecretWord
{
    String clue, visible, secret;

public SecretWord()
{
    String [] wordList = { "Umbrella", "Albert Einstien", "Hangman", "Shouvik Mitra" };
    
    String [] clueList = { "Rainy Season", "One of the greatest Scientist", "Name of this game", "Name of the creator" };
    int rand;
    rand = (int) (Math.random()*4);
    secret = wordList[rand];
    clue = clueList[rand];
    int wordLength = secret.length();
    
    visible = "";
   
    for ( int i = 0; i < secret.length(); i++)
    {
        char c = secret.charAt(i);
        
        if ( c == ' ' )
            visible += c;
        else
            visible += '_';
    }
}

public String getClue()
{
    return clue;
}

public String toString()
{
    // String s = "";
    // for(int i = 0; i < wordLength; i++)
    //    s = s + "_ ";
    // return s;
    
    return visible;
}

    // provided by Group 4 and 8
    public boolean update(char c)
    {
        char[] secretArray = new char [secret.length()];
        char[] visibleArray = new char [secret.length()];
        String s = "";
        boolean contains = false ;
        
        //We make the String secret an array
        for(int i = 0; i < secret.length(); i++)
        {
            secretArray[i] = secret.charAt(i);
            visibleArray[i] = visible.charAt(i);
        }
        
        //We are uptading our empty visible array
        for(int k = 0; k < secret.length();k++)
        {
            
            if(secretArray[k] == c)
            {
                visibleArray[k] = c;
                contains = true;
            }
        }
        //We are changing our visible array into the visible string
        for(int m=0; m < secret.length(); m++ )
        {
            s = s + visibleArray[m];
        }
        visible = s;
        
        return contains;
   }
    //This is a method to check if the secret word is solved
    public boolean isSolved()
    {   
        return secret.equalsIgnoreCase(visible);
    }
}

Click Here to download the code as .rar file
If you don't have an extractor you may download the .txt file from here.. The .txt file consist of 3 classes compile them separately in your java compiler (Bluej). And Enjoy !!!

Friday, 31 October 2014

Angry Birds Transformers

Rovio's mashup of Angry Birds and the
Transformers changes the Angry Bird game
mechanic, but still manages to be very
entertaining.

Wednesday, 1 October 2014

Program involving Chronological logic (GAME OF A THIEF)

     A PROGRAM TO HELP A THIEF.
STORY: a Thief is to robb a house. There are different items of different values and Amounts. 
This is a program to help the thief to take the most valuable items within his capacity.
 This program may seem easy but actually it has a brainstorming logic behind it.

CONCEPT:
                        Eg:
Item1 ($1000)(200kg) , Item2($2000)(100kg) , Item3($300)(200kg)  , Item4($4000)(300kg)

The thief’s capacity is 500kg of items , then he will take
Item4(300kg) , Item2(100kg) , Item1(100kg)

NOTE: Item-weights should be noted not to exceed the capacity.
CODING:
        import java.util.Scanner;
//program to steal most valuable items from a house by AGNIVA
public class Thief
{
    static int W[];
    static int M[];int n;
    static Scanner sc = new Scanner(System.in);
    public Thief(int num){
        n = num;
        W = new int[n];
        M = new int[n];
    }
    public void bblsort(){
        for (int c = 0; c < ( n - 1 ); c++) {
            for (int d = 0; d < n - c - 1; d++) {
                 if (M[d] < M[d+1]) /* For ascending order use < */
                 {
                    int swap  = M[d];
                    int swap2 = W[d];
                     M[d]   =   M[d+1];
                     M[d+1] = swap;
                     W[d]   =   W[d+1];
                     W[d+1] = swap2;
                 }
            }
         }
    }
    public void display(int fin)
    {
        System.out.println("------------------------------------------------------");
        for(int i = 0;i<=fin;i++){
            System.out.println(" STOLEN ITEM having"+(i+1)+"th PREFENCE::"+M[i]);
            System.out.println(" MASS ::"+W[i]+"Kg");
        }
    }
    public void input()
    {
         for(int i = 0;i<n;i++){
            System.out.println("ENTER Amount of item"+(i+1)+" in RUPEES");
            M[i] = sc.nextInt();
            System.out.println("ENTER MASS of item "+(i+1)+" in Kg");
            W[i] = sc.nextInt();
        }
    }
    public int sum(int g){
        int sn = 0;
        for(int i = 0;i<=g;i++){
            sn+= W[i];
        }
        return sn;
    }   
    public static void main(String[] args){
        System.out.println("ENTER NUMBER OF ITEMS");
        int no = sc.nextInt();
        Thief ob = new Thief(no);
        ob.input();
        System.out.println("ENTER THE CAPACITY :");
        int cap = sc.nextInt();
        ob.bblsort();
        int s = 0;int x = no-1;
        do{
            s = ob.sum(x);
            if(s>cap){
                x--;
            }
        }while((s>cap)&&(x>0));
        s = ob.sum(x);
        if(x == 0 && W[0]>cap){
            System.out.println("ITEM"+1+" RUPEES"+M[0]);
            System.out.println("ITEM Wt"+cap+"Kg ");
        }
        else{
            ob.display(x);
            if(s<cap ){
                try{
                int t = cap - s;
                System.out.println("REMAINING ITEM"+(x+2)+"= RUPEES"+M[x+1]);
                System.out.println("ITEM Wt"+t+"Kg ");
               }
               catch(ArrayIndexOutOfBoundsException e){
                   System.out.println("THE CAPACITY EXCEEDS THE OVERALL WEIGHTS");
                }
            }
        }
        System.out.println("ALL THESE ITEMS SHOULD BE STOLEN");
    }
}
SNAPSHOTS:




Monday, 29 September 2014

TicTacToe Real-Time Game in Java

Tic-Tac-Toe REAL TIME GAME IN JAVA
                        by AGNIVA MUKHOPADHYAY
                        This is a simple  game of criss – cross which I brought out using Java.
You have to enter the row-number and column number of the grid. Well the computer does not have any intelligence. But still it never misses it’s turn.
  There is a very interesting logic behind it using Math.random() class. You can understand it by  seeing the coding . And  also be careful with  logic of decision making regarding the winner.

FINALLY,enjoy the game…..

Snapshots of the game





CODE……..
//coded by AGNIVA MUKHOPADHYAY
import java.io.*;
public class TicTacToe
{
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static String a[][] = new String [3][3];
   
    public void displayScreen(){
        
        System.out.println("   0 1 2  "); 
        System.out.println("  0_|_|_   ");
        System.out.println("  1_|_|_   ");
        System.out.println("  2 | |    ");
        System.out.println(" IMAGINE THIS AS A GRID OF TICTACTOE  ");
    }
    public static void main(String args[])throws IOException
    {
        TicTacToe ob = new TicTacToe();
        for( int t = 0;t<3;t++){
            for( int y = 0;y<3;y++){
                a[t][y] = " ";
            }
        }
        System.out.println(" ENTER THE RESPECTIVE POSITION U CHOOSE & WAIT FOR THE COMPUTER'S TURN   ");
       
        for( int i = 0;i<4;i++){
            ob.displayScreen();
            // user's turn
            System.out.print("ENTER THE ROW NUMBER :");
            int r = Integer.parseInt(br.readLine());
            System.out.println();
            System.out.print("ENTER THE COLUMN NUMBER :");
            int c = Integer.parseInt(br.readLine());
            System.out.println();
            a[r][c] = "x";
            // computer's turn
            int co = 0;
            do{
             int r1 = (int)(Math.random()*3);
             int c1 = (int)(Math.random()*3);
             if(a[r1][c1] == " "){
                 a[r1][c1] = "o";co = 1;
             }
             else{
                 co = 0;
             }
            }while(co == 0);
            // the result per step
             System.out.println("\f");
            for( int t1 = 0;t1<3;t1++){
              for( int y1 = 0;y1<3;y1++){
                System.out.print(a[t1][y1]);
               
              }
               System.out.println();
           }
           if(ob.validity() || ob.negativity()){
               break;
            }
           System.out.println("______________________________________________________");
        }
        if(ob.validity()){
            System.out.print("YOU WON");
        }
        else if(ob.negativity()){
            System.out.print("YOU LOSE");
        }
        else{
            System.out.print("IT's A TIE");
        }
    }
    public boolean validity(){
        String valid = "";boolean f = false;
        for(int i = 0;i<3;i++){
            for(int j = 0;j<3;j++){
                valid += a[j][i];
            }
            if(xcount(valid,'x') == 3){
                f = true;
            }
            valid = "";
            for(int j = 0;j<3;j++){
                valid += a[i][j];
            }
            if(xcount(valid,'x') == 3){
                f = true;
            }
            valid = "";
        }
        if((a[0][2].equals("x") && a[1][1].equals("x") && a[2][0].equals("x"))||(a[0][0].equals("x") && a[1][1].equals("x") &&  a[2][2].equals("x"))){
            f = true;
        }
        return f;
    }
    public boolean negativity(){
        String valid = "";boolean f = false;
        for(int i = 0;i<3;i++){
            for(int j = 0;j<3;j++){
                valid += a[j][i];
            }
            if(xcount(valid,'o') == 3){
                f = true;
            }
            valid = "";
            for(int j = 0;j<3;j++){
                valid += a[i][j];
            }
            if(xcount(valid,'o') == 3){
                f = true;
            }
            valid = "";
        }
        if((a[0][2].equals("o") && a[1][1].equals("o") && a[2][0].equals("o"))||(a[0][0].equals("o") && a[1][1].equals("o") &&  a[2][2].equals("o"))){
            f = true;
        }
        return f;
       
    }
    public int xcount(String s,char d){
        int n = 0;
        for(int i = 0;i<s.length();i++){
            char c = s.charAt(i);
            if(c == d){
                n++;
            }

        }
        return n;
    }
    public void input()throws IOException
    {
        for( int t = 0;t<3;t++){
            for( int y = 0;y<3;y++){
                System.out.println("Enter a String(x/o)");
                a[t][y] = br.readLine();
            }
        }
        for( int t = 0;t<3;t++){
            for( int y = 0;y<3;y++){
                System.out.print( a[t][y]+" ");
            }
            System.out.println();
        }
    }

}