Story Text Applet
<< Perspective Floor | FinalProjectsTrailIndex | Battleship >>
Room.java
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; public class Room { //protected ArrayList<Item> items; protected String name, description; protected HashMap<String, Room> exits; public Room(String name) { //items = new ArrayList<Item>(); this.name=name; description = "You are in a room"; exits = new HashMap<String, Room>(); } public String getDescription(){ return "\n"+description+"\n"; } public void setDescription(String s){ description=s; } public void addExit(String s, Room r){ exits.put(s, r); } public String getMenu(){ String m="Choices: "; String[] k=exits.keySet().toArray(new String[0]); for (String s:k){ m+=s+" "; } return m; } public Room getRoom(char ch){ String[] k= exits.keySet().toArray(new String[0]); for(String s:k) if(ch==s.charAt(0)) return exits.get(s); return null; } }
StoryTextApplet.java
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class StoryTextApplet extends Applet implements KeyListener { private TextArea ta; private Room currentRoom, field, door, house; public void init(){ this.setFocusable(true); this.requestFocus(); //setLayout(new GridLayout(2,0)); addKeyListener(this); ta = new TextArea("Wecome\n",30, 80, TextArea.SCROLLBARS_VERTICAL_ONLY); ta.setEditable(false); ta.setBackground(Color.BLACK); ta.setForeground(Color.GREEN); ta.setFont(new Font("Courier", Font.BOLD , 18 )); add(ta); initField(); initDoor(); field.addExit("N)orth", door); initHouse(); door.addExit("O)pen", house); currentRoom=field; ta.append(currentRoom.getDescription()+"\n"); ta.append(currentRoom.getMenu()); } private void initHouse() { house = new Room("Entry"); house.setDescription("You are in the entry of a house."); house.addExit("D)oor", door); } private void initDoor() { door = new Room("Door"); door.setDescription("You are standing in front of a Door of a house"); door.addExit("S)outh", field); } private void initField() { field = new Room("F)ield"); field.setDescription("You are in a field. You see a house in the distance."); } public void paint(Graphics g){ //g.setColor(Color.WHITE); //g.fillRect(0, 0, getWidth(), getHeight()); //g.setColor(Color.YELLOW); //g.fillOval(350, 500, 200, 200); this.requestFocus(); } @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { char ch=Character.toUpperCase(e.getKeyChar()); Room newRoom = currentRoom.getRoom(ch); if(newRoom==null) ta.append("\nI don't understand "+ch+"\n"); else{ currentRoom=newRoom; } ta.append(currentRoom.getDescription()); ta.append("\n"+currentRoom.getMenu()); } @Override public void keyReleased(KeyEvent e) {} }