Text Based Game In Java Applet

A Final Project For my Class

Page 1 of 1

8 Replies - 4829 Views - Last Post: 25 May 2008 - 07:24 PM Rate Topic: -----

#1 Riceraider  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 15-May 08

Text Based Game In Java Applet

Posted 15 May 2008 - 10:14 AM

My classmate and I are doing a classical text based adventure game for our final project, We are aware this is going to be a painful task, but I feel once we have the framework done that it will go much smoother than it is now.

Currently, I am trying to figure out how to create a Java Applet where the text scrolls as though it were the terminal window. We also want to have the background be black(I figured how to do this part), and the text to be white(This is the harder part for me).

import javax.swing.*; 
import java.applet.*; 
import java.util.*;
import java.awt.*;

public class projectApplet extends JApplet
{
	public class GameApplet extends JPanel
	{
		void GameAppletl()
		{
			
		}
		public void paintComponent(Graphics g)
		{
			super.paintComponent(g);//calls super-class
			Color black = new Color(0,0,0);//creates color Black
			setBackground(black); // Sets the background to the new color
		}
		

	}
	public void init()//Sets Applet window Size
	{
		setSize(500,500);
		getContentPane().add(new DemoPanel());
	}

}



Looking at tutorials at this website, this is what I have for the applet so far.

How do you make it scroll the text like terminal window, instead of using drawString("",0,0)?

How do you make it print out text from a seperate class? (eg. we have a story class that has all of the story text)

Is it possible to make the text colored, if so, How?

Please assume that I know little about applets, we have only been introcuced to them this late in the year. If you need the code for other classes to see how they work, please tell me.

This post has been edited by Riceraider: 15 May 2008 - 10:15 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Text Based Game In Java Applet

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Text Based Game In Java Applet

Posted 15 May 2008 - 02:05 PM

View PostRiceraider, on 15 May, 2008 - 10:14 AM, said:

My classmate and I are doing a classical text based adventure game for our final project, We are aware this is going to be a painful task, but I feel once we have the framework done that it will go much smoother than it is now.

Currently, I am trying to figure out how to create a Java Applet where the text scrolls as though it were the terminal window. We also want to have the background be black(I figured how to do this part), and the text to be white(This is the harder part for me).



Why re-inventing the wheel ? Forget your paint() method and drawString() at all.

Create JTextArea textArea

textArea.setForeground(Color.WHITE);
textArea.setBacground(Color.BLACK);
Create a JScrollPane using the textArea

JScrollPane scrollPane = new JScrollPane(textArea);

add the scrollPane to your JApplet
then just:

textArea.append("some text");


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class projectApplet extends JApplet implements ActionListener
{
  private JTextArea textArea;
  private int lineNumber = 0;   // this is just to test
  
  public void init() {	
	JPanel panel = new JPanel();
	textArea = new JTextArea();
	textArea.setBackground(Color.BLACK);
	textArea.setForeground(Color.WHITE);
	JScrollPane sp = new JScrollPane(textArea);
	panel.add(sp);
	
	Container window = getContentPane();
	window.setLayout(new BorderLayout());
	window.add(sp,BorderLayout.CENTER);
	// this is just to test------------------
	JButton b = new JButton("Clik to add a line");
	b.addActionListener(this);
	window.add(b, BorderLayout.SOUTH);
	//---------------------------------------
  }

  public void actionPerformed(ActionEvent arg0) {
	   lineNumber++;
	   textArea.append("\nLine number: " + lineNumber);
  }
}


This post has been edited by pbl: 15 May 2008 - 03:30 PM

Was This Post Helpful? 0
  • +
  • -

#3 Riceraider  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 15-May 08

Re: Text Based Game In Java Applet

Posted 15 May 2008 - 10:48 PM

Thank you so VERY much, This solves pretty much all my basic problems. I will start reading up on how this JTextArea works and what I can do to it. It is yet again one of the many JAVA things I have not heard of, just goes to show you how new I am. I plan on working on this for about 3-5 hours Saturday, I will tell you guys how the code is coming along!

The game is based on the book "The Atrocity Archives" By Charlie Stross (I e-mailed him and got permission so long as I go through the "adoption of a suitable open source license." -- Still doing research on this).

Once again, Thank you very much.
Was This Post Helpful? 0
  • +
  • -

#4 Riceraider  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 15-May 08

Re: Text Based Game In Java Applet

Posted 25 May 2008 - 04:20 PM

Ok, so far the code for the actual game is going fine, but still, displaying it in a window is hard. We are thinking of using JTextField and JTextArea. What I planned the code to do, was whenever you enter the command, it gets the input, copies it into the JTextArea, and then runs the input through our "Story" class and makes the game run in that manner. I am getting nullpointerexceptions and other errors and I do not know how to fix it because of my unfamilliarity with these Java abilities.

Instead of just trying to say all that I did, Allow me to show you:

public class TextDemo extends JPanel implements ActionListener {
	public static String input;
	public static JTextField textField;
	public static JTextArea textArea;
	private final static String newline = "\n";
	public static GamePlayer game=new GamePlayer();
	public Story story=new Story();
	
	public TextDemo() {
		super(new GridBagLayout());

		textArea = new JTextArea(20, 50);
		textArea.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(textArea);
		

		textField = new JTextField(20);
		textField.addActionListener(this);
		
		//Add Components to this panel.
		GridBagConstraints c = new GridBagConstraints();
		c.gridwidth = GridBagConstraints.REMAINDER;
		
		c.fill = GridBagConstraints.HORIZONTAL;
		
		
		c.fill = GridBagConstraints.BOTH;
		c.weightx = 1.0;
		c.weighty = 1.0;
		add(scrollPane, c);
		add(textField, c);
	}
	public static String getInput()
	{
		return textField.getText();
	}
	public void actionPerformed(ActionEvent evt) {
		input = textField.getText();
		textArea.append(input + newline);
   //	 Story.story(game);

		//Make sure the new text is visible, even if there
		//was a selection in the text area.
		textArea.setCaretPosition(textArea.getDocument().getLength());
		
		story.story(game);
		
	}

	/**
	 * Create the GUI and show it.  For thread safety,
	 * this method should be invoked from the
	 * event dispatch thread.
	 */
	private static void createAndShowGUI() {
		//Create and set up the window.
		JFrame frame = new JFrame("TextDemo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Add contents to the window.
		frame.add(new TextDemo());

		//Display the window.
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		//Schedule a job for the event dispatch thread:
		//creating and showing this application's GUI.
		
		createAndShowGUI();

		
		textArea.append("THE ATROCITY ARCHIVES"+newline);
		
	}
}

Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Text Based Game In Java Applet

Posted 25 May 2008 - 04:46 PM

To help you we'll need a copy of your classes: GamePlayer and Story
Was This Post Helpful? 0
  • +
  • -

#6 Riceraider  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 15-May 08

Re: Text Based Game In Java Applet

Posted 25 May 2008 - 04:56 PM

View Postpbl, on 25 May, 2008 - 04:46 PM, said:

To help you we'll need a copy of your classes: GamePlayer and Story


Here they are:

public class Story
{
	GamePlayer game=new GamePlayer();
	StorySegments a=new StorySegments();
	InitLocations init=new InitLocations();
	BobHoward b=new BobHoward();
	String input = TextDemo.getInput();
	private LocationData currentLoc;
	private boolean greenSkyComplete;
	private boolean gotFirstItem=false;
	private boolean hasShownFirst=false;
	private boolean hasShownSecond=false;
	private boolean hasShownThird=false;
	private boolean hasShownFourth=false;
	private int numOfTurns=1;
	private boolean greenSkyLocInit=false;
	
	public Story()
	{
		greenSkyComplete=false;
	}
	
	public LocationData getCurrentLocation()
	{
		return currentLoc;
	}
	
	public void setCompletionPro(boolean bool)
	{
		greenSkyComplete=bool;
	}

	public void story(GamePlayer game)
	{
		init.addFirstLocs();
		if(hasShownFirst==false)//shows first blurb
		{
			System.out.println(a.getStorySegment(game.getStoryPhase()));
			hasShownFirst=true;
		}
		if(greenSkyLocInit==false)//inits prologue locs
		{
			currentLoc=InitLocations.greenSkyLocs[1][1];
			greenSkyLocInit=true;
		}
		if(greenSkyComplete==false)
		{
			if(gotFirstItem==false)//inits items
			{
				BobHoward.addItem(new Items("Pager", "An ordinary pager, that can be used to contact you."));
				BobHoward.addItem(new Items("Mobile phone", "An ordinary cellphone, that doesn't play mp3s or take pictures."));
				gotFirstItem=true;
			}
			if(numOfTurns==2&&hasShownSecond==false)//prints pager bit
			{
				game.setStoryPhase(1);
				System.out.println(a.getStorySegment(game.getStoryPhase()));
				hasShownSecond=true;
				return;
			}
			if(hasShownThird==true&&numOfTurns==1&&hasShownFourth==false)
			{
				game.setStoryPhase(3);
				System.out.println(a.getStorySegment(game.getStoryPhase()));
				hasShownFourth=true;
				return;
			}
//			Scanner in=new Scanner(System.in);
//			printMenu();
//		  String input=in.nextLine();
			if(input.equalsIgnoreCase("quit")||input.equalsIgnoreCase("exit"))//quits
			{
				game.setStoryPhase(99);
				return;
			}
			if(input.equalsIgnoreCase("inventory")||input.equalsIgnoreCase("inv")||input.equalsIgnoreCase("i")||input.equalsIgnoreCase("items"))//shows inventory
			{
				System.out.println(b.toString());
				numOfTurns++;
				return;
			}
			if(input.equalsIgnoreCase("north")||input.equalsIgnoreCase("n"))//moves north
			{
				if(hasShownSecond==false)//shows second story blurb
				{
					System.out.println("You need to wait for the last late-working executive to leave.");
					numOfTurns++;
					return;
				}
				if(hasShownSecond==true)//has shown second story blurb
				{
					numOfTurns=0;
					if(hasShownThird==false)
					{
						int x=currentLoc.getX();
						int y=currentLoc.getY();
						y--;
						currentLoc=InitLocations.greenSkyLocs[x][y];
						game.setStoryPhase(2);
						System.out.println(a.getStorySegment(game.getStoryPhase()));
						hasShownThird=true;
					}
					return;
				}
			}
			if(hasShownThird==true&&numOfTurns==1&&hasShownFourth==false)
			{
				game.setStoryPhase(3);
				System.out.println(a.getStorySegment(game.getStoryPhase()));
				hasShownFourth=true;
				return;
			}
			if(input.equalsIgnoreCase("east")||input.equalsIgnoreCase("e")||input.equalsIgnoreCase("west")||input.equalsIgnoreCase("w")||input.equalsIgnoreCase("south")||input.equalsIgnoreCase("s"))//moves other ways
			{
				System.out.println("You can't go that way!");
				numOfTurns++;
				return;
			}
			if(input.equalsIgnoreCase("look around"))//location info
			{
				currentLoc.printDesc();
				numOfTurns++;
				return;
			}
			if(input.substring(0,3).equalsIgnoreCase("get"))//gets stuff
			{
				if(getCurrentLocation().isItemInLocation(input.substring(4)))
				{
					getCurrentLocation().isItemInLocation(input.substring(4));
					numOfTurns++;
					System.out.println("Gotten.");
					return;
				}
				else
				{
					System.out.println("That isn't here!");
					return;
				}
			}
			if(input.length()>7&&input.substring(0,7).equalsIgnoreCase("look at"))//looks at stuff
			{
				if(BobHoward.findItem(input.substring(8))>=0)
				{
					int index=BobHoward.findItem(input.substring(8));
					System.out.println(BobHoward.inventory.get(index).getDescription());
					numOfTurns++;
					return;
				}
				else if(BobHoward.findItem(input.substring(8))==-1)
				{
					System.out.println("You haven't got that!");
					return;
				}
			}
			if(hasShownFourth==true&&input.equals("auto/share/fs/scooby/netapp/user/home/malcolm/R/catbert/world_domination/manifesto"))
			{
				System.out.println("aaaa");
				greenSkyComplete=true;
				return;
			}
			else
			{
				printError();
				game.setStoryPhase(99);//error messages
				return;
			}
		}
	}
	
	public void printMenu()
	{
		System.out.print("\n>");
	}
	
	public void printError()
	{
		double pick=Math.random()*3;
		if(pick<=1)
			System.out.println("+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++");
		if(pick>1&&pick<=2)
			System.out.println("+++ Out Of Cheese Error. Melon Melon Melon. Redo From Start +++");
		if(pick>2)
			System.out.println("+++ I Am Sorry. It Is Hard To Convey Five-Dimensional Ideas In A Language Evolved To Scream Defiance At The Monkeys In The Next Tree +++");
	}
}



I am relatively sure that GamePlay needs to go away for what I plan to do.

public class GamePlayer
{

	private int storyPhase;
	
	public int getStoryPhase()
	{
		return storyPhase;
	}
	
	public void setStoryPhase(int a)
	{
		storyPhase=a;
	}
	
	public static void main(String[]args)
	{
		System.out.println("THE ATROCITY ARCHIVES");
		System.out.println("Story by: Charles Stross	 Mucked-About-With by: Johnny Musser & Jordan Rice");
		System.out.println("Copyright (c) 2008 by Johnny Musser & Jordan Rice. All rights reserved, except those held by the bloke who actually wrote the book.");
		System.out.println("Pre-Release 0.1 / Serial number 42 / Interpreter * Version K\n");
		GamePlayer game=new GamePlayer();
		game.setStoryPhase(0);
		Story story=new Story();
		while(game.getStoryPhase()<99)
		{
			story.story(game);
		}
		System.out.println("Game Over");
	}
}

Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Text Based Game In Java Applet

Posted 25 May 2008 - 05:20 PM

More you provide us with classes more we discover new classes...
Now we have the following classes missing:
- StorySegments
- InitLocations
- BobHoward
- LocationData

You are sure you have/need all these classes ?
Was This Post Helpful? 0
  • +
  • -

#8 Riceraider  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 15-May 08

Re: Text Based Game In Java Applet

Posted 25 May 2008 - 05:39 PM

We were taught to seperate our code into different classes, but I get your point, we should combine a few of them together.

public class Items
{
	private String name;
	private String description;
	
	public Items(String n, String d)
	{
		name=n;
		description=d;
	}
	
	public String getName()
	{
		return name;
	}
	
	public String getDescription()
	{
		return description;
	}
}


public class BobHoward
{
	public static ArrayList<Items> inventory=new ArrayList<Items>();
	
	public static void addItem(Items k)
	{
		inventory.add(k);
	}
	
	public ArrayList<Items> getInventory()
	{
		return inventory;
	}
	
	public void removeItem(String k)
	{
		for(int q=0;q<inventory.size();q++)
		{
			if(inventory.get(q).getName().equalsIgnoreCase(k))
				inventory.remove(inventory.get(q));
		}
	}
	
	public String toString()
	{
		String inv="\nInventory:";
		for(int q=0;q<inventory.size();q++)
		{
			inv=inv+"\n\t"+inventory.get(q).getName();
		}
		return inv;
	}
	
	public static int findItem(String a)
	{
		for(int q=0;q<inventory.size();q++)
		{
			if(inventory.get(q).getName().equalsIgnoreCase(a))
				return q;
		}
		return -1;
	}
}


public class StorySegments
{
	private String[]story={"PROLOGUE: GREEN SKY AT NIGHT, HACKER'S DELIGHT\n\nYou're lurking in the shrubbery behind an industrial unit, armed with a\nclipboard, a pager, and a pair of bulbous night-vision goggles. The bloody\nthings make you look like a train-spotter with a gasmask fetish, and\nthe green-ness of everything is giving you a headache.",
							"Your pager vibrates, and a message tells you the manager has finally left.\nYou can now enter the window to the north.",
							"You stumble in through the window, sending a stack of CDs flying,\nand wonder how in the h*** the owner can fail to notice your great muddy\nboot-print between the obviously confidential documents. You step into one\nof the cubicles, and feel a brief twinge of sympathy for the poor b******.\nThe desk has three machines on it two normal ones, and the one you're\ninterested in, a weird-a** piece of machinery that looks at least a decade old.\nYou login to the main computer, but need to first find the proper directory.",
							"\nYou pull out your mobile, and dial 'Capital Laundry Services'. You're told\nthe directory is auto slash share slash fs slash scooby slash netapp\nslash user slash home slash malcolm slash R slash catbert slash\nworld-underscore-domination slash manifesto.\nEnter it into the computer now."};
	
	public String getStorySegment(int a)
	{
		return story[a];
	}
}


public class LocationData
{
	private String description;
	private ArrayList<Items> itemsInLocation;
	private int up;
	private int across;
	
	public LocationData(String desc, ArrayList<Items>theseItems,int y, int x)
	{
		description=desc;
		itemsInLocation=theseItems;
		up=y;
		across=x;
	}
	
	public int getX()
	{
		return across;
	}
	
	public int getY()
	{
		return up;
	}
	
	public boolean isItemInLocation(String name)
	{
		for(int k=0;k<itemsInLocation.size();k++)
		{
			if((itemsInLocation.get(k).getName()).equalsIgnoreCase(name))
			{
				BobHoward.addItem(itemsInLocation.get(k));
				itemsInLocation.remove(k);
				return true;
			}
		}
		return false;
	}
	
	public void printDesc()
	{
		System.out.println(description);
		return;
	}
}


public class InitLocations
{
	public static LocationData[][]greenSkyLocs=new LocationData[2][2];

	public void addFirstLocs()
	{
		ArrayList<Items>shrubItems=null;
		Items CD=new Items("Shrub", "A blank disc, or at least, nothing you would want to know about anyway.\nIt has a Black Sabbath cover.");
		ArrayList<Items>cubicleItems=new ArrayList<Items>();
		cubicleItems.add(CD);
		LocationData shrub=new LocationData("The shrubbery, outside the offices of Memetix(UK)Ltd.,\na subsidiary of a Menlo Park, California, based multinational. It is\ncurrently drizzling.",shrubItems,1,1);
		greenSkyLocs[1][1]=shrub;
		LocationData cubicle=new LocationData("A typical cubicle h***. Beige partitions, photocopier looming like an altar\nbeneath a wall covered with devotional scriptures--the company's code of\nconduct. The cubicle you are interested in has several Dilbert cartoons pinned\nto the wall, a sign of mild rebellion.\nVarious books (Knuth, Dijkstra, Al-Hazred) are scattered about.",cubicleItems,1,0);
		greenSkyLocs[1][0]=cubicle;
	}
}


Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Text Based Game In Java Applet

Posted 25 May 2008 - 07:24 PM

What came first: the hen or the egg ?

The constructor of TextDemo() creates a Story object
The constructor of Story() needs a TextDemo

public class Story
{
	GamePlayer game=new GamePlayer();
	StorySegments a=new StorySegments();
	InitLocations init=new InitLocations();
	BobHoward b=new BobHoward();
	String input = TextDemo.getInput();   // <--------------------



public class TextDemo extends JPanel implements ActionListener {
	public static String input;
	public static JTextField textField;
	public static JTextArea textArea;
	private final static String newline = "\n";
	public static GamePlayer game = new GamePlayer();
	public Story story = new Story();   // <-----------------------------


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1