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...
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....
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...
Programmed In Java In this assignment you will create a simple game. You will put all...
Programmed In Java In this assignment you will create a simple game. You will put all of your code in a class called “Game”. You may put all of your code in the main method. An example of the “game” running is provided below. Y ou will start by welcoming the user. 1. You should print "Welcome! Your starting coordinates are (0, 0).” 2. On the next line, you will tell the user the acceptable list of commands. This should...
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,...
1) based on the text  What does the text imply is the positive return from "investing" in...
1) based on the text  What does the text imply is the positive return from "investing" in accounts receivables? As is true of other current assets, accounts receivable should be thought of as an investment. The level of accounts receivable should not be judged too high or too low based on historical standards of industry norms, but rather the test should be whether the level of return we are able to earn from this asset equals or exceeds the potential gain...
THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a...
THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a method swapNodes to SinglyLinkedList class. This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same nodes, etc. Write the main method to test the swapNodes method. Hint: You may need to traverse the list. Exercise 2 In this exercise, you will...
Buh-RING IT! For this assignment, you’re going to simulate a text-based Role-Playing Game (RPG). Design (pseudocode)...
Buh-RING IT! For this assignment, you’re going to simulate a text-based Role-Playing Game (RPG). Design (pseudocode) and implement (source) for a program that reads in 1) the hero’s Hit Points (HP – or health), 2) the maximum damage the hero does per attack, 3) the monster’s HP and 4) the maximum monster’s damage per attack.   When the player attacks, it will pick a random number between 0 and up to the maximum damage the player does, and then subtract that...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT