Results 1 to 3 of 3
  1. #1
    Blue Energy is offline Member
    Join Date
    May 2011
    Location
    Right Behind You
    Posts
    2
    Rep Power
    0

    Unhappy Help me? Class final project.

    Hello everyone, I am Blue Energy. I have created this account to get what help I can with my current java code. Currently, things I want to do is make a text based game like zork in java. I have gotten the code from here and edited it myself. I would like help on how to make an inventory as well as I want it so that when you leave a room, depending on what room you are in and what direction you are going you will get different answers if there is no available room (null). I am trying to get a lockpick to be in the bird's nest once you further examine it. The Bird's nest should be a container item with one space. The lockpick is later used on the south side of the house. From this, I plan to learn how to use similar methods in things like doors, trapdoors, and ladders. (Things that only are abled to be used after a certain point in the game is passed).

    Java Code:
    package GameHopp;
    /**
     * This class holds information about a command that was issued by the user.
     * A command currently consists of two strings: a command word and a second
     * word (for example, if the command was "take map", then the two strings
     * obviously are "take" and "map").
     * 
     * The way this is used is: Commands are already checked for being valid
     * command words. If the user entered an invalid command (a word that is not
     * known) then the command word is <null>.
     *
     * If the command had only one word, then the second word is <null>.
     *
     * The second word is not checked at the moment. It can be anything. If this
     * game is extended to deal with items, then the second part of the command
     * should probably be changed to be an item rather than a String.
     */
    
    class Command
    {
        private String commandWord;
        private String secondWord;
    
        /**
         * Create a command object. First and second word must be supplied, but
         * either one (or both) can be null. The command word should be null to
         * indicate that this was a command that is not recognized by this game.
         */
        public Command(String firstWord, String secondWord)
        {
            commandWord = firstWord;
            this.secondWord = secondWord;
        }
    
        /**
         * Return the command word (the first word) of this command. If the
         * command was not understood, the result is null.
         */
        public String getCommandWord()
        {
            return commandWord;
        }
    
        /**
         * Return the second word of this command. Returns null if there was no
         * second word.
         */
        public String getSecondWord()
        {
            return secondWord;
        }
    
        /**
         * Return true if this command was not understood.
         */
        public boolean isUnknown()
        {
            return (commandWord == null);
        }
    
        /**
         * Return true if the command has a second word.
         */
        public boolean hasSecondWord()
        {
            return (secondWord != null);
        }
    }

    Java Code:
    package GameHopp;
    /*
     * This class holds an enumeration of all command words known to the game.
     * It is used to recognise commands as they are typed in.
     *
     * This class is part of the "GameHopp" game.
     */
    
    class CommandWords
    {
        // a constant array that holds all valid command words
        private static final String validCommands[] = {
            "go", "quit", "help"
        };
    
        /**
         * Constructor - initialise the command words.
         */
        public CommandWords()
        {
            // nothing to do at the moment...
        }
    
        /**
         * Check whether a given String is a valid command word. 
         * Return true if it is, false if it isn't.
         **/
        public boolean isCommand(String aString)
        {
            for(int i = 0; i < validCommands.length; i++)
            {
                if(validCommands[i].equals(aString))
                    return true;
            }
            // if we get here, the string was not found in the commands
            return false;
        }
    
        /*
         * Print all valid commands to System.out.
         */
        public void showAll() 
        {
            for(int i = 0; i < validCommands.length; i++)
            {
                System.out.print(validCommands[i] + "  ");
            }
            System.out.println();
        }
    }

    Java Code:
    package GameHopp;
    /**
     * Class Game - the main class of the "GameHopp" game.
     * 
     *  This class is the main class of the "GameHopp" application. GameHopp is a very
     *  simple (it won't be later), text based adventure game.  Users can walk around some scenery.
     *  That's all. It should really be extended to make it more interesting!
     * 
     *  To play this game, create an instance of this class and call the "play"
     *  routine.
     * 
     *  This main class creates and initializes all the others: it creates all
     *  rooms, creates the parser and starts the game.  It also evaluates the
     *  commands that the parser returns.
     */
    
    class Game 
    {
        private Parser parser;
        private Room currentRoom;
            
    
        /**
         * Create the game and initialize its internal map.
         */
        public Game() 
        {
            createRooms();
            parser = new Parser();
        }
    
        /**
         * Create all the rooms and link their exits together.
         */
        private void createRooms()
        {
            Room forestPath, inATreeFirstLevel, inATreeSecondLevel, topOfTree, hangingTree, riverbank, cliffFace, lake, forestPath2, deepWoods, eastOfHouse, northOfHouse, westOfHouse, southOfHouse;
          
            // create the rooms
            forestPath = new Room("\nForest Path:\nYou are surrounded by trees on all sides.\nThere is a path leading to the North and to the South.\nThere is a tree here that looks climbable.");
            inATreeFirstLevel = new Room("\nIn a Tree:\nYou have climbed the tree. You cannot see much as you are not too far off the ground.\nYou can climb higher in the tree or go back down to the forest floor.");
            inATreeSecondLevel= new Room("\nIn a Tree:\nYou are high up in the tree now. You see a house far to the East. You may be able to get to this house\nby going north along the path. There are some more branches leading toward the top of the tree,\nbut it would be near impossible to get back down.");
            topOfTree = new Room("\nTop of Tree:\nYou have climbed to the top of the tree. Being this high up in the tree makes your thinking clouded.\nYou see a Bird's nest here. There seems to be something inside. There are a few trees that you may be\nable to jump to in a sideways direction from here allowing safe passage to the ground.");
            hangingTree= new Room("\nTree Branch:\nYou jump to a tree and it was much further away then you thought. You almost lose your grip and are\nhanging from the tree. Dropping from here would be safe.");
            riverbank = new Room("\nRiverbank:\nYou followed the path to where you are brought to a large river. The sides are covered in mud.\nIn the mud there seems to be a handle of some sort.");
            cliffFace = new Room("\nCliff Face:\nYou follow the river West and come to a rocky ledge. You do not see many handholds \nso it would be hard to climb it. Looking up you see a rope ladder that has yet to be let down.");
            lake = new Room("\nLake:\nYou follow the river East and come to a large lake. Where the water is coming\nfrom to flow down the river is unknown.");
            forestPath2 = new Room("\nForest Path:\nThe path you were following is starting to veer off to the East, yet there seems to be a \nfaint path still to the North. It seems to be getting darker towards the North.");
            deepWoods = new Room("\nDeep Woods:\nThe light is starting to fade all around you as you go deeper into the woods. You see a \ncave further North. You have a feeling of unease pass over you.");
            eastOfHouse = new Room("\nEast of House:\nYou happen to come upon a house. The door seems to be on the south side.\nThe windows are boarded up and it looks as if no one has lived here for a long time.");
            northOfHouse = new Room("\nNorth of House:\nYou see a wall with some letters written on it. is says\n\"Welcome to GameHopp\"");
            westOfHouse = new Room("\nWest of House:\nThe boarded up windows allow for no possible entry into the house. Try the South side.");
            southOfHouse = new Room("\nSouth of House:\n There is a door on this side of the house. if you had a lockpick, you \ncould try to pick the lock.");
            /* = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");
             = new Room("");*/
            
            // initialise room exits
            forestPath.setExits(forestPath2, null, riverbank, null, inATreeFirstLevel, null, null);
            inATreeFirstLevel.setExits(null, null, null, null, inATreeSecondLevel, forestPath, null);
            inATreeSecondLevel.setExits(null, null, null, null, topOfTree, inATreeFirstLevel, null);
            topOfTree.setExits(null, null, null, null, null, null, hangingTree);
            hangingTree.setExits(forestPath, forestPath, forestPath, forestPath, null, forestPath, null);
            riverbank.setExits(forestPath, lake, null, cliffFace, null, null, null);
            cliffFace.setExits(null, riverbank, null, null, null, null, null);
            lake.setExits(null, null, null, riverbank, null, null, null);
            forestPath2.setExits(deepWoods, eastOfHouse, forestPath, null, null, null, null);
            deepWoods.setExits(null, null, forestPath2, null, null, null, null);
            eastOfHouse.setExits(northOfHouse, null, southOfHouse, forestPath2, null, null, null);
            northOfHouse.setExits(null, eastOfHouse, null, westOfHouse, null, null, null);
            westOfHouse.setExits(northOfHouse, null, southOfHouse, null, null, null, null);
            southOfHouse.setExits(null, eastOfHouse, null, westOfHouse, null, null, null);
            /*.setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);
            .setExits(null, null, null, null, null, null, null);*/
    
    
    
    
            currentRoom = forestPath;  // start game outside
        }
    
        /**
         *  Main play routine.  Loops until end of play.
         */
        public void play() 
        {            
            printWelcome();
    
            // Enter the main command loop.  Here we repeatedly read commands and
            // execute them until the game is over.
                    
            boolean finished = false;
            while (! finished)
            {
                Command command = parser.getCommand();
                finished = processCommand(command);
            }
            System.out.println("Thank you for playing.  Good bye.");
        }
    
        /**
         * Print out the opening message for the player.
         */
        private void printWelcome()
        {
            System.out.println();
            System.out.println("Welcome to GameHopp!");
            System.out.println("GameHopp is a new, incredibly boring adventure game.");
            System.out.println("Type go and a direction to play. \nUnfortunatly, items have not yet been implemented.");
            System.out.println();
            System.out.println(currentRoom.longDescription());
        }
    
        /**
         * Given a command, process (that is: execute) the command.
         * If this command ends the game, true is returned, otherwise false is
         * returned.
         */
        private boolean processCommand(Command command) 
        {
            if(command.isUnknown())
            {
                System.out.println("I don't know what you mean...");
                return false;
            }
    
            String commandWord = command.getCommandWord();
            if (commandWord.equals("help"))
                printHelp();
            else if (commandWord.equals("go"))
                goRoom(command);
            else if (commandWord.equals("quit"))
            {
                if(command.hasSecondWord())
                    System.out.println("Quit what?");
                else
                    return true;  // signal that we want to quit
            }
            return false;
            /*else if (commandWord.equals("use"))
                inventoryUsed(item);
            return false;*/
        }
    
        // implementations of user commands:
    
        /**
         * Print out some help information.
         * Here we print some stupid, cryptic message and a list of the 
         * command words.
         */
        private void printHelp() 
        {
            System.out.println("You have awoken in a forest. You are alone.");
            System.out.println();
            System.out.println("Your command words are:");
            parser.showCommands();
        }
    
        /** 
         * Try to go to one direction. If there is an exit, enter the new
         * room, otherwise print an error message.
         */
        private void goRoom(Command command)
        {
            if(!command.hasSecondWord())
            {
                // if there is no second word, we don't know where to go...
                System.out.println("Go where?");
                return;
            }
    
            String direction = command.getSecondWord();
    
            // Try to leave current room.
            Room nextRoom = currentRoom.nextRoom(direction);
    
            if (nextRoom == null)
                System.out.println("This direction has not yet been implemented.\nPlease try another!");
            else 
            {
                currentRoom = nextRoom;
                System.out.println(currentRoom.longDescription());
            }
        }
        private void inventoryUsed(Command useItem)
        {
            if(!useItem.hasSecondWord())
            {
                // if there is no second word, we don't know what to use...
                System.out.println("Use what?");
                return;
            }
    
            String item = useItem.getSecondWord();
    
            // Use item on specified object.
        }
    }

    Java Code:
    package GameHopp;
    /* 
     * This class is part of GameHopp. GameHopp is a simple, text based adventure game.
     *
     * This parser reads user input and tries to interpret it as a "GameHopp"
     * command. Every time it is called it reads a line from the terminal and
     * tries to interpret the line as a two word command. It returns the command
     * as an object of class Command.
     *
     * The parser has a set of known command words. It checks user input against
     * the known commands, and if the input is not one of the known commands, it
     * returns a command object that is marked as an unknown command.
     */
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.StringTokenizer;
    
    class Parser 
    {
    
        private CommandWords commands;  // holds all valid command words
    
        public Parser() 
        {
            commands = new CommandWords();
        }
    
        public Command getCommand() 
        {
            String inputLine = "";   // will hold the full input line
            String word1;
            String word2;
    
            System.out.print("> ");     // print prompt
    
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(System.in));
            try {
                inputLine = reader.readLine();
            }
            catch(java.io.IOException exc) {
                System.out.println ("There was an error during reading: "
                                    + exc.getMessage());
            }
    
            StringTokenizer tokenizer = new StringTokenizer(inputLine);
    
            if(tokenizer.hasMoreTokens())
                word1 = tokenizer.nextToken();      // get first word
            else
                word1 = null;
            if(tokenizer.hasMoreTokens())
                word2 = tokenizer.nextToken();      // get second word
            else
                word2 = null;
    
            // note: we just ignore the rest of the input line.
    
            // Now check whether this word is known. If so, create a command
            // with it. If not, create a "nil" command (for unknown command).
    
            if(commands.isCommand(word1))
                return new Command(word1, word2);
            else
                return new Command(null, word2);
        }
    
        /**
         * Print out a list of valid command words.
         */
        public void showCommands()
        {
            commands.showAll();
        }
    }

    Java Code:
    package GameHopp;
    /*
     * Class Room - a room in an adventure game.
     * 
     * This class is part of GameHopp. GameHopp is a simple, text based adventure game.
     *
     * "Room" represents one location in the scenery of the game.  It is 
     * connected to at most four other rooms via exits.  The exits are labelled
     * north, east, south, west.  For each direction, the room stores a reference
     * to the neighbouring room, or null if there is no exit in that direction.
     */
    
    import java.util.HashMap;
    
    class Room 
    {
        private String description;
        private HashMap exits;        // stores exits of this room.
    
        /**
         * Create a room described "description". Initially, it has no exits.
         * "description" is something like "a kitchen" or "an open court yard".
         */
        public Room(String description) 
        {
            this.description = description;
            exits = new HashMap();
        }
    
        /**
         * Define the exits of this room.  Every direction either leads to
         * another room or is null (no exit there).
         */
        public void setExits(Room north, Room east, Room south, Room west, Room up, Room down, Room sideways)
        {
            if(north != null)
                exits.put("north", north);
            if(east != null)
                exits.put("east", east);
            if(south != null)
                exits.put("south", south);
            if(west != null)
                exits.put("west", west);
            if(up != null)
                exits.put("up", up);
            if(down != null)
                exits.put("down", down);
            if(sideways != null)
                exits.put("sideways", sideways);
        }
    
        /**
         * Return the description of the room (the one that was defined in the
         * constructor).
         */
        public String shortDescription()
        {
            return description;
        }
    
        /**
         * Return a long description of this room, on the form:
         *     You are in the kitchen.
         *     Exits: north west
         */
        public String longDescription()
        {
            return description;
        }
    
        /**
         * Return the room that is reached if we go from this room in direction
         * "direction". If there is no room in that direction, return null.
         */
        public Room nextRoom(String direction) 
        {
            return (Room)exits.get(direction);
        }
    }

    Java Code:
    package GameHopp;
    
    /**
        Author(s) = Blue Energy
        Keywords = 
        Name = RunGame
        Description = This is the class to run the game.
        This class is not to be edited.
        Version = 0.01
    */
    
    public class RunGame
    {
        public static void main (String[]args)
        {
            Game game1 = new Game();
            game1.play();
        }
    }
    Last edited by Blue Energy; 05-13-2011 at 06:40 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,576
    Rep Power
    23

    Default

    Do you have any specific java coding problems?
    Or what is your question?

  3. #3
    Blue Energy is offline Member
    Join Date
    May 2011
    Location
    Right Behind You
    Posts
    2
    Rep Power
    0

    Default

    Well, for one, I would like to know how to make an inventory class (Like a skeleton), as well as "use" and "examine" commands in the game. I thought I would provide all the code so you all could see what I have, and alter then repost what should be included to get it to do what I want.

Similar Threads

  1. Java's Class Final Project - Tower Defense
    By lastpirate89 in forum New To Java
    Replies: 6
    Last Post: 05-11-2011, 03:04 PM
  2. Urgent! Need help for my final year project!!
    By kazuma_riku73 in forum Sun Java Wireless Toolkit
    Replies: 7
    Last Post: 06-18-2010, 11:48 AM
  3. Urgent! Need help for my final year project!!
    By kazuma_riku73 in forum Sun Java Wireless Toolkit
    Replies: 1
    Last Post: 01-15-2009, 11:14 AM
  4. GUI Final Project help
    By Unknown in forum New To Java
    Replies: 21
    Last Post: 12-30-2008, 07:58 PM
  5. [SOLVED] is final class members are also final ?
    By haoberoi in forum New To Java
    Replies: 4
    Last Post: 11-10-2008, 03:01 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •