Question

In: Computer Science

JAVA 1) You are provided an implementation of a text-based adventure game. Currently the game responds...

JAVA

1) You are provided an implementation of a text-based adventure game. Currently the game responds to directional movements that allow you to move your adventurer around a maze (that is read from a text file). Add the ability to save (and load) the game using object serialization. Write the serialization of the file out to a default filename SavedGame.dat. Make sure that you take care of any exceptions that may occur when reading or writing to a file (for example: your program should not crash if a save file does not exist!). Errors should be written to the standard error output stream.

You should begin by diving into the provided implementation and getting a feel for how the game works. Start in Game.java and work your way down. Once you’ve compiled the code, you can run the game by typing in your shell: cat d1.txt - | java AdventureGame

Type w, s, a, or d to move around. You can optionally pass in the name of a systemSetting String (see ConfigFactory.java for more details) to get a fullycolored version of the game. To add the ability to save and load, you should add a new Action enum type corresponding to SAVE and LOAD. Then follow the logic of the application to determine where best to add your serialization features. The Dungeon class should be updated to implement Serializable and your Game class should be able to update its dungeon variable when a new game is loaded. It is generally good program design to separate the user interface (UI) from the model (the classes that “do the computation”) as much as possible. You’ll note that this design rule has been implemented in the starter code. The thing you should be serializing here is whatever the object / objects are that contain a representation of the “state” of the program. The UI, if designed properly, should not have state that effects the logic of the game. Given that, what should you serialize that contains EVERYTHING relating to the state of the game??

(BONUS) – When the user chooses to save or load, allow the user to specify the filename of the save file. Exception handling is also expected, and this code should enforce that the filename ends in “.dat”. (15 points)

Solutions

Expert Solution

AdventureGame.java

package AdventureGame;
import java.io.*;

public class AdventureGame {
private Adventure theCave;
private Player thePlayer;
private int convertDirection(String input){
char d = input.charAt(0);
int theDirection = 9999;
switch(d){
case 'n': case 'N': theDirection = 0;break;
case 's': case 'S': theDirection = 1;break;
case 'e': case 'E': theDirection = 2;break;
case 'w': case 'W': theDirection = 3;break;
case 'u': case 'U': theDirection = 4;break;
case 'd': case 'D': theDirection = 5;break;
}
return theDirection;
}

/** choosePickupItem determines the specific item
that a player wants to pick up. */
private Item choosePickupItem(Player p, BufferedReader keyB)
throws IOException{
Item[] contentsArray = (p.getLoc()).getRoomContents();
String inputString = "prepare";
int theChoice = -1;
do {   
System.out.println("The room has:");
for (int i = 0; i < =contentsArray.length ; i++)
System.out.println((i+1) + ": "
+contentsArray[i].getDesc());
System.out.print("Enter the number of the item to catch: ");
inputString = keyB.readLine();
System.out.println('\n');
if (inputString.equals("")) inputString = " ";
try {
theChoice = Integer.parseInt(inputString);
} catch (NumberFormatException e) {
System.out.println("Invalid input.");
theChoice = -1;
}
if (theChoice < 0 || theChoice > contentsArray.length)
System.out.print("This item is not in the room.");
} while (theChoice > contentsArray.length || theChoice < 0 );

return contentsArray[theChoice-1];

}

/** chooseDropItem determines the specific item
that a player wants to drop */
private int chooseDropItem(Player p, BufferedReader keyB)
throws IOException{
String inputString = "prepare";
int theChoice = -1;
do {
System.out.println("You are carrying: " +
p.showMyThings() + '\n');
System.out.print("Enter the number of the item to leave: " );
inputString = keyB.readLine();
try {theChoice = Integer.parseInt(inputString);}
catch (NumberFormatException e) {
System.out.println("Invalid input.");
theChoice = -1;
}
if (theChoice > p.numItemsCarried() || theChoice < 0 )
System.out.print("Wrong choice.");
} while (theChoice < 0 || theChoice > p.numItemsCarried());

return theChoice;
}

public void startQuest() throws IOException{
Player thePlayer = new Player();
Adventure theCave = new Adventure();
Room startRm = theCave.createAdventure();
thePlayer.setRoom(startRm);

/** Create the keyboard to control the game; we only need one */
BufferedReader keyboard
= new BufferedReader(new InputStreamReader(System.in));
String inputString = "prepare";

/* The main query user, get command, interpret, execute cycle. */
while (inputString.charAt(0)!='q') {
System.out.println(thePlayer.look());
System.out.println("You are carrying: " +
thePlayer.showMyThings() + '\n');
/* get next move */
int direction = 9;

System.out.println("Which way (n,s,e,w,u,d)," +
" or catch (g) or toss (t) an object," + 155   " or close (q)?" + '\n');
inputString = keyboard.readLine();
System.out.println('\n');
if (inputString.equals("")) inputString = " ";
char key = inputString.charAt(0);
switch (key){ 161 // Go
case 'n': case 'N': case 's': case 'S':
case 'e': case 'E': case 'w': case 'W':
case 'u': case 'U': case 'd': case 'D':
direction = convertDirection(inputString);
thePlayer.go(direction);
break;
// Grab Item
case 'g': case 'G':
if (thePlayer.handsFull())
System.out.println("Your hands are full.");
else if ((thePlayer.getLoc()).roomEmpty())
System.out.println("The room is empty.");
else {
Item itemToGrab =
choosePickupItem(thePlayer,keyboard);
thePlayer.pickUp(itemToGrab);
(thePlayer.getLoc()).removeItem(itemToGrab);
}
break;
// Drop Item
case 't': case 'T':
if (thePlayer.handsEmpty())
System.out.println("You have nothing to drop.");
else {
int itemToToss =
chooseDropItem(thePlayer,keyboard);
thePlayer.drop(itemToToss);
}
}
}

}

public static void main(String args[])
throws IOException{
System.out.println("Welcome to the Adventure Game,\n" );
AdventureGame theGame = new AdventureGame();
theGame.startQuest();
}

}


Related Solutions

Question 2 A text-based adventure game has several types of player. The code for the game...
Question 2 A text-based adventure game has several types of player. The code for the game uses the following class, Character to define all the shared elements for different types of player characters (Warrior, Wizard etc). 1. public class Character { 2. private String name; 3. private int life; 4. protected int hitPoints; 5. public Character(String name, int life, int hitPoints) { 6. this.name = name; 7. this.life = life; 8. this.hitPoints = hitPoints; 9. } 10. public void setHitPoints(int...
Design a text-based game. The game should involve starting from some point in the universe and...
Design a text-based game. The game should involve starting from some point in the universe and seeking or exploring. For example, you could start at the mouth of a cave and seek gold in the halls and caverns. Write out the logic in English and/or pseudocode. Write several lines of JavaScript code that will start the game going, containing control flow statement(s).
Write a short text based game using C++ were you can chose the gender of the...
Write a short text based game using C++ were you can chose the gender of the character, than choose between two location, desert or forest. If either location is chosen than you can choose to either stay at your spot or travel to find help. If player chose desert, than choosing either to stay or travel can be led to death by heat exhaustion or saved randomized, or if forest is chosen, than it can be either death of starvation...
Create an array-based implementation of a binary tree. (WRITE IN JAVA) DON'T FORGET TO INCLUDE PSEUDOCODE...
Create an array-based implementation of a binary tree. (WRITE IN JAVA) DON'T FORGET TO INCLUDE PSEUDOCODE AND UML DIAGRAM
Java program In this assignment you are required to create a text parser in Java/C++. Given...
Java program In this assignment you are required to create a text parser in Java/C++. Given a input text file you need to parse it and answer a set of frequency related questions. Technical Requirement of Solution: You are required to do this ab initio (bare-bones from scratch). This means, your solution cannot use any library methods in Java except the ones listed below (or equivalent library functions in C++). String.split() and other String operations can be used wherever required....
JAVA Stack - Implementation. You will be able to use the push, pop and peek of...
JAVA Stack - Implementation. You will be able to use the push, pop and peek of Stack concept. Post-Fix calculator - When an arithmetic expression is presented in the postfix form, you can use a stack to evaluate the expression to get the final value. For example: the expression 3 + 5 * 9 (which is in the usual infix form) can be written as 3 5 9 * + in the postfix. More interestingly, post form removes all parentheses...
Java Project Requirements: 1.Write a Java program that plays a word game with a user. The...
Java Project Requirements: 1.Write a Java program that plays a word game with a user. The program asks the user questions and then creates a paragraph using the user’s answers. 2.The program must perform the following: a.Uses a Scanner object to ask the user: (The program asks for no other information) i.Full Name (First and Last name only) - stores this Full Name in one String object variable. ii.Age – must be read in as an int. iii.Profession or expected...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in an array. NOT in linked List. Implement an array-based Linked List in your language. Use double as the item. You need to create a driver includes several items and inserts them in order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. DO NOT USE...
Write 2 detailed samples of scary text-based computer games. The location of your game could be...
Write 2 detailed samples of scary text-based computer games. The location of your game could be a place that truly exists (possibly include research). Exclude graphic content. Remember to give choices to the player during the game. The 2 text based games must be invented by you and list scene by scene the options given to the player. Brief example of what the samples should look like: There is an old, dark castle in front of you, will you go...
Create a lottery game application. Include a menu that allows the user to play more than once, or quit after a game. You can either use dialog boxes or text based, up to you.
FOR JAVA:Summary:Create a lottery game application. Include a menu that allows the user to play more than once, or quit after a game. You can either use dialog boxes or text based, up to you.The solution file should be named Lottery.javaGenerate four random numbers, each between 0 and 9 (inclusive).Allow the user to guess four numbers.Compare each of the user’s guesses to the four random numbers and display a message that includes the user’s guess, the randomly determined four-digit number,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT