Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Create a Swamp Game in Java
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


purav savla
Create a Swamp Game in Java
4 Answer(s)      a year and 4 months ago
Posted in : Java Beginners


You are to create a game called ‚??Get Out of My Swamp‚??. In this game an ogre, called ‚??Hek‚??, wanders around his swamp, if he encounters an ogre enemy in his swamp he kills it. If he encounters two ogre enemies in the same place they kill the ogre and the game ends. Full details of the game are given below. There is a sample session from a game given at the end of the coursework. The swamp can be thought of as a four by four grid.

When the game starts the ogre is placed in a random square (i.e. part of the swamp). However he must not be placed in the top left hand corner of the swamp when the game starts, although he can move there during the game. When the ogre moves, he can move to ANY(Diagonally as well) of the neighbouring squares as shown below. The ogre cannot move out of the swamp.The square the ogre moves to is chosen at random from all the possible squares that it can move to. There are three types of ogre enemies that can inhabit HEk‚??s swamp; a snake, a parrot and a donkey. There is a hole in the fence around Hek‚??s swamp in the top left corner and this is where the enemies enter the swamp. Once in the swamp the enemies move in exactly the same way as the ogre; i.e. they move randomly to any of the neighbouring squares.

Every time Hek moves there is a one in three chance of an enemy entering the swamp, the type of enemy is completely random.

Although there are only three types of enemies. new types of enemy may be available in the future. You should take this into account when coding your solution.

If the ogre moves into the same square as an enemy, the ogre kills the enemy and the enemy is removed from the swamp. If the ogre moves into the same square as two or more enemies, the enemies kill the ogre and the game is over.

If the ogre is still alive and the user chooses not to make another move the game state should be saved using serialization. When the program starts the user should have the option of loading saved data or starting a new game. It should be possible to change the size of your swamp by simply changing one integer in your program. You should incorporate both the singleton pattern and the observer pattern into your game. If you cannot see an obvious place for the patterns in the game you may extend the specification of the game in any way in order to incorporate the patterns.

Please provide me with the solution as soon as possible because i need to demonstrate the same on monday 12th august. Thanking You. Purav


Advertisement
View Answers

August 11, 2013 at 1:58 AM


Test it and let me know about it. Seems to be working for me, not sure if I am on missing on any of the requirements.

GetOutOfMySwamp.java

package getoutofmyswamp;
import java.io.*;
/**main class :: Controls the game
 * @author Shasankar
 */
public class GetOutOfMySwamp {
    //main presents the user with main menu
    public static void main(String[] args) {        
        UIHelper ui = new UIHelper();
        String input;
        do{
            input = ui.getUserInput("\n\tGet Out Of My Swamp"
                    + "\n\t~~~~~~~~~~~~~~~~~~~"
                    + "\nNew Game(N)"
                    + "\nLoad Game(L)"
                    + "\nSettings(S)"
                    + "\nExit(E)"
                    + "\nUser Choice?? ");            
            switch(input){
                case "N":
                    startNewGame();
                    break;
                case "L":
                    loadGame();
                    break;
                case "S":
                    changeSettings();
                    break;
                case "E":
                    break;
                default:
                    System.out.println("Invalid Input! Try Again");
            }
        }while(!input.equals("E"));        
    }
    //save game using serialization
    public static void saveTheGame(Game theGame){        
        try{
            ObjectOutputStream os = new ObjectOutputStream
                    (new FileOutputStream("GameData.save"));
            os.writeObject(theGame);
            os.close();
        }catch(IOException e){
            System.out.println("IOException " + e);
        }
    }
    //load the game using deserialization
    public static void loadGame(){        
        Game theGame = null;
        try{
            ObjectInputStream os = new ObjectInputStream
                    (new FileInputStream("GameData.save"));
            theGame = (Game) os.readObject();
            os.close();
        }catch(Exception e){
            System.out.println("Exception " + e);
        }
        if(theGame.start())            
            saveTheGame(theGame);
    }
    //start a new game
    public static void startNewGame(){
        Settings gameSettings = null;
        Game theGame;
        try{
            ObjectInputStream os = new ObjectInputStream
                    (new FileInputStream("Settings.save"));
            gameSettings = (Settings) os.readObject();
            os.close();
            theGame = new Game
                (gameSettings.getGridOrder(),gameSettings.getNewEnemies());
        }catch(Exception e){
            theGame = new Game();
        }                
        if(theGame.start())            
            saveTheGame(theGame);
    }    
    //user can control order of the grid & introduce new enemies
    public static void changeSettings(){
        UIHelper ui = new UIHelper();
        Settings gameSettings = new Settings();
        String input = null,gridOrder = null;
        int intGridOrder;
        do{
            input = ui.getUserInput("\n\tSettings"
                    + "\n\t~~~~~~~~"
                    + "\nGrid Order(G)"
                    + "\nAdd New Enemies(A)"                    
                    + "\nExit(E)"
                    + "\nUser Choice?? "); 
            switch(input){
                case "G":
                    do {
                        gridOrder = ui.getUserInput
                                ("Enter Grid Order (must be > 2): ");
                        intGridOrder = Integer.parseInt(gridOrder);
                        if (intGridOrder<=2)
                            System.out.println("Try Again Dude");
                    }while(intGridOrder<=2);
                    gameSettings.setGridOrder(intGridOrder);
                    break;
                case "A":
                    gameSettings.addNewEnemies
                            (ui.getUserInput("Enter Your Deadly Enemy: "));
                    break;                
                case "E":
                    break;
                default:
                    System.out.println("Invalid Input! Try Again");
            }
        }while(!input.equals("E"));
        try{
            ObjectOutputStream os = new ObjectOutputStream
                    (new FileOutputStream("Settings.save"));
            os.writeObject(gameSettings);
            os.close();
        }catch(IOException e){
            System.out.println("IOException " + e);
        }   
        System.out.println("Warning::Changes will take effect for New Game");
    }
}

Character.java

package getoutofmyswamp;
import java.io.*;
/**character class :: Character properties & behaviors
 * @author Shasankar
 */
public class Character implements Serializable{
    private String name;
    private int row,col,bounds;
    //constructor for enemies since they start at (0,0)
    public Character(String name,int bounds){
        this.name = name;
        this.row = 0;
        this.col = 0;    
        this.bounds = bounds;
    }
    //constructor for ogre which can start at any location except (0,0)
    public Character(String name,int row,int col,int bounds){
        this.name = name;
        this.row = row;
        this.col = col;
        this.bounds = bounds;
    }
    //toString override
    public String toString(){
        return (name + " at (" + row + "," + col + ")\t");
    }
    //character movements
    //return true if movement possible else false
    public boolean moveUp(){
        if((row-1) >= 0){
            row--;
            return true;
        }else
            return false;            
    }
    public boolean moveDown(){
        if((row+1) < bounds){
            row++;
            return true;
        }else
            return false;            
    }
    public boolean moveLeft(){
        if((col-1) >= 0){
            col--;
            return true;
        }else
            return false;            
    }
    public boolean moveRight(){
        if((col+1) < bounds){
            col++;
            return true;
        }else
            return false;            
    }
    public boolean moveUpRight(){
        if((col+1) < bounds && (row-1) >= 0){
            col++;
            row--;
            return true;
        }else
            return false;            
    }
    public boolean moveDownRight(){
        if((col+1) < bounds && (row+1) < bounds){
            col++;
            row++;
            return true;
        }else
            return false;            
    }
    public boolean moveDownLeft(){
        if((col-1) >= 0 && (row+1) < bounds){
            col--;
            row++;
            return true;
        }else
            return false;            
    }
    public boolean moveUpLeft(){
        if((col-1) >= 0 && (row-1) >= 0){
            col--;
            row--;
            return true;
        }else
            return false;            
    }
    //equals override for checking if characters are at same grid position
    public boolean equals(Character c){
        if((row==c.row) && (col==c.col))
            return true;
        else
            return false;
    }    
}

Game.java

package getoutofmyswamp;
import java.lang.reflect.Array;
import java.util.Random;
import java.util.ArrayList;
import java.io.*;
/**game class :: The real game is executed here
 * @author Shasankar
 */
public class Game implements Serializable{
    private Character Ogre;
    private ArrayList Enemies;
    private ArrayList typesOfEnemies;
    private String[] moves = {"U","D","R","L","UR","DR","DL","UL"};
    private UIHelper ui = new UIHelper();
    private int moveNo,gridOrder;

    public Game(){        
        this(4,new ArrayList());
    }    
    public Game(int gridOrder,ArrayList newTypesOfEnemies){
        int rand = (new Random().nextInt(gridOrder * gridOrder - 1)) + 1;
        int row = rand / gridOrder;
        int col = rand % gridOrder;
        Ogre = new Character("Ogre",row,col,gridOrder);
        Enemies = new ArrayList();
        typesOfEnemies = new ArrayList();
        typesOfEnemies.add("Snake");
        typesOfEnemies.add("Parrot");
        typesOfEnemies.add("Donkey");           
        for(String enemy:newTypesOfEnemies)
                typesOfEnemies.add(enemy);                
        moveNo = -1;
        this.gridOrder = gridOrder;
    }
    //start the game
    public boolean start(){        
        boolean validInput = false;   
        String input = null;
        int newEnemyAtMoveNo = 0;
        do{
            displayCharPositions();
            if(!checkOgreAlive()){                
                System.out.println("Ogre Dead!!");
                return false;
            }
            input = ui.getUserInput("\n\tMove Ogre"
                    + "\n\t~~~~~~~~~ "
                    + "\nUp(U)/Down(D)/Left(L)/Right(R)"
                    + "\nUpRight(UR)/DownRight(DR)/DownLeft(DL)/UpLeft(UL)"
                    + "\nExit(E)"
                    + "\nUser Choice?? ");

            validInput = moveCharacter(Ogre,input);                        
            if(!validInput){
                if(!input.equals("E"))
                    System.out.println("Invalid move! Try Again");
            }
            else {                
                moveNo ++;
                System.out.println("Move No.: " + (moveNo+1));
                moveEachEnemy();
                if(moveNo % 3 == 0)                    
                    newEnemyAtMoveNo = new Random().nextInt(3);                
                if(moveNo % 3 == newEnemyAtMoveNo)
                    enterNewEnemy();                
            }
        }while(!input.equals("E"));          
        input = ui.getUserInput("Save the game?(Y/N): ");
        if(input.equals("Y"))
            return true;
        else
            return false;
    }
    //display current position of the characters
    public void displayCharPositions(){
        System.out.print("\n" + Ogre );
        for(Character c:Enemies)
            System.out.print(c);        
        System.out.print("\n");
    }        
    //a new enemy appears into the grid throught the hole
    public void enterNewEnemy(){
        String charName = typesOfEnemies.get(new Random().nextInt(typesOfEnemies.size()));
        Enemies.add(new Character(charName,gridOrder));
    }
    //each enemy moves in random direction
    public void moveEachEnemy(){
        String move;
        for(Character c:Enemies){            
            do
                move = Array.get(moves, new Random().nextInt(8)).toString();                
            while(!moveCharacter(c,move));
        }            
    }
    //move a character
    public boolean moveCharacter(Character c,String move){
        switch(move){
                case "U":                    
                    return c.moveUp();                    
                case "D":
                    return c.moveDown();
                case "L":
                    return c.moveLeft();
                case "R":
                    return c.moveRight();
                case "UR":
                    return c.moveUpRight();
                case "DR":
                    return c.moveDownRight();
                case "DL":
                    return c.moveDownLeft();
                case "UL":
                    return c.moveUpLeft();
                default:
                    return false;
        }
    }
    //check if the ogre is alive
    //return true if alive else false
    public boolean checkOgreAlive(){
        int enemiesEncountered = 0;
        Character defeatedEnemy = null;
        for(Character c:Enemies){
            if(Ogre.equals(c)){
                enemiesEncountered++;
                defeatedEnemy = c;
            }
            if (enemiesEncountered > 1)
                return false;
        }
        if(enemiesEncountered == 1){
            System.out.println("Ogre killed the " + defeatedEnemy );
            Enemies.remove(defeatedEnemy);
        }        
        return true;
    }
}

Settings.java

package getoutofmyswamp;
import java.io.*;
import java.util.ArrayList;
/**settings class :: This class has settings like order of the grid 
 * & additional enemies added by the user.
 * @author Shasankar
 */
public class Settings implements Serializable{
    private int gridOrder;
    private ArrayList newTypesOfEnemies;
    public Settings(){
        gridOrder = 4;
        newTypesOfEnemies = new ArrayList();
    }
    //getter for grid order
    public int getGridOrder(){
        return gridOrder;
    }
    //getter for new enemies
    public ArrayList getNewEnemies(){
        return newTypesOfEnemies;
    }
    //set user defined grid order
    public void setGridOrder(int gridOrder){
        this.gridOrder = gridOrder;
    }
    //add user defined enemy to the list of enemies
    public void addNewEnemies(String newTypeOfEnemy){        
        newTypesOfEnemies.add(newTypeOfEnemy);
    }
}

UIHelper.java

package getoutofmyswamp;
import java.io.*;
/**input class :: This class helps to get user inputs.
 * @author Shasankar
 */
public class UIHelper implements Serializable{    
    public String getUserInput(String prompt){
        System.out.print(prompt);
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            return br.readLine();
        }catch(IOException e){
            System.out.println("IOException" + e);
        }
        return null;
    }
}


August 12, 2013 at 9:09 PM


Hey bro thanks for the answer but there are many errors in it. Have you checked it bro ??? If not then please chck and leme know. Thanx a ton , cheers !!!



August 12, 2013 at 9:48 PM


ofcorse 'bro' .. its running giving the desired output. what errors? can u plz detail rather than saying "there are many errors in it".



August 14, 2013 at 8:21 AM


errors with move function stating that it cannot take input as a string and it shld b a int or enum. Some more errors as well but i dnt remember bro. Do one thing try 2 run your this prog in eclipse and see d errors u get. watsay ??? As i dnt hv a laptop @ home so i can only access eclipse in d uni so untill i go can you please check it for me ??? Thanks 4 ur help.



Related Tutorials/Questions & Answers:
Create a Swamp Game in Java
Create a Swamp Game in Java  You are to create a game called ‚??Get Out of My Swamp‚??. In this game an ogre, called ‚??Hek‚??, wanders around his... of the swamp when the game starts, although he can move there during the game. When
java game
java game  Can anyone please give me a game source code
Advertisements
Create a guessing game - Framework
Create a guessing game  Create a guessing game that picks a random number between 1 and 100 and lets you keep guessing until you get it right! You..., too. it is in java but i m not sure about the language, it is like c.print
JAVA Game
JAVA Game  I want to make a JAVA game...in dat game...d player has to input a word in 10 secnds...4 dat m running a delay loop... but the problem is not...i am not getting any way...to make that input field(eg: String str
Game
Game  how can create simple game in java . thank u so match ,please help
Java Game Pontoon
Java Game Pontoon  Could someone help me create a programme for the game pontoon //play a game of pontoon import java.util.*; public class Pontoon { public static void main (String args[]) { //deal initial hands
Game
Game  How to develop a game using java? give me a total code for any simple game
game Nim - Java Beginners
game Nim  how is the search tree for a game Nim looks like
game
game  How to make 3D game in java Applet
game
game  Hi thank you for answers.I am devoloping a java game caled Duck Hunt Game in netbeans6.7.1 software and I need help in some codes...,if you have this game's code please post me as soon as possible
Java game Pontoon
Java game Pontoon  Hello. I have trouble with my pontoon code. I ahve done it using simple java programming. It is working BUT it dosent stops when the players hand rises ober 24 points. where in game the player should be bust
Java program for connectfour game
Java program for connectfour game  Hello, my program is about connectFour game. I need help with resolving the logic for this problem. I appreciate...; ConnectFourServer game = new ConnectFourServer(); private ConnectFourClient
Craps Game Java Programming Help
Craps Game Java Programming Help  Craps is a casino game that involves the throwing of a pair of dice. Based on the throw, the thrower either gets to continue throw (and win money), or stops throwing (and loses money). Write your
Java game bulls and cows
Java game bulls and cows In this tutorial, you will learn how to implement bulls and cows game in java. The game bulls and cows is an ancient game...;quit", the user will come out from the game. If the user inputs 4 digit
who know full coding of guessing game in java?
who know full coding of guessing game in java?  There is only 1 player. Use JAVA Random toolkit to generate random number between 1 to 10. Once user... again or to exit the game by type 1 to proceed the game and type 2 to end the game
Java Program
Java Program  You are to create a game called √Ę??Get Out of My Swamp√Ę??. In this game an ogre, called √Ę??Hek√Ę??, wanders around his swamp, if he... the game starts the ogre is placed in a random square (i.e. part of the swamp
Java Program
Java Program  You are to create a game called √Ę??Get Out of My Swamp√Ę??. In this game an ogre, called √Ę??Hek√Ę??, wanders around his swamp, if he... the game starts the ogre is placed in a random square (i.e. part of the swamp
BRICK-BREAKER game concept - Java Beginners
BRICK-BREAKER game concept  I am planning to write a program for BRICK-BREAKER GAME. can any 1 help me any 1 can u plz help me frzzz?? you can also send the mails to poramboku.me@gmai.com
genaral snake game in java - Java Beginners
genaral snake game in java  can u please send code for fallowing write a snake game program using swings?  Hi This is the source code of Snake game in swing Snake.java file import javax.swing.JFrame
Blackjack game - IDE Questions
Blackjack game  Create a java code for a simple blackjack game for just one hand of Blackjack, it does not need to include money and betting
Guess Number Games in Java
Guess Number Games in Java Here we are going to create guess number game where user have to guess the randomly generated number. For this, we have allowed... will like to quit from the game, you can press 'quit'button.   Here
tetris game code - Swing AWT
tetris game code  To develop a JAVA puzzle game which is a "variation" of the Tetris game
Chess Application In Java Swing
.style1 { margin-right: 0px; } Chess Application In Java Swing       In this section, you will learn how to create chess game in java swing
game programming
game programming  Hi. i have witten the script and have almost completed developing a social game like mafia wars. can any one plz help me by answering me some of my doubts.. after uploading the game on facebook how tokeep data
Chess Game
Chess Game  How could I make a basic 8x8 chess table with two dimensional arrays and insert the chess pieces in the array?   Please visit the following link: http://roseindia.net/java/example/java/swing/chess
how to create notepad in java
how to create notepad in java  how to create notepad in java
How to create a class in java
How to create a class in java  I am a beginner in programming and tried to learn how to do programming in Java. Friends please explain how can I create a class in Java
How to Create Keyboard in JAVA
How to Create Keyboard in JAVA  please help me to create On-Screen Keyboard with java and please give me an another idia to make it ..............iam waiting for your help ,think u so much
How to create charts in Java?
How to create charts in Java?  Is there any example of creating charts and graphs in Java? thanks   Hi, check the tutorial: Chart & Graphs Tutorials in Java Thanks
How do i slow down the game (othello game)??
How do i slow down the game (othello game)??  Hello, I built an othello game that can be played by 2 humans , human and computer and two computers... with each other the fram doesn't appear until the game is finish. I think it is becase
to create a java class and methods
to create a java class and methods  How to create a java class without using the library class to represent linked lists of integers and also provide it with methods that can be used to reverse a list & append two lists.Also
Advertisements
 

 

 

DMCA.com